{"accepted_answer": {"answer_html": "
Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.
\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into "main" effects and pure interaction? If you fit the model as
\nm2 <- gam(\n y ~ s(subject, bs = "re") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = "REML"\n)\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.
\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the "main" effect of $z$) is doing is pulling the interaction surface up or down a bit.
\n", "answer_id": 676825, "answer_text": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.\n\n\n\n\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into \"main\" effects and pure interaction? If you fit the model as\n\n\n\n\nm2 <- gam(\n y ~ s(subject, bs = \"re\") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = \"REML\"\n)\n\n\n\n\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.\n\n\n\n\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the \"main\" effect of $z$) is doing is pulling the interaction surface up or down a bit.", "answer_url": "https://stats.stackexchange.com/a/676825", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-10T13:46: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": 676821, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-10T13:46:19+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "F2BC6152-84F6-49C2-A240-5C8FBED68528", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F2BC6152-84F6-49C2-A240-5C8FBED68528/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-10T14:27:48+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "49FD277A-D37F-425E-AE90-F3246031F5A9", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49FD277A-D37F-425E-AE90-F3246031F5A9/view-source"}], "score": 3, "updated_at": "2026-08-10T14:27:48+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "\nm <- gam(y ~ s(time) + s(subject, bs = \"re\") + s(z) + ti(time, z), data = dat)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676821, "sha256": "26b22c75d5bb179af3f2834caa82225c7019e801c4737401abbe51f12f71a0af", "source_url": "https://stats.stackexchange.com/questions/676821/should-a-covariates-main-effect-be-dropped-when-its-totally-confounded-concur"}, {"block_index": 1, "code_text": "library(mgcv)\nset.seed(1)\n\nn_subject <- 150\nn_visit <- 6\ntime_seq <- seq(0, 10, length.out = n_visit)\n\nz <- rnorm(n_subject)\nsubject_effect <- rnorm(n_subject, sd = 2)\n\ndat <- do.call(rbind, lapply(seq_len(n_subject), function(i) {\n y <- 5 + sqrt(time_seq) + subject_effect[i] + 0.5*z[i] + 0.3*z[i]*time_seq/10 + rnorm(n_visit, sd = 0.5)\n data.frame(subject = i, time = time_seq, y = y, z = z[i])\n}))\ndat$subject <- factor(dat$subject)\n\nm <- gam(y ~ s(time, k = 5) + s(subject, bs = \"re\") + s(z, k = 8) + ti(time, z, k = c(4,4)), data = dat)\nround(concurvity(m, full = FALSE)$estimate, 3)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676821, "sha256": "bbec1ef160e17f38db311ea10d2a766fc7f04eb5dc7ff5b70bcf557a69383b95", "source_url": "https://stats.stackexchange.com/questions/676821/should-a-covariates-main-effect-be-dropped-when-its-totally-confounded-concur"}, {"block_index": 0, "code_text": "m2 <- gam(\n y ~ s(subject, bs = \"re\") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = \"REML\"\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676825, "sha256": "d85eb81e68d8cddcd5c8461d048625abd5d44fc3710f416fc52b5b7acd084030", "source_url": "https://stats.stackexchange.com/a/676825"}], "other_answers": [], "product": "code_qa", "question": "I have repeated-measures data — multiple observations per subject over time — and a covariate that is constant within subject (e.g., a baseline characteristic measured once). My model includes a subject-level random intercept and I want to test whether this covariate's association with the outcome changes over time.\n\n\n\n\n\nm <- gam(y ~ s(time) + s(subject, bs = \"re\") + s(z) + ti(time, z), data = dat)\n\n\n\n\n\nconcurvity(m, full = FALSE)$estimate shows s(subject) and s(z) (z's own main effect) at 1.000 in one direction, confirming total non-identifiability — since z has zero within-subject variation, s(subject, bs=\"re\") can fully reproduce whatever flat contribution s(z) would estimate.\n\n\n\n\nMy current approach is to drop s(z) entirely and keep only ti(time, z), on the reasoning that ti()'s own identifiability constraints make it self-contained regardless of whether the (non-identifiable) main effect is present — interpreting the retained term as \"how the association between z and y changes over time,\" while treating any claim about z's flat/average association as unrecoverable given this random-effect structure.\n\n\n\n\nReproducible example:\n\n\n\n\nlibrary(mgcv)\nset.seed(1)\n\nn_subject <- 150\nn_visit <- 6\ntime_seq <- seq(0, 10, length.out = n_visit)\n\nz <- rnorm(n_subject)\nsubject_effect <- rnorm(n_subject, sd = 2)\n\ndat <- do.call(rbind, lapply(seq_len(n_subject), function(i) {\n y <- 5 + sqrt(time_seq) + subject_effect[i] + 0.5*z[i] + 0.3*z[i]*time_seq/10 + rnorm(n_visit, sd = 0.5)\n data.frame(subject = i, time = time_seq, y = y, z = z[i])\n}))\ndat$subject <- factor(dat$subject)\n\nm <- gam(y ~ s(time, k = 5) + s(subject, bs = \"re\") + s(z, k = 8) + ti(time, z, k = c(4,4)), data = dat)\nround(concurvity(m, full = FALSE)$estimate, 3)\n\n\n\n\n\nQuestions:\n\n\n\n\n\nIs dropping z's main effect while retaining ti(time, z) a way to handle this, or is there a better-established approach?\n\n\n\n\nDoes ti(time, z)'s own estimate depend in any way on whether the non-identifiable main effect is included or excluded from the model?\n\n\n\n\n\nMany thanks", "record_id": "Scientific-Code-and-Analysis-QA:stats:676821", "selected_answer": {"answer_html": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.
\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into "main" effects and pure interaction? If you fit the model as
\nm2 <- gam(\n y ~ s(subject, bs = "re") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = "REML"\n)\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.
\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the "main" effect of $z$) is doing is pulling the interaction surface up or down a bit.
\n", "answer_id": 676825, "answer_text": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.\n\n\n\n\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into \"main\" effects and pure interaction? If you fit the model as\n\n\n\n\nm2 <- gam(\n y ~ s(subject, bs = \"re\") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = \"REML\"\n)\n\n\n\n\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.\n\n\n\n\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the \"main\" effect of $z$) is doing is pulling the interaction surface up or down a bit.", "answer_url": "https://stats.stackexchange.com/a/676825", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-10T13:46: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": 676821, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-10T13:46:19+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "F2BC6152-84F6-49C2-A240-5C8FBED68528", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F2BC6152-84F6-49C2-A240-5C8FBED68528/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-10T14:27:48+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "49FD277A-D37F-425E-AE90-F3246031F5A9", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49FD277A-D37F-425E-AE90-F3246031F5A9/view-source"}], "score": 3, "updated_at": "2026-08-10T14:27:48+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 676825, "answers": [{"answer_html": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.
\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into "main" effects and pure interaction? If you fit the model as
\nm2 <- gam(\n y ~ s(subject, bs = "re") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = "REML"\n)\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.
\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the "main" effect of $z$) is doing is pulling the interaction surface up or down a bit.
\n", "answer_id": 676825, "answer_text": "Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.\n\n\n\n\nIn this instance, I don't see why you need to decompose the 2d function $f(\\text{time}, \\text{z})$ into \"main\" effects and pure interaction? If you fit the model as\n\n\n\n\nm2 <- gam(\n y ~ s(subject, bs = \"re\") +\n te(time, z, k = c(6,10)),\n data = dat,\n method = \"REML\"\n)\n\n\n\n\n\nyou get essentially the same fit without the concurvity issues and with fewer smoothing parameters to estimate to boot.\n\n\n\n\nI wouldn't worry about the concurvity in your decomposed model; that a flat function is concurved with the random intercepts isn't an issue because it doesn't affect the estimated terms. All that $f^{*}(\\text{z})$ (the \"main\" effect of $z$) is doing is pulling the interaction surface up or down a bit.", "answer_url": "https://stats.stackexchange.com/a/676825", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-10T13:46: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": 676821, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-10T13:46:19+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "F2BC6152-84F6-49C2-A240-5C8FBED68528", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F2BC6152-84F6-49C2-A240-5C8FBED68528/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-10T14:27:48+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "49FD277A-D37F-425E-AE90-F3246031F5A9", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49FD277A-D37F-425E-AE90-F3246031F5A9/view-source"}], "score": 3, "updated_at": "2026-08-10T14:27:48+00:00"}], "domain": "statistics", "external_links": [], "medical_sensitive": false, "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": "Elara", "question_author_url": "https://stats.stackexchange.com/users/515316/elara", "question_author_user_type": "registered", "question_created_at": "2026-08-10T10:16:49+00:00", "question_html": "I have repeated-measures data — multiple observations per subject over time — and a covariate that is constant within subject (e.g., a baseline characteristic measured once). My model includes a subject-level random intercept and I want to test whether this covariate's association with the outcome changes over time.
\n\nm <- gam(y ~ s(time) + s(subject, bs = "re") + s(z) + ti(time, z), data = dat)\n\nconcurvity(m, full = FALSE)$estimate shows s(subject) and s(z) (z's own main effect) at 1.000 in one direction, confirming total non-identifiability — since z has zero within-subject variation, s(subject, bs="re") can fully reproduce whatever flat contribution s(z) would estimate.
\nMy current approach is to drop s(z) entirely and keep only ti(time, z), on the reasoning that ti()'s own identifiability constraints make it self-contained regardless of whether the (non-identifiable) main effect is present — interpreting the retained term as "how the association between z and y changes over time," while treating any claim about z's flat/average association as unrecoverable given this random-effect structure.
\nReproducible example:
\nlibrary(mgcv)\nset.seed(1)\n\nn_subject <- 150\nn_visit <- 6\ntime_seq <- seq(0, 10, length.out = n_visit)\n\nz <- rnorm(n_subject)\nsubject_effect <- rnorm(n_subject, sd = 2)\n\ndat <- do.call(rbind, lapply(seq_len(n_subject), function(i) {\n y <- 5 + sqrt(time_seq) + subject_effect[i] + 0.5*z[i] + 0.3*z[i]*time_seq/10 + rnorm(n_visit, sd = 0.5)\n data.frame(subject = i, time = time_seq, y = y, z = z[i])\n}))\ndat$subject <- factor(dat$subject)\n\nm <- gam(y ~ s(time, k = 5) + s(subject, bs = "re") + s(z, k = 8) + ti(time, z, k = c(4,4)), data = dat)\nround(concurvity(m, full = FALSE)$estimate, 3)\n\nQuestions:
\nMany thanks
\n", "question_id": 676821, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I have repeated-measures data — multiple observations per subject over time — and a covariate that is constant within subject (e.g., a baseline characteristic measured once). My model includes a subject-level random intercept and I want to test whether this covariate's association with the outcome changes over time.\n\n\n\n\n\nm <- gam(y ~ s(time) + s(subject, bs = \"re\") + s(z) + ti(time, z), data = dat)\n\n\n\n\n\nconcurvity(m, full = FALSE)$estimate shows s(subject) and s(z) (z's own main effect) at 1.000 in one direction, confirming total non-identifiability — since z has zero within-subject variation, s(subject, bs=\"re\") can fully reproduce whatever flat contribution s(z) would estimate.\n\n\n\n\nMy current approach is to drop s(z) entirely and keep only ti(time, z), on the reasoning that ti()'s own identifiability constraints make it self-contained regardless of whether the (non-identifiable) main effect is present — interpreting the retained term as \"how the association between z and y changes over time,\" while treating any claim about z's flat/average association as unrecoverable given this random-effect structure.\n\n\n\n\nReproducible example:\n\n\n\n\nlibrary(mgcv)\nset.seed(1)\n\nn_subject <- 150\nn_visit <- 6\ntime_seq <- seq(0, 10, length.out = n_visit)\n\nz <- rnorm(n_subject)\nsubject_effect <- rnorm(n_subject, sd = 2)\n\ndat <- do.call(rbind, lapply(seq_len(n_subject), function(i) {\n y <- 5 + sqrt(time_seq) + subject_effect[i] + 0.5*z[i] + 0.3*z[i]*time_seq/10 + rnorm(n_visit, sd = 0.5)\n data.frame(subject = i, time = time_seq, y = y, z = z[i])\n}))\ndat$subject <- factor(dat$subject)\n\nm <- gam(y ~ s(time, k = 5) + s(subject, bs = \"re\") + s(z, k = 8) + ti(time, z, k = c(4,4)), data = dat)\nround(concurvity(m, full = FALSE)$estimate, 3)\n\n\n\n\n\nQuestions:\n\n\n\n\n\nIs dropping z's main effect while retaining ti(time, z) a way to handle this, or is there a better-established approach?\n\n\n\n\nDoes ti(time, z)'s own estimate depend in any way on whether the non-identifiable main effect is included or excluded from the model?\n\n\n\n\n\nMany thanks", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Elara", "profile_url": "https://stats.stackexchange.com/users/515316/elara", "user_type": "registered"}, "created_at": "2026-08-10T10:16:49+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "E53E485F-D0B2-4D71-A71D-49FBF67B610C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E53E485F-D0B2-4D71-A71D-49FBF67B610C/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-10T18:21:03+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "87843E03-0788-44C4-AC39-D6D27DF85636", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/87843E03-0788-44C4-AC39-D6D27DF85636/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676821/should-a-covariates-main-effect-be-dropped-when-its-totally-confounded-concur", "split": "train", "split_group": "a67c79324cd462d3f9e765754df2a7a00495b44528883bd5734192a2b6a73ff1", "tags": ["interaction", "generalized-additive-model", "mgcv", "identifiability", "concurvity"], "thread_id": "stats:676821", "title": "Should a covariate's main effect be dropped when it's totally confounded (concurvity = 1) with a random intercept in a repeated-measures GAMM?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676851, "sha256": "8fb2dac783667ca934aace318bc1d59d4d831af318b2b8cc2e7524964863b77a", "source_url": "https://stats.stackexchange.com/a/676851"}, {"block_index": 2, "code_text": "set.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676851, "sha256": "0a411abb79864630d059298e04f1470aba7ba285a921cba1d89b9c7066255849", "source_url": "https://stats.stackexchange.com/a/676851"}], "other_answers": [], "product": "code_qa", "question": "The following is a multivariate Student's t distribution\n$$ p_{\\sigma^2}(\\mathrm{x})= {\\displaystyle {N_{\\nu,\\sigma^2}}\\left[1+\\frac{1}{\\nu\\sigma^2}\\sum_{i=1}^nx_i^2\\right]^{-(\\nu +n)/2}}, \\;\\mathrm{x}=[x_1,\\cdots,x_n]^{\\top}\\in \\mathbb{R}^n,\\;\\nu>2,$$ where $N_{\\nu,\\sigma^2}=\\frac {\\Gamma \\left[(\\nu +n)/2\\right]}{\\Gamma (\\nu /2)\\nu ^{n/2} \\pi^{n/2}{\\sigma}^{n}}.$ I am struggling to find the higher-order moments $E[X^{\\top}X]$, $E[X^{\\top}X(X^{\\top}X)^{\\top}]$. Is there a way to get these quantities?", "record_id": "Scientific-Code-and-Analysis-QA:stats:676824", "selected_answer": {"answer_html": "I offer an elementary solution. It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.
\nThere are other solutions that might provide simpler formulas but are less elementary (e.g., use cylindrical coordinates).
\nBecause $\\sqrt{\\nu}\\sigma$ evidently is a scale parameter we can ignore it (for now), leaving everything to depend on the number of variables $n$ and the parameter $\\nu.$ Writing $\\mathbf x = (x_1, x_2, \\ldots, x_n),$ let the density be
\n$$p(\\mathbf x;\\nu) = \\frac{\\Gamma\\left(\\frac{\\nu + n}{2}\\right)}{\\Gamma\\left(\\frac{\\nu}{2}\\right)\\pi^{n/2}} \\left(1 + \\sum_{i=1}^n x_i^2\\right)^{-(\\nu + n)/2} = \\frac{1}{C(\\nu, n)}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}.$$
\nThe moment of degree $\\mathbf k = (k_1, k_2, \\ldots, k_n)$ is, by definition,
\n$$\\mu(\\mathbf k; \\nu) = \\int \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\int_{-\\infty}^{\\infty}\\cdots\\int_{-\\infty}^{\\infty} x_1^{k_1}x_2^{k_2}\\cdots x_n^{k_n} p(\\mathbf x;\\nu)\\,\\mathrm dx_1\\mathrm dx_2\\cdots \\mathrm dx_n.$$
\nBecause $p$ depends only on the squares $x_i^2,$ it is an even function of all the variables. Consequently (implicitly assuming $\\mu(\\mathbf k;\\nu)$ exists),
\n\n\nwhenever any $k_i$ is an odd integer, $\\mu(\\mathbf k;\\nu) = 0.$
\n
Otherwise, when all the $k_i$ are even integers, we may integrate over positive $x_i$ only and double the result. Doing this for all $n$ variables gives
\n$$\\mu(\\mathbf k; \\nu) = 2^n\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\frac{2^n}{C(\\nu,n)}\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} \\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu+n)/2}\\,\\mathrm d\\mathbf x$$
\nThe question comes down to computing the integral on the right hand side. It deserves a name; let's call it
\n$$f(\\mathbf k;\\nu) = C(\\nu,n)\\mu(\\mathbf k;\\nu) = 2^n\\int \\mathbf x^{\\mathbf k}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}\\,\\mathrm d\\mathbf x,$$
\nwhere from now on the integral is understood as encompassing all non-negative values of the $x_i.$
\nOne way to evaluate such integrals is to integrate one variable at a time. To this end, set $y^2 = 1 + x_1^2 + \\cdots + x_{n-1}^2 = 1 + ||\\mathbf x_{\\hat n}||^2$ (with $y\\ge 0$). The notation $\\mathbf x_{\\hat n}$ means the component $x_n$ is omitted. Substituting $u = (x/y)^2$ shows
\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k} \\left(y^2 + x^2\\right)^{-\\alpha/2} \\,\\mathrm dx &= y^{k +1 - \\alpha}\\int_0^\\infty u^{(k-1)/2}\\left(1 + u\\right)^{-\\alpha/2} \\,\\mathrm du\\\\\n& = \\left(y^2\\right)^{-(\\alpha - k - 1)/2}\\,B\\left(\\frac{k+1}{2}, \\frac{\\alpha-k-1}{2}\\right)\n\\end{aligned}$$
\n(a Beta function, arising e.g. from normalizing a Beta prime distribution).
\nApplying this in the case $\\alpha = \\nu + n$ and $k = k_n$ says
\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k_n} \\left(y^2 + x^2\\right)^{-(\\nu + n)/2} \\,\\mathrm dx = \\left(y^2\\right)^{-(\\nu - k_n + (n - 1))/2}\\,B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right)\n\\end{aligned}$$
\nPerforming the remaining integration over $(x_1, x_2, \\ldots, x_{n-1}) = \\mathbf x_{\\hat n}$ shows
\n$$f(\\mathbf k;\\nu) = f(\\mathbf k_{\\hat n};\\, \\nu - k_n)B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right).$$
\nIterating from $i = n$ down to $1$ decreases $n$ by $1$ at each step and decreases $\\nu$ by $k_i$ for the next step, whence
\n\n\n$$f(\\mathbf{k};\\,\\nu) = \\prod_{i=1}^n B\\left(\\frac{k_i+1}{2}, \\frac{\\nu - (k_i + k_{i+1} + \\cdots + k_n) + i - 1}{2}\\right).$$
\n
(Although this can be simplified using basic properties of Gamma functions, it is good enough for computation and analysis.)
\nAs a check, we recover the normalizing constant as the zeroth moment,
\n$$\\begin{aligned}\n C(\\nu, n) &= f((0,\\ldots,0);\\, n) \\\\\n&=\\prod_{i=1}^n B\\left(\\frac{0+1}{2}, \\frac{\\nu - 0 + (i-1)}{2}\\right)\\\\\n&=\\prod_{i=1}^n \\frac{\\Gamma\\left(\\frac{0+1}{2}\\right)\\Gamma\\left(\\frac{\\nu - 0 + (i-1)}{2}\\right)}{\\Gamma\\left(\\frac{\\nu + (i-1) + 1}{2}\\right)}\\\\\n&= \\frac{\\Gamma\\left(\\frac{1}{2}\\right)^n \\Gamma\\left(\\frac{\\nu}{2}\\right)}{\\Gamma\\left(\\frac{\\nu+n}{2}\\right)}.\n\\end{aligned}$$
\nThis agrees with the value quoted in the question, since $\\Gamma(1/2)=\\sqrt{\\pi}.$
\nFinally, recall that a scale parameter $\\tau$ multiplies each variable $x_i$ by $\\tau,$ whence it multiplies the moment of order $\\mathbf k$ by $\\tau(k_1+k_2+\\cdots+k_n).$ Writing
\n$$\\kappa = k_1+k_2+\\cdots+k_n$$
\nand recalling the scale parameter is $\\tau = \\sqrt{\\nu}\\sigma$ shows that
\n\n\n$$\\mu(\\mathbf k;\\,\\nu,\\sigma) = \\frac{\\nu^{\\kappa/2}\\sigma^\\kappa f(\\mathbf k;\\,\\nu)}{C(\\nu, n)}.$$
\n
The question concerns linear combinations of moments of order $4$ ($\\kappa = 4$). Computing the coefficients--which is merely a matter of multiplying the matrices--is of no interest here.
\nTo maintain precision and avoid numerical overflow, it is best to compute products of Beta functions using logarithms. Here is an example of how that's done in R, using its built-in lbeta (logarithm of Beta) function.
#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n\nThe sum and cumsum functions require only $O(n)$ computational effort and storage.
For example, the $(0,1,2,3)$ moment with $\\nu=12$ is found as
\n> mu(c(0,1,2,3), 12, 1)\n[1] 4.583662\n\nAs a test, I generated datasets of one million iid observations from multivariate $t$ distributions (using the mnormt package) and compared the sample moments (for various $\\mathbf k$) to the formula:
set.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n\nThe output, equal to $1.012$ in this example, ideally would be $1,$ indicating perfect agreement. But $t$ distributions, especially for smallish $\\nu,$ are rather heavy-tailed, resulting in very high sampling variances for the higher moments (this one is of order $\\kappa = 0+1+2=3$). In light of this, $1.012$ is excellent agreement.
\nThe output of additional tests continues to support the conclusion that the formulas for $f$ and $\\mu$ are correct.
\n", "answer_id": 676851, "answer_text": "I offer an elementary solution. It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.\n\n\n\n\nThere are other solutions that might provide simpler formulas but are less elementary (e.g., use cylindrical coordinates).\n\n\n\n\nInitial simplification\n\n\n\n\nBecause $\\sqrt{\\nu}\\sigma$ evidently is a scale parameter we can ignore it (for now), leaving everything to depend on the number of variables $n$ and the parameter $\\nu.$ Writing $\\mathbf x = (x_1, x_2, \\ldots, x_n),$ let the density be\n\n\n\n\n$$p(\\mathbf x;\\nu) = \\frac{\\Gamma\\left(\\frac{\\nu + n}{2}\\right)}{\\Gamma\\left(\\frac{\\nu}{2}\\right)\\pi^{n/2}} \\left(1 + \\sum_{i=1}^n x_i^2\\right)^{-(\\nu + n)/2} = \\frac{1}{C(\\nu, n)}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}.$$\n\n\n\n\nThe moment of degree $\\mathbf k = (k_1, k_2, \\ldots, k_n)$ is, by definition,\n\n\n\n\n$$\\mu(\\mathbf k; \\nu) = \\int \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\int_{-\\infty}^{\\infty}\\cdots\\int_{-\\infty}^{\\infty} x_1^{k_1}x_2^{k_2}\\cdots x_n^{k_n} p(\\mathbf x;\\nu)\\,\\mathrm dx_1\\mathrm dx_2\\cdots \\mathrm dx_n.$$\n\n\n\n\nBecause $p$ depends only on the squares $x_i^2,$ it is an even function of all the variables. Consequently (implicitly assuming $\\mu(\\mathbf k;\\nu)$ exists),\n\n\n\n\n\n\n\nwhenever any $k_i$ is an odd integer, $\\mu(\\mathbf k;\\nu) = 0.$\n\n\n\n\n\n\n\nOtherwise, when all the $k_i$ are even integers, we may integrate over positive $x_i$ only and double the result. Doing this for all $n$ variables gives\n\n\n\n\n$$\\mu(\\mathbf k; \\nu) = 2^n\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\frac{2^n}{C(\\nu,n)}\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} \\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu+n)/2}\\,\\mathrm d\\mathbf x$$\n\n\n\n\nThe question comes down to computing the integral on the right hand side. It deserves a name; let's call it\n\n\n\n\n$$f(\\mathbf k;\\nu) = C(\\nu,n)\\mu(\\mathbf k;\\nu) = 2^n\\int \\mathbf x^{\\mathbf k}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}\\,\\mathrm d\\mathbf x,$$\n\n\n\n\nwhere from now on the integral is understood as encompassing all non-negative values of the $x_i.$\n\n\n\n\nThe key formula\n\n\n\n\nOne way to evaluate such integrals is to integrate one variable at a time. To this end, set $y^2 = 1 + x_1^2 + \\cdots + x_{n-1}^2 = 1 + ||\\mathbf x_{\\hat n}||^2$ (with $y\\ge 0$). The notation $\\mathbf x_{\\hat n}$ means the component $x_n$ is omitted. Substituting $u = (x/y)^2$ shows\n\n\n\n\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k} \\left(y^2 + x^2\\right)^{-\\alpha/2} \\,\\mathrm dx &= y^{k +1 - \\alpha}\\int_0^\\infty u^{(k-1)/2}\\left(1 + u\\right)^{-\\alpha/2} \\,\\mathrm du\\\\\n& = \\left(y^2\\right)^{-(\\alpha - k - 1)/2}\\,B\\left(\\frac{k+1}{2}, \\frac{\\alpha-k-1}{2}\\right)\n\\end{aligned}$$\n\n\n\n\n(a Beta function, arising e.g. from normalizing a Beta prime distribution (https://en.wikipedia.org/wiki/Beta_prime_distribution#Generalization)).\n\n\n\n\nApplying this in the case $\\alpha = \\nu + n$ and $k = k_n$ says\n\n\n\n\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k_n} \\left(y^2 + x^2\\right)^{-(\\nu + n)/2} \\,\\mathrm dx = \\left(y^2\\right)^{-(\\nu - k_n + (n - 1))/2}\\,B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right)\n\\end{aligned}$$\n\n\n\n\nPerforming the remaining integration over $(x_1, x_2, \\ldots, x_{n-1}) = \\mathbf x_{\\hat n}$ shows\n\n\n\n\n$$f(\\mathbf k;\\nu) = f(\\mathbf k_{\\hat n};\\, \\nu - k_n)B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right).$$\n\n\n\n\nIterating from $i = n$ down to $1$ decreases $n$ by $1$ at each step and decreases $\\nu$ by $k_i$ for the next step, whence\n\n\n\n\n\n\n\n$$f(\\mathbf{k};\\,\\nu) = \\prod_{i=1}^n B\\left(\\frac{k_i+1}{2}, \\frac{\\nu - (k_i + k_{i+1} + \\cdots + k_n) + i - 1}{2}\\right).$$\n\n\n\n\n\n\n\n(Although this can be simplified using basic properties of Gamma functions, it is good enough for computation and analysis.)\n\n\n\n\nAs a check, we recover the normalizing constant as the zeroth moment,\n\n\n\n\n$$\\begin{aligned}\n C(\\nu, n) &= f((0,\\ldots,0);\\, n) \\\\\n&=\\prod_{i=1}^n B\\left(\\frac{0+1}{2}, \\frac{\\nu - 0 + (i-1)}{2}\\right)\\\\\n&=\\prod_{i=1}^n \\frac{\\Gamma\\left(\\frac{0+1}{2}\\right)\\Gamma\\left(\\frac{\\nu - 0 + (i-1)}{2}\\right)}{\\Gamma\\left(\\frac{\\nu + (i-1) + 1}{2}\\right)}\\\\\n&= \\frac{\\Gamma\\left(\\frac{1}{2}\\right)^n \\Gamma\\left(\\frac{\\nu}{2}\\right)}{\\Gamma\\left(\\frac{\\nu+n}{2}\\right)}.\n\\end{aligned}$$\n\n\n\n\nThis agrees with the value quoted in the question, since $\\Gamma(1/2)=\\sqrt{\\pi}.$\n\n\n\n\nFinally, recall that a scale parameter $\\tau$ multiplies each variable $x_i$ by $\\tau,$ whence it multiplies the moment of order $\\mathbf k$ by $\\tau(k_1+k_2+\\cdots+k_n).$ Writing\n\n\n\n\n$$\\kappa = k_1+k_2+\\cdots+k_n$$\n\n\n\n\nand recalling the scale parameter is $\\tau = \\sqrt{\\nu}\\sigma$ shows that\n\n\n\n\n\n\n\n$$\\mu(\\mathbf k;\\,\\nu,\\sigma) = \\frac{\\nu^{\\kappa/2}\\sigma^\\kappa f(\\mathbf k;\\,\\nu)}{C(\\nu, n)}.$$\n\n\n\n\n\n\n\nThe question concerns linear combinations of moments of order $4$ ($\\kappa = 4$). Computing the coefficients--which is merely a matter of multiplying the matrices--is of no interest here.\n\n\n\n\nImplementation and testing\n\n\n\n\nTo maintain precision and avoid numerical overflow, it is best to compute products of Beta functions using logarithms. Here is an example of how that's done in R, using its built-in lbeta (logarithm of Beta) function.\n\n\n\n\n#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n\n\n\n\n\nThe sum and cumsum functions require only $O(n)$ computational effort and storage.\n\n\n\n\nFor example, the $(0,1,2,3)$ moment with $\\nu=12$ is found as\n\n\n\n\n> mu(c(0,1,2,3), 12, 1)\n[1] 4.583662\n\n\n\n\n\nAs a test, I generated datasets of one million iid observations from multivariate $t$ distributions (using the mnormt package) and compared the sample moments (for various $\\mathbf k$) to the formula:\n\n\n\n\nset.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n\n\n\n\n\nThe output, equal to $1.012$ in this example, ideally would be $1,$ indicating perfect agreement. But $t$ distributions, especially for smallish $\\nu,$ are rather heavy-tailed, resulting in very high sampling variances for the higher moments (this one is of order $\\kappa = 0+1+2=3$). In light of this, $1.012$ is excellent agreement.\n\n\n\n\nThe output of additional tests continues to support the conclusion that the formulas for $f$ and $\\mu$ are correct.", "answer_url": "https://stats.stackexchange.com/a/676851", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T15:28:16+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": 676824, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-08-12T15:28:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "C9CDAB77-2DD2-446E-837A-211128FD0EE9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C9CDAB77-2DD2-446E-837A-211128FD0EE9/view-source"}], "score": 2, "updated_at": "2026-08-12T15:28:16+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "I offer an elementary solution. It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.
\nThere are other solutions that might provide simpler formulas but are less elementary (e.g., use cylindrical coordinates).
\nBecause $\\sqrt{\\nu}\\sigma$ evidently is a scale parameter we can ignore it (for now), leaving everything to depend on the number of variables $n$ and the parameter $\\nu.$ Writing $\\mathbf x = (x_1, x_2, \\ldots, x_n),$ let the density be
\n$$p(\\mathbf x;\\nu) = \\frac{\\Gamma\\left(\\frac{\\nu + n}{2}\\right)}{\\Gamma\\left(\\frac{\\nu}{2}\\right)\\pi^{n/2}} \\left(1 + \\sum_{i=1}^n x_i^2\\right)^{-(\\nu + n)/2} = \\frac{1}{C(\\nu, n)}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}.$$
\nThe moment of degree $\\mathbf k = (k_1, k_2, \\ldots, k_n)$ is, by definition,
\n$$\\mu(\\mathbf k; \\nu) = \\int \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\int_{-\\infty}^{\\infty}\\cdots\\int_{-\\infty}^{\\infty} x_1^{k_1}x_2^{k_2}\\cdots x_n^{k_n} p(\\mathbf x;\\nu)\\,\\mathrm dx_1\\mathrm dx_2\\cdots \\mathrm dx_n.$$
\nBecause $p$ depends only on the squares $x_i^2,$ it is an even function of all the variables. Consequently (implicitly assuming $\\mu(\\mathbf k;\\nu)$ exists),
\n\n\nwhenever any $k_i$ is an odd integer, $\\mu(\\mathbf k;\\nu) = 0.$
\n
Otherwise, when all the $k_i$ are even integers, we may integrate over positive $x_i$ only and double the result. Doing this for all $n$ variables gives
\n$$\\mu(\\mathbf k; \\nu) = 2^n\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\frac{2^n}{C(\\nu,n)}\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} \\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu+n)/2}\\,\\mathrm d\\mathbf x$$
\nThe question comes down to computing the integral on the right hand side. It deserves a name; let's call it
\n$$f(\\mathbf k;\\nu) = C(\\nu,n)\\mu(\\mathbf k;\\nu) = 2^n\\int \\mathbf x^{\\mathbf k}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}\\,\\mathrm d\\mathbf x,$$
\nwhere from now on the integral is understood as encompassing all non-negative values of the $x_i.$
\nOne way to evaluate such integrals is to integrate one variable at a time. To this end, set $y^2 = 1 + x_1^2 + \\cdots + x_{n-1}^2 = 1 + ||\\mathbf x_{\\hat n}||^2$ (with $y\\ge 0$). The notation $\\mathbf x_{\\hat n}$ means the component $x_n$ is omitted. Substituting $u = (x/y)^2$ shows
\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k} \\left(y^2 + x^2\\right)^{-\\alpha/2} \\,\\mathrm dx &= y^{k +1 - \\alpha}\\int_0^\\infty u^{(k-1)/2}\\left(1 + u\\right)^{-\\alpha/2} \\,\\mathrm du\\\\\n& = \\left(y^2\\right)^{-(\\alpha - k - 1)/2}\\,B\\left(\\frac{k+1}{2}, \\frac{\\alpha-k-1}{2}\\right)\n\\end{aligned}$$
\n(a Beta function, arising e.g. from normalizing a Beta prime distribution).
\nApplying this in the case $\\alpha = \\nu + n$ and $k = k_n$ says
\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k_n} \\left(y^2 + x^2\\right)^{-(\\nu + n)/2} \\,\\mathrm dx = \\left(y^2\\right)^{-(\\nu - k_n + (n - 1))/2}\\,B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right)\n\\end{aligned}$$
\nPerforming the remaining integration over $(x_1, x_2, \\ldots, x_{n-1}) = \\mathbf x_{\\hat n}$ shows
\n$$f(\\mathbf k;\\nu) = f(\\mathbf k_{\\hat n};\\, \\nu - k_n)B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right).$$
\nIterating from $i = n$ down to $1$ decreases $n$ by $1$ at each step and decreases $\\nu$ by $k_i$ for the next step, whence
\n\n\n$$f(\\mathbf{k};\\,\\nu) = \\prod_{i=1}^n B\\left(\\frac{k_i+1}{2}, \\frac{\\nu - (k_i + k_{i+1} + \\cdots + k_n) + i - 1}{2}\\right).$$
\n
(Although this can be simplified using basic properties of Gamma functions, it is good enough for computation and analysis.)
\nAs a check, we recover the normalizing constant as the zeroth moment,
\n$$\\begin{aligned}\n C(\\nu, n) &= f((0,\\ldots,0);\\, n) \\\\\n&=\\prod_{i=1}^n B\\left(\\frac{0+1}{2}, \\frac{\\nu - 0 + (i-1)}{2}\\right)\\\\\n&=\\prod_{i=1}^n \\frac{\\Gamma\\left(\\frac{0+1}{2}\\right)\\Gamma\\left(\\frac{\\nu - 0 + (i-1)}{2}\\right)}{\\Gamma\\left(\\frac{\\nu + (i-1) + 1}{2}\\right)}\\\\\n&= \\frac{\\Gamma\\left(\\frac{1}{2}\\right)^n \\Gamma\\left(\\frac{\\nu}{2}\\right)}{\\Gamma\\left(\\frac{\\nu+n}{2}\\right)}.\n\\end{aligned}$$
\nThis agrees with the value quoted in the question, since $\\Gamma(1/2)=\\sqrt{\\pi}.$
\nFinally, recall that a scale parameter $\\tau$ multiplies each variable $x_i$ by $\\tau,$ whence it multiplies the moment of order $\\mathbf k$ by $\\tau(k_1+k_2+\\cdots+k_n).$ Writing
\n$$\\kappa = k_1+k_2+\\cdots+k_n$$
\nand recalling the scale parameter is $\\tau = \\sqrt{\\nu}\\sigma$ shows that
\n\n\n$$\\mu(\\mathbf k;\\,\\nu,\\sigma) = \\frac{\\nu^{\\kappa/2}\\sigma^\\kappa f(\\mathbf k;\\,\\nu)}{C(\\nu, n)}.$$
\n
The question concerns linear combinations of moments of order $4$ ($\\kappa = 4$). Computing the coefficients--which is merely a matter of multiplying the matrices--is of no interest here.
\nTo maintain precision and avoid numerical overflow, it is best to compute products of Beta functions using logarithms. Here is an example of how that's done in R, using its built-in lbeta (logarithm of Beta) function.
#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n\nThe sum and cumsum functions require only $O(n)$ computational effort and storage.
For example, the $(0,1,2,3)$ moment with $\\nu=12$ is found as
\n> mu(c(0,1,2,3), 12, 1)\n[1] 4.583662\n\nAs a test, I generated datasets of one million iid observations from multivariate $t$ distributions (using the mnormt package) and compared the sample moments (for various $\\mathbf k$) to the formula:
set.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n\nThe output, equal to $1.012$ in this example, ideally would be $1,$ indicating perfect agreement. But $t$ distributions, especially for smallish $\\nu,$ are rather heavy-tailed, resulting in very high sampling variances for the higher moments (this one is of order $\\kappa = 0+1+2=3$). In light of this, $1.012$ is excellent agreement.
\nThe output of additional tests continues to support the conclusion that the formulas for $f$ and $\\mu$ are correct.
\n", "answer_id": 676851, "answer_text": "I offer an elementary solution. It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.\n\n\n\n\nThere are other solutions that might provide simpler formulas but are less elementary (e.g., use cylindrical coordinates).\n\n\n\n\nInitial simplification\n\n\n\n\nBecause $\\sqrt{\\nu}\\sigma$ evidently is a scale parameter we can ignore it (for now), leaving everything to depend on the number of variables $n$ and the parameter $\\nu.$ Writing $\\mathbf x = (x_1, x_2, \\ldots, x_n),$ let the density be\n\n\n\n\n$$p(\\mathbf x;\\nu) = \\frac{\\Gamma\\left(\\frac{\\nu + n}{2}\\right)}{\\Gamma\\left(\\frac{\\nu}{2}\\right)\\pi^{n/2}} \\left(1 + \\sum_{i=1}^n x_i^2\\right)^{-(\\nu + n)/2} = \\frac{1}{C(\\nu, n)}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}.$$\n\n\n\n\nThe moment of degree $\\mathbf k = (k_1, k_2, \\ldots, k_n)$ is, by definition,\n\n\n\n\n$$\\mu(\\mathbf k; \\nu) = \\int \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\int_{-\\infty}^{\\infty}\\cdots\\int_{-\\infty}^{\\infty} x_1^{k_1}x_2^{k_2}\\cdots x_n^{k_n} p(\\mathbf x;\\nu)\\,\\mathrm dx_1\\mathrm dx_2\\cdots \\mathrm dx_n.$$\n\n\n\n\nBecause $p$ depends only on the squares $x_i^2,$ it is an even function of all the variables. Consequently (implicitly assuming $\\mu(\\mathbf k;\\nu)$ exists),\n\n\n\n\n\n\n\nwhenever any $k_i$ is an odd integer, $\\mu(\\mathbf k;\\nu) = 0.$\n\n\n\n\n\n\n\nOtherwise, when all the $k_i$ are even integers, we may integrate over positive $x_i$ only and double the result. Doing this for all $n$ variables gives\n\n\n\n\n$$\\mu(\\mathbf k; \\nu) = 2^n\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} p(\\mathbf x;\\nu)\\,\\mathrm d\\mathbf x = \\frac{2^n}{C(\\nu,n)}\\int_{(0,\\ldots,0)}^{(\\infty,\\ldots,\\infty)} \\mathbf x^{\\mathbf k} \\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu+n)/2}\\,\\mathrm d\\mathbf x$$\n\n\n\n\nThe question comes down to computing the integral on the right hand side. It deserves a name; let's call it\n\n\n\n\n$$f(\\mathbf k;\\nu) = C(\\nu,n)\\mu(\\mathbf k;\\nu) = 2^n\\int \\mathbf x^{\\mathbf k}\\left(1 + ||\\mathbf x||^2\\right)^{-(\\nu + n)/2}\\,\\mathrm d\\mathbf x,$$\n\n\n\n\nwhere from now on the integral is understood as encompassing all non-negative values of the $x_i.$\n\n\n\n\nThe key formula\n\n\n\n\nOne way to evaluate such integrals is to integrate one variable at a time. To this end, set $y^2 = 1 + x_1^2 + \\cdots + x_{n-1}^2 = 1 + ||\\mathbf x_{\\hat n}||^2$ (with $y\\ge 0$). The notation $\\mathbf x_{\\hat n}$ means the component $x_n$ is omitted. Substituting $u = (x/y)^2$ shows\n\n\n\n\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k} \\left(y^2 + x^2\\right)^{-\\alpha/2} \\,\\mathrm dx &= y^{k +1 - \\alpha}\\int_0^\\infty u^{(k-1)/2}\\left(1 + u\\right)^{-\\alpha/2} \\,\\mathrm du\\\\\n& = \\left(y^2\\right)^{-(\\alpha - k - 1)/2}\\,B\\left(\\frac{k+1}{2}, \\frac{\\alpha-k-1}{2}\\right)\n\\end{aligned}$$\n\n\n\n\n(a Beta function, arising e.g. from normalizing a Beta prime distribution (https://en.wikipedia.org/wiki/Beta_prime_distribution#Generalization)).\n\n\n\n\nApplying this in the case $\\alpha = \\nu + n$ and $k = k_n$ says\n\n\n\n\n$$\\begin{aligned}\n2\\int_0^\\infty x^{k_n} \\left(y^2 + x^2\\right)^{-(\\nu + n)/2} \\,\\mathrm dx = \\left(y^2\\right)^{-(\\nu - k_n + (n - 1))/2}\\,B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right)\n\\end{aligned}$$\n\n\n\n\nPerforming the remaining integration over $(x_1, x_2, \\ldots, x_{n-1}) = \\mathbf x_{\\hat n}$ shows\n\n\n\n\n$$f(\\mathbf k;\\nu) = f(\\mathbf k_{\\hat n};\\, \\nu - k_n)B\\left(\\frac{k_n+1}{2}, \\frac{\\nu - k_n + (n-1)}{2}\\right).$$\n\n\n\n\nIterating from $i = n$ down to $1$ decreases $n$ by $1$ at each step and decreases $\\nu$ by $k_i$ for the next step, whence\n\n\n\n\n\n\n\n$$f(\\mathbf{k};\\,\\nu) = \\prod_{i=1}^n B\\left(\\frac{k_i+1}{2}, \\frac{\\nu - (k_i + k_{i+1} + \\cdots + k_n) + i - 1}{2}\\right).$$\n\n\n\n\n\n\n\n(Although this can be simplified using basic properties of Gamma functions, it is good enough for computation and analysis.)\n\n\n\n\nAs a check, we recover the normalizing constant as the zeroth moment,\n\n\n\n\n$$\\begin{aligned}\n C(\\nu, n) &= f((0,\\ldots,0);\\, n) \\\\\n&=\\prod_{i=1}^n B\\left(\\frac{0+1}{2}, \\frac{\\nu - 0 + (i-1)}{2}\\right)\\\\\n&=\\prod_{i=1}^n \\frac{\\Gamma\\left(\\frac{0+1}{2}\\right)\\Gamma\\left(\\frac{\\nu - 0 + (i-1)}{2}\\right)}{\\Gamma\\left(\\frac{\\nu + (i-1) + 1}{2}\\right)}\\\\\n&= \\frac{\\Gamma\\left(\\frac{1}{2}\\right)^n \\Gamma\\left(\\frac{\\nu}{2}\\right)}{\\Gamma\\left(\\frac{\\nu+n}{2}\\right)}.\n\\end{aligned}$$\n\n\n\n\nThis agrees with the value quoted in the question, since $\\Gamma(1/2)=\\sqrt{\\pi}.$\n\n\n\n\nFinally, recall that a scale parameter $\\tau$ multiplies each variable $x_i$ by $\\tau,$ whence it multiplies the moment of order $\\mathbf k$ by $\\tau(k_1+k_2+\\cdots+k_n).$ Writing\n\n\n\n\n$$\\kappa = k_1+k_2+\\cdots+k_n$$\n\n\n\n\nand recalling the scale parameter is $\\tau = \\sqrt{\\nu}\\sigma$ shows that\n\n\n\n\n\n\n\n$$\\mu(\\mathbf k;\\,\\nu,\\sigma) = \\frac{\\nu^{\\kappa/2}\\sigma^\\kappa f(\\mathbf k;\\,\\nu)}{C(\\nu, n)}.$$\n\n\n\n\n\n\n\nThe question concerns linear combinations of moments of order $4$ ($\\kappa = 4$). Computing the coefficients--which is merely a matter of multiplying the matrices--is of no interest here.\n\n\n\n\nImplementation and testing\n\n\n\n\nTo maintain precision and avoid numerical overflow, it is best to compute products of Beta functions using logarithms. Here is an example of how that's done in R, using its built-in lbeta (logarithm of Beta) function.\n\n\n\n\n#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma = 1) {\n n <- length(k)\n y <- lf(k, nu)\n exp(y + lgamma((nu + n)/2) - lgamma(nu/2) - (n/2) * log(pi) + \n sum(k) * (log(nu)/2 + log(sigma)))\n}\n\n\n\n\n\nThe sum and cumsum functions require only $O(n)$ computational effort and storage.\n\n\n\n\nFor example, the $(0,1,2,3)$ moment with $\\nu=12$ is found as\n\n\n\n\n> mu(c(0,1,2,3), 12, 1)\n[1] 4.583662\n\n\n\n\n\nAs a test, I generated datasets of one million iid observations from multivariate $t$ distributions (using the mnormt package) and compared the sample moments (for various $\\mathbf k$) to the formula:\n\n\n\n\nset.seed(17)\nk <- c(0, 1, 2)\nnu <- 5\nX <- t(rmt(1e6, 0, diag(1, n), df = nu)) # One row for each coordinate\nm <- mean(apply(abs(X)^k, 2, prod)) # The estimated moment of order `k`\nm / mu(k, nu) \n\n\n\n\n\nThe output, equal to $1.012$ in this example, ideally would be $1,$ indicating perfect agreement. But $t$ distributions, especially for smallish $\\nu,$ are rather heavy-tailed, resulting in very high sampling variances for the higher moments (this one is of order $\\kappa = 0+1+2=3$). In light of this, $1.012$ is excellent agreement.\n\n\n\n\nThe output of additional tests continues to support the conclusion that the formulas for $f$ and $\\mu$ are correct.", "answer_url": "https://stats.stackexchange.com/a/676851", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T15:28:16+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": 676824, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-08-12T15:28:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "C9CDAB77-2DD2-446E-837A-211128FD0EE9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C9CDAB77-2DD2-446E-837A-211128FD0EE9/view-source"}], "score": 2, "updated_at": "2026-08-12T15:28:16+00:00"}], "domain": "statistics", "external_links": ["https://en.wikipedia.org/wiki/Beta_prime_distribution#Generalization"], "medical_sensitive": false, "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": "SATYA", "question_author_url": "https://stats.stackexchange.com/users/375640/satya", "question_author_user_type": "registered", "question_created_at": "2026-08-10T13:38:12+00:00", "question_html": "The following is a multivariate Student's t distribution\n$$ p_{\\sigma^2}(\\mathrm{x})= {\\displaystyle {N_{\\nu,\\sigma^2}}\\left[1+\\frac{1}{\\nu\\sigma^2}\\sum_{i=1}^nx_i^2\\right]^{-(\\nu +n)/2}}, \\;\\mathrm{x}=[x_1,\\cdots,x_n]^{\\top}\\in \\mathbb{R}^n,\\;\\nu>2,$$ where $N_{\\nu,\\sigma^2}=\\frac {\\Gamma \\left[(\\nu +n)/2\\right]}{\\Gamma (\\nu /2)\\nu ^{n/2} \\pi^{n/2}{\\sigma}^{n}}.$ I am struggling to find the higher-order moments $E[X^{\\top}X]$, $E[X^{\\top}X(X^{\\top}X)^{\\top}]$. Is there a way to get these quantities?
\n", "question_id": 676824, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "The following is a multivariate Student's t distribution\n$$ p_{\\sigma^2}(\\mathrm{x})= {\\displaystyle {N_{\\nu,\\sigma^2}}\\left[1+\\frac{1}{\\nu\\sigma^2}\\sum_{i=1}^nx_i^2\\right]^{-(\\nu +n)/2}}, \\;\\mathrm{x}=[x_1,\\cdots,x_n]^{\\top}\\in \\mathbb{R}^n,\\;\\nu>2,$$ where $N_{\\nu,\\sigma^2}=\\frac {\\Gamma \\left[(\\nu +n)/2\\right]}{\\Gamma (\\nu /2)\\nu ^{n/2} \\pi^{n/2}{\\sigma}^{n}}.$ I am struggling to find the higher-order moments $E[X^{\\top}X]$, $E[X^{\\top}X(X^{\\top}X)^{\\top}]$. Is there a way to get these quantities?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "SATYA", "profile_url": "https://stats.stackexchange.com/users/375640/satya", "user_type": "registered"}, "created_at": "2026-08-10T13:38:12+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "FE80823D-F8D4-4BF7-916A-95ECE3955E38", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FE80823D-F8D4-4BF7-916A-95ECE3955E38/view-source"}, {"content_license": null, "contributor": {"display_name": "kjetil b halvorsen", "profile_url": "https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen", "user_type": "moderator"}, "created_at": "2026-08-10T13:43:33+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "09839026-A5FE-44BE-B46A-D0FCD7254AFE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/09839026-A5FE-44BE-B46A-D0FCD7254AFE/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676824/higher-moments-of-multivariate-students-t-distribution", "split": "train", "split_group": "d616db2eb7c80d9bcbf195f175fdfced0ba92b76f0e66918c59a439d07fa96f0", "tags": ["mathematical-statistics", "inference", "moments", "t-distribution"], "thread_id": "stats:676824", "title": "Higher Moments of multivariate Student's t distribution"}} {"accepted_answer": {"answer_html": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$
\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$
\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.
\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.
\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.
\n", "answer_id": 676849, "answer_text": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$\n\n\n\n\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$\n\n\n\n\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Qsmelzjn.png] (https://i.sstatic.net/Qsmelzjn.png)\n\n\n\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.\n\n\n\n\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.", "answer_url": "https://stats.stackexchange.com/a/676849", "author": "Thomas Lumley", "author_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T03:14:18+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": 676842, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:14:18+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "EF5747F6-4B6A-42A4-8968-9F80C87019F6", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EF5747F6-4B6A-42A4-8968-9F80C87019F6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:21:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "A9820920-337C-4445-864A-E2CE6845065B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A9820920-337C-4445-864A-E2CE6845065B/view-source"}], "score": 4, "updated_at": "2026-08-12T03:21:16+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, mean = 0, sd = sqrt(mean(x^2)), log = TRUE))\n ll_sigma_in_H0= sum(dnorm(x, mean = muhat, sd = 1, log = TRUE))\n llr= max(ll_mu_in_H0, ll_sigma_in_H0)- sum(dnorm(x, mean = muhat, sd = sigmahat, log = TRUE))\n T[i]= -2*llr\n}\n\npar(mar=c(5,4,4,12), xpd=TRUE)\nplot(sort(T), (1:nsim)/nsim, type='l', lty=2, xlab= 'x', ylab= 'CDF')\nlines(qchisq(p= (1:nsim)/nsim, df= 1, ncp = 0, lower.tail = TRUE, log.p = FALSE), (1:nsim)/nsim, lty=1)\nlegend(\"topright\",inset= c(-0.5,0), lty= c(2,1), legend= c('empirical', 'chi^2 with df=1'))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676842, "sha256": "6655bd907225c7526d765f76e3438c4e3188e536db6da04f4ad8037510fb01ec", "source_url": "https://stats.stackexchange.com/questions/676842/the-asymptotic-distribution-of-likelihood-ratio-statistic-when-the-null-hypothes"}], "other_answers": [], "product": "code_qa", "question": "In fact I doubt if such kind of hypothesis test will be used in real work, but just out of curiosity I have a question on the property of such test.\n\n\n\n\nQuestion. Consider an $n$-dimensional parameter $\\theta= (\\theta_1, \\cdots, \\theta_n)\\in \\Theta$ where $\\Theta$ is an open subset in $\\mathbb R^n$, and the hypothesis\n$$ H_0: \\text{either }\\theta_1= c_1 \\text{ or }\\theta_2= c_2\\longleftrightarrow\nH_1:\\text{ otherwise},$$\nwhere $c_1, c_2$ are given constant.\nWhat is the asymptotic distribution of $-2 \\log\\lambda$ where $\\lambda$ is the likelihood ratio statistic, if the true model is $\\theta_1= c_1$ and $\\theta_2= c_2$?\n(Assuming all other conditions of Wilks's Theorem).\n\n\n\n\nFor example, consider $X_1,\\cdots, X_n$ are i.i.d. samples from $N(\\mu, \\sigma^2)$,\nand test if $H_0: \\text{either }\\mu=0 \\text{ or }\\sigma^2= 1$ holds.\nThen the maximum likelihood estimation is the one in $(\\mu, \\sigma^2)= (0, \\sqrt{\\frac{1}{n}\\sum_{i=1}^n X_i^2} )$ and $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$\nwhich has a larger likelihood, and from this we can compute the LR statistic $\\lambda$.\n\n\n\n\nIf, say, the model is generated under true parameter $\\mu= 1, \\sigma^2= 1$, then\nthe simulating data shows that the empirical cdf of $-2\\log\\lambda$\nand $\\chi^2_1$ are very close, which seems to suggest that $-2\\log\\lambda\\to_d\\chi^2_1$,\nand this is in fact the case, as, when the sample size tends to infinity, the probability that the MLE under $H_0$ is $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$ (which corresponds to the true parameter) will tend to $1$, so the LR statistic is the same as testing $H_0: \\sigma^2= 1$ which probability tending to $1$.\n\n\n\n\nHowever, if the true parameter is $(\\mu, \\sigma^2)= (0, 1)$, then the empirical cdf of $-2\\log\\lambda$ is no longer close to $\\chi^2_1$, as the figure below shows.\n\n\n\n\nMy question is, does $-2\\log\\lambda$ has a general asymptotic distribution in such case?\n\n\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/cWv54DMg.png] (https://i.sstatic.net/cWv54DMg.png)\n\n\n\n\n# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, mean = 0, sd = sqrt(mean(x^2)), log = TRUE))\n ll_sigma_in_H0= sum(dnorm(x, mean = muhat, sd = 1, log = TRUE))\n llr= max(ll_mu_in_H0, ll_sigma_in_H0)- sum(dnorm(x, mean = muhat, sd = sigmahat, log = TRUE))\n T[i]= -2*llr\n}\n\npar(mar=c(5,4,4,12), xpd=TRUE)\nplot(sort(T), (1:nsim)/nsim, type='l', lty=2, xlab= 'x', ylab= 'CDF')\nlines(qchisq(p= (1:nsim)/nsim, df= 1, ncp = 0, lower.tail = TRUE, log.p = FALSE), (1:nsim)/nsim, lty=1)\nlegend(\"topright\",inset= c(-0.5,0), lty= c(2,1), legend= c('empirical', 'chi^2 with df=1'))", "record_id": "Scientific-Code-and-Analysis-QA:stats:676842", "selected_answer": {"answer_html": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$
\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$
\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.
\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.
\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.
\n", "answer_id": 676849, "answer_text": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$\n\n\n\n\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$\n\n\n\n\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Qsmelzjn.png] (https://i.sstatic.net/Qsmelzjn.png)\n\n\n\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.\n\n\n\n\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.", "answer_url": "https://stats.stackexchange.com/a/676849", "author": "Thomas Lumley", "author_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T03:14:18+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": 676842, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:14:18+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "EF5747F6-4B6A-42A4-8968-9F80C87019F6", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EF5747F6-4B6A-42A4-8968-9F80C87019F6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:21:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "A9820920-337C-4445-864A-E2CE6845065B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A9820920-337C-4445-864A-E2CE6845065B/view-source"}], "score": 4, "updated_at": "2026-08-12T03:21:16+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 676849, "answers": [{"answer_html": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$
\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$
\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.
\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.
\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.
\n", "answer_id": 676849, "answer_text": "It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your $N(\\mu,\\sigma^2)$ example that means the asymptotic null distribution is the same as testing $\\mu=0$ or $\\sigma^2=1$ for the bivariate Normal distribution that's the limit of $\\sqrt{n}(\\hat\\mu-\\mu,\\hat\\sigma^2-\\sigma^2)$\n\n\n\n\nThis doesn't initially get you all that far further forward, because that distribution is ugly. You can now notice that for this specific asymptotic bivariate Normal problem the variables are orthogonal. The restricted MLE under the null is either $(0,\\hat\\sigma^2)$ or $(\\hat\\mu,1)$, depending on which is closer to $\\hat\\theta$. That means the log likelihood ratio is the minimum of two independent scaled $\\chi^2_1$\n\n\n\n\nSpecifically, we should get the minimum of two $\\chi^2_1$s. The red line shows this CDF on your plot.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Qsmelzjn.png] (https://i.sstatic.net/Qsmelzjn.png)\n\n\n\n\nFor the more general case you have a limiting bivariate Normal problem with non-diagonal variance. It's still true that you just work out the distance to the restricted MLE, but that's the closest point in a non-rectangular norm. The geometry is not the same in all the orthants. Also, the restricted MLE can be at the equivalent of $(0,1)$ with non-zero probability, so there's a $\\chi^2_0$ component to the mixture. I think you end up with five components in total for two parameters.\n\n\n\n\nWith more than two parameters taking part, everything is exactly the same only incomparably worse: the geometry of the closest point in the null hypothesis just gets more and more complicated, with more and more components. But the idea is the same: the LRT is asymptotically the LRT for a single-observation local Gaussian shift problem. This is, in some sense, why Wald's Theorem works and why Chernoff's result for boundary problems works and lots of other things.", "answer_url": "https://stats.stackexchange.com/a/676849", "author": "Thomas Lumley", "author_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-12T03:14:18+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": 676842, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:14:18+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "EF5747F6-4B6A-42A4-8968-9F80C87019F6", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EF5747F6-4B6A-42A4-8968-9F80C87019F6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Thomas Lumley", "profile_url": "https://stats.stackexchange.com/users/249135/thomas-lumley", "user_type": "registered"}, "created_at": "2026-08-12T03:21:16+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "A9820920-337C-4445-864A-E2CE6845065B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A9820920-337C-4445-864A-E2CE6845065B/view-source"}], "score": 4, "updated_at": "2026-08-12T03:21:16+00:00"}], "domain": "statistics", "external_links": ["https://i.sstatic.net/Qsmelzjn.png", "https://i.sstatic.net/cWv54DMg.png"], "medical_sensitive": false, "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": "Asigan", "question_author_url": "https://stats.stackexchange.com/users/499652/asigan", "question_author_user_type": "registered", "question_created_at": "2026-08-11T15:31:10+00:00", "question_html": "In fact I doubt if such kind of hypothesis test will be used in real work, but just out of curiosity I have a question on the property of such test.
\nQuestion. Consider an $n$-dimensional parameter $\\theta= (\\theta_1, \\cdots, \\theta_n)\\in \\Theta$ where $\\Theta$ is an open subset in $\\mathbb R^n$, and the hypothesis\n$$ H_0: \\text{either }\\theta_1= c_1 \\text{ or }\\theta_2= c_2\\longleftrightarrow\nH_1:\\text{ otherwise},$$\nwhere $c_1, c_2$ are given constant.\nWhat is the asymptotic distribution of $-2 \\log\\lambda$ where $\\lambda$ is the likelihood ratio statistic, if the true model is $\\theta_1= c_1$ and $\\theta_2= c_2$?\n(Assuming all other conditions of Wilks's Theorem).
\nFor example, consider $X_1,\\cdots, X_n$ are i.i.d. samples from $N(\\mu, \\sigma^2)$,\nand test if $H_0: \\text{either }\\mu=0 \\text{ or }\\sigma^2= 1$ holds.\nThen the maximum likelihood estimation is the one in $(\\mu, \\sigma^2)= (0, \\sqrt{\\frac{1}{n}\\sum_{i=1}^n X_i^2} )$ and $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$\nwhich has a larger likelihood, and from this we can compute the LR statistic $\\lambda$.
\nIf, say, the model is generated under true parameter $\\mu= 1, \\sigma^2= 1$, then\nthe simulating data shows that the empirical cdf of $-2\\log\\lambda$\nand $\\chi^2_1$ are very close, which seems to suggest that $-2\\log\\lambda\\to_d\\chi^2_1$,\nand this is in fact the case, as, when the sample size tends to infinity, the probability that the MLE under $H_0$ is $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$ (which corresponds to the true parameter) will tend to $1$, so the LR statistic is the same as testing $H_0: \\sigma^2= 1$ which probability tending to $1$.
\nHowever, if the true parameter is $(\\mu, \\sigma^2)= (0, 1)$, then the empirical cdf of $-2\\log\\lambda$ is no longer close to $\\chi^2_1$, as the figure below shows.
\nMy question is, does $-2\\log\\lambda$ has a general asymptotic distribution in such case?
\n# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, mean = 0, sd = sqrt(mean(x^2)), log = TRUE))\n ll_sigma_in_H0= sum(dnorm(x, mean = muhat, sd = 1, log = TRUE))\n llr= max(ll_mu_in_H0, ll_sigma_in_H0)- sum(dnorm(x, mean = muhat, sd = sigmahat, log = TRUE))\n T[i]= -2*llr\n}\n\npar(mar=c(5,4,4,12), xpd=TRUE)\nplot(sort(T), (1:nsim)/nsim, type='l', lty=2, xlab= 'x', ylab= 'CDF')\nlines(qchisq(p= (1:nsim)/nsim, df= 1, ncp = 0, lower.tail = TRUE, log.p = FALSE), (1:nsim)/nsim, lty=1)\nlegend("topright",inset= c(-0.5,0), lty= c(2,1), legend= c('empirical', 'chi^2 with df=1'))\n\n", "question_id": 676842, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "In fact I doubt if such kind of hypothesis test will be used in real work, but just out of curiosity I have a question on the property of such test.\n\n\n\n\nQuestion. Consider an $n$-dimensional parameter $\\theta= (\\theta_1, \\cdots, \\theta_n)\\in \\Theta$ where $\\Theta$ is an open subset in $\\mathbb R^n$, and the hypothesis\n$$ H_0: \\text{either }\\theta_1= c_1 \\text{ or }\\theta_2= c_2\\longleftrightarrow\nH_1:\\text{ otherwise},$$\nwhere $c_1, c_2$ are given constant.\nWhat is the asymptotic distribution of $-2 \\log\\lambda$ where $\\lambda$ is the likelihood ratio statistic, if the true model is $\\theta_1= c_1$ and $\\theta_2= c_2$?\n(Assuming all other conditions of Wilks's Theorem).\n\n\n\n\nFor example, consider $X_1,\\cdots, X_n$ are i.i.d. samples from $N(\\mu, \\sigma^2)$,\nand test if $H_0: \\text{either }\\mu=0 \\text{ or }\\sigma^2= 1$ holds.\nThen the maximum likelihood estimation is the one in $(\\mu, \\sigma^2)= (0, \\sqrt{\\frac{1}{n}\\sum_{i=1}^n X_i^2} )$ and $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$\nwhich has a larger likelihood, and from this we can compute the LR statistic $\\lambda$.\n\n\n\n\nIf, say, the model is generated under true parameter $\\mu= 1, \\sigma^2= 1$, then\nthe simulating data shows that the empirical cdf of $-2\\log\\lambda$\nand $\\chi^2_1$ are very close, which seems to suggest that $-2\\log\\lambda\\to_d\\chi^2_1$,\nand this is in fact the case, as, when the sample size tends to infinity, the probability that the MLE under $H_0$ is $(\\mu, \\sigma^2)= (\\frac 1n\\sum_{i=1}^n X_i, 1)$ (which corresponds to the true parameter) will tend to $1$, so the LR statistic is the same as testing $H_0: \\sigma^2= 1$ which probability tending to $1$.\n\n\n\n\nHowever, if the true parameter is $(\\mu, \\sigma^2)= (0, 1)$, then the empirical cdf of $-2\\log\\lambda$ is no longer close to $\\chi^2_1$, as the figure below shows.\n\n\n\n\nMy question is, does $-2\\log\\lambda$ has a general asymptotic distribution in such case?\n\n\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/cWv54DMg.png] (https://i.sstatic.net/cWv54DMg.png)\n\n\n\n\n# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, mean = 0, sd = sqrt(mean(x^2)), log = TRUE))\n ll_sigma_in_H0= sum(dnorm(x, mean = muhat, sd = 1, log = TRUE))\n llr= max(ll_mu_in_H0, ll_sigma_in_H0)- sum(dnorm(x, mean = muhat, sd = sigmahat, log = TRUE))\n T[i]= -2*llr\n}\n\npar(mar=c(5,4,4,12), xpd=TRUE)\nplot(sort(T), (1:nsim)/nsim, type='l', lty=2, xlab= 'x', ylab= 'CDF')\nlines(qchisq(p= (1:nsim)/nsim, df= 1, ncp = 0, lower.tail = TRUE, log.p = FALSE), (1:nsim)/nsim, lty=1)\nlegend(\"topright\",inset= c(-0.5,0), lty= c(2,1), legend= c('empirical', 'chi^2 with df=1'))", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Asigan", "profile_url": "https://stats.stackexchange.com/users/499652/asigan", "user_type": "registered"}, "created_at": "2026-08-11T15:31:10+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "12CBC237-71E5-4C7A-8DB4-C9CB01074B9D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/12CBC237-71E5-4C7A-8DB4-C9CB01074B9D/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-12T01:24:32+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "C0DDD5BE-21BF-4736-ABCF-642B92C21EDA", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C0DDD5BE-21BF-4736-ABCF-642B92C21EDA/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-12T04:37:20+00:00", "raw_file": "raw/codex_api_v1/4f74c7234d8d68222a97a637c85bc14d5aa045a3d3f336d95a6178b29bc656cd_1790825248437413600_0.json", "raw_sha256": "8385102f4bd0517d9240ab820144fa12ccb111d0c4dd000e66bdc0e0ba0294fe", "revision_guid": "03306B28-DD9D-42D1-990F-0DBB141FA2C2", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/03306B28-DD9D-42D1-990F-0DBB141FA2C2/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676842/the-asymptotic-distribution-of-likelihood-ratio-statistic-when-the-null-hypothes", "split": "train", "split_group": "04f52474e604252adf534b05534d06a31a2b2b196a4a54978ab75b8b8a135d5c", "tags": ["mathematical-statistics", "likelihood-ratio"], "thread_id": "stats:676842", "title": "The asymptotic distribution of likelihood ratio statistic when the null hypothesis is described by an \"or\" condition"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "library(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676858, "sha256": "e3b1e32f3f32fe01d572135a32ea1e26fbbec71586b485ee403199e72bc87c81", "source_url": "https://stats.stackexchange.com/questions/676858/how-do-i-account-for-site-in-a-dbrda-while-evaluating-the-effect-of-variables-th"}, {"block_index": 0, "code_text": "ord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676863, "sha256": "bc9680397eb4e4c17b1e6a48e377a48440fce734ee9b4c8c11f10e16e2a30592", "source_url": "https://stats.stackexchange.com/a/676863"}, {"block_index": 1, "code_text": "ctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676863, "sha256": "3f6e3af9e3118f4e94ce8847b13eba7f0f099f0c7268848fd38f3aa5704e26ce", "source_url": "https://stats.stackexchange.com/a/676863"}, {"block_index": 3, "code_text": "my_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by \"margin\")\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676863, "sha256": "6818238b2ed33870cc626f77e5c65b19bc5edac4c145555b6e3d34875e45702d", "source_url": "https://stats.stackexchange.com/a/676863"}], "other_answers": [], "product": "code_qa", "question": "I am trying to evaluate which environmental variables drive variation in microbial communities. I have 5 samples collected at 15 sites, and for each sample, I have a microbial community, soil pH, soil NO3, and MAT.\n\n\n\n\nI wanted to account for site when testing the effect of my environmental variables, so I tried:\n\n\n\n\nlibrary(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n\n\n\n\n\nbut because all samples at a site have the same MAT, the model does not evaluate MAT.\n\n\n\n\nHow can I test the effects of all of my environmental variables while accounting for site?", "record_id": "Scientific-Code-and-Analysis-QA:stats:676858", "selected_answer": {"answer_html": "There are two options for testing ordination models in vegan:
\nIn 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the data.
\nIn 2. you would fit you model (even without the Condition() bit, but I would advise you keep it in, and then you restrict the permutations to be within the levels of site.
In both cases you would pass something to the anova() function. This gives you some options as "test the effect of my environmental variables" is not a well-defined things; do you mean to fit an omnibus test of the joint effects of the three terms in the model, or to test sequential or marginal effects of each individual term?
If you want the omnibus test, essentially of the whole model, you would do:
\nord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n\nThis would use complete randomisation (so it is a model-based test) of the amount of variation in the $d_{ij}$ dissimilarities in Y explained by the model containing pH, NO3, MAT after removing the between site differences (due to the Condition()).
A restricted permutation for a design-based test would be
\nctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n\nOr for marginal effects, where you get a test of adding say pH to a model with MAT + NO3, for each term in turn:
set.seed(20260814)\nanova(ord, by = "margin")\n\nset.seed(20260814)\nanova(ord, by = "margin", permutations = ctrl)\n\nThe entire problem in your data however is that MAT is confounded with site; there isn't a way to test MAT and account for site as mathematically MAT and site have the same representation in the model and hence have the same estimated effect (as long as you code MAT as a factor) in the model.
Because you don't have replication of MAT within levels of site there isn't anything you can do that includes both variables.
That said, including MAT in the model (if coded as a factor) will account for the crude between site differences in Y. So you can use the model-based route and just do:
my_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by "margin")\n\nThe interpretation is complicated however; you can't claim that the estimated effect of MAT is due to MAT as it could be due to any differences between your sites, which may or may not include a temperature effect.
This is where experimental design comes in; ideally a statistical analysis plan created before you collected the data would have identified the issue, allowing you to address these problem (where possible) or highlight hypotheses that cannot be tested given the chosen design.
\n", "answer_id": 676863, "answer_text": "There are two options for testing ordination models in vegan:\n\n\n\n\n\nmodel-based permutations, and\n\n\n\n\ndesign-based\n\n\n\n\n\nIn 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the data.\n\n\n\n\nIn 2. you would fit you model (even without the Condition() bit, but I would advise you keep it in, and then you restrict the permutations to be within the levels of site.\n\n\n\n\nIn both cases you would pass something to the anova() function. This gives you some options as \"test the effect of my environmental variables\" is not a well-defined things; do you mean to fit an omnibus test of the joint effects of the three terms in the model, or to test sequential or marginal effects of each individual term?\n\n\n\n\nIf you want the omnibus test, essentially of the whole model, you would do:\n\n\n\n\nord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n\n\n\n\n\nThis would use complete randomisation (so it is a model-based test) of the amount of variation in the $d_{ij}$ dissimilarities in Y explained by the model containing pH, NO3, MAT after removing the between site differences (due to the Condition()).\n\n\n\n\nA restricted permutation for a design-based test would be\n\n\n\n\nctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n\n\n\n\n\nOr for marginal effects, where you get a test of adding say pH to a model with MAT + NO3, for each term in turn:\n\n\n\n\nset.seed(20260814)\nanova(ord, by = \"margin\")\n\nset.seed(20260814)\nanova(ord, by = \"margin\", permutations = ctrl)\n\n\n\n\n\nThe entire problem in your data however is that MAT is confounded with site; there isn't a way to test MAT and account for site as mathematically MAT and site have the same representation in the model and hence have the same estimated effect (as long as you code MAT as a factor) in the model.\n\n\n\n\nBecause you don't have replication of MAT within levels of site there isn't anything you can do that includes both variables.\n\n\n\n\nThat said, including MAT in the model (if coded as a factor) will account for the crude between site differences in Y. So you can use the model-based route and just do:\n\n\n\n\nmy_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by \"margin\")\n\n\n\n\n\nThe interpretation is complicated however; you can't claim that the estimated effect of MAT is due to MAT as it could be due to any differences between your sites, which may or may not include a temperature effect.\n\n\n\n\nThis is where experimental design comes in; ideally a statistical analysis plan created before you collected the data would have identified the issue, allowing you to address these problem (where possible) or highlight hypotheses that cannot be tested given the chosen design.", "answer_url": "https://stats.stackexchange.com/a/676863", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-14T06:11:59+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": 676858, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-14T06:11:59+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "A07F8661-3C22-4FF1-B601-E3771400D740", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A07F8661-3C22-4FF1-B601-E3771400D740/view-source"}], "score": 2, "updated_at": "2026-08-14T06:11:59+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "There are two options for testing ordination models in vegan:
\nIn 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the data.
\nIn 2. you would fit you model (even without the Condition() bit, but I would advise you keep it in, and then you restrict the permutations to be within the levels of site.
In both cases you would pass something to the anova() function. This gives you some options as "test the effect of my environmental variables" is not a well-defined things; do you mean to fit an omnibus test of the joint effects of the three terms in the model, or to test sequential or marginal effects of each individual term?
If you want the omnibus test, essentially of the whole model, you would do:
\nord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n\nThis would use complete randomisation (so it is a model-based test) of the amount of variation in the $d_{ij}$ dissimilarities in Y explained by the model containing pH, NO3, MAT after removing the between site differences (due to the Condition()).
A restricted permutation for a design-based test would be
\nctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n\nOr for marginal effects, where you get a test of adding say pH to a model with MAT + NO3, for each term in turn:
set.seed(20260814)\nanova(ord, by = "margin")\n\nset.seed(20260814)\nanova(ord, by = "margin", permutations = ctrl)\n\nThe entire problem in your data however is that MAT is confounded with site; there isn't a way to test MAT and account for site as mathematically MAT and site have the same representation in the model and hence have the same estimated effect (as long as you code MAT as a factor) in the model.
Because you don't have replication of MAT within levels of site there isn't anything you can do that includes both variables.
That said, including MAT in the model (if coded as a factor) will account for the crude between site differences in Y. So you can use the model-based route and just do:
my_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by "margin")\n\nThe interpretation is complicated however; you can't claim that the estimated effect of MAT is due to MAT as it could be due to any differences between your sites, which may or may not include a temperature effect.
This is where experimental design comes in; ideally a statistical analysis plan created before you collected the data would have identified the issue, allowing you to address these problem (where possible) or highlight hypotheses that cannot be tested given the chosen design.
\n", "answer_id": 676863, "answer_text": "There are two options for testing ordination models in vegan:\n\n\n\n\n\nmodel-based permutations, and\n\n\n\n\ndesign-based\n\n\n\n\n\nIn 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the data.\n\n\n\n\nIn 2. you would fit you model (even without the Condition() bit, but I would advise you keep it in, and then you restrict the permutations to be within the levels of site.\n\n\n\n\nIn both cases you would pass something to the anova() function. This gives you some options as \"test the effect of my environmental variables\" is not a well-defined things; do you mean to fit an omnibus test of the joint effects of the three terms in the model, or to test sequential or marginal effects of each individual term?\n\n\n\n\nIf you want the omnibus test, essentially of the whole model, you would do:\n\n\n\n\nord <- dbrda(Y ~ pH + NO3 + MAT + Condition(Site), data = my_df)\n\nset.seed(20260814)\nanova(ord)\n\n\n\n\n\nThis would use complete randomisation (so it is a model-based test) of the amount of variation in the $d_{ij}$ dissimilarities in Y explained by the model containing pH, NO3, MAT after removing the between site differences (due to the Condition()).\n\n\n\n\nA restricted permutation for a design-based test would be\n\n\n\n\nctrl <- with(\n my_df,\n how(\n blocks = site\n )\n)\n\nset.seed(20260814)\nanova(ord, permutations = ctrl)\n\n\n\n\n\nOr for marginal effects, where you get a test of adding say pH to a model with MAT + NO3, for each term in turn:\n\n\n\n\nset.seed(20260814)\nanova(ord, by = \"margin\")\n\nset.seed(20260814)\nanova(ord, by = \"margin\", permutations = ctrl)\n\n\n\n\n\nThe entire problem in your data however is that MAT is confounded with site; there isn't a way to test MAT and account for site as mathematically MAT and site have the same representation in the model and hence have the same estimated effect (as long as you code MAT as a factor) in the model.\n\n\n\n\nBecause you don't have replication of MAT within levels of site there isn't anything you can do that includes both variables.\n\n\n\n\nThat said, including MAT in the model (if coded as a factor) will account for the crude between site differences in Y. So you can use the model-based route and just do:\n\n\n\n\nmy_df <- my_df |>\n transform(\n fMAT = factor(MAT)\n )\n\nord <- dbrda(Y ~ pH + NO3 + fMAT, data = my_df)\n\nset.seed(20260814)\nanova(ord, by \"margin\")\n\n\n\n\n\nThe interpretation is complicated however; you can't claim that the estimated effect of MAT is due to MAT as it could be due to any differences between your sites, which may or may not include a temperature effect.\n\n\n\n\nThis is where experimental design comes in; ideally a statistical analysis plan created before you collected the data would have identified the issue, allowing you to address these problem (where possible) or highlight hypotheses that cannot be tested given the chosen design.", "answer_url": "https://stats.stackexchange.com/a/676863", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-14T06:11:59+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": 676858, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-14T06:11:59+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "A07F8661-3C22-4FF1-B601-E3771400D740", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A07F8661-3C22-4FF1-B601-E3771400D740/view-source"}], "score": 2, "updated_at": "2026-08-14T06:11:59+00:00"}], "domain": "statistics", "external_links": [], "medical_sensitive": false, "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": "Tillandsia123", "question_author_url": "https://stats.stackexchange.com/users/489435/tillandsia123", "question_author_user_type": "registered", "question_created_at": "2026-08-13T14:13:45+00:00", "question_html": "I am trying to evaluate which environmental variables drive variation in microbial communities. I have 5 samples collected at 15 sites, and for each sample, I have a microbial community, soil pH, soil NO3, and MAT.
\nI wanted to account for site when testing the effect of my environmental variables, so I tried:
\nlibrary(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n\nbut because all samples at a site have the same MAT, the model does not evaluate MAT.
How can I test the effects of all of my environmental variables while accounting for site?
\n", "question_id": 676858, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I am trying to evaluate which environmental variables drive variation in microbial communities. I have 5 samples collected at 15 sites, and for each sample, I have a microbial community, soil pH, soil NO3, and MAT.\n\n\n\n\nI wanted to account for site when testing the effect of my environmental variables, so I tried:\n\n\n\n\nlibrary(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n\n\n\n\n\nbut because all samples at a site have the same MAT, the model does not evaluate MAT.\n\n\n\n\nHow can I test the effects of all of my environmental variables while accounting for site?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Tillandsia123", "profile_url": "https://stats.stackexchange.com/users/489435/tillandsia123", "user_type": "registered"}, "created_at": "2026-08-13T14:13:45+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7B37CEAA-255C-414E-8A5C-901D88775172", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7B37CEAA-255C-414E-8A5C-901D88775172/view-source"}, {"content_license": null, "contributor": {"display_name": "Community", "profile_url": "https://stats.stackexchange.com/users/-1/community", "user_type": "moderator"}, "created_at": "2026-08-13T16:05:23+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "0B02F8B6-209E-470E-B9B3-ADE3ADB3F0F3", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/0B02F8B6-209E-470E-B9B3-ADE3ADB3F0F3/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676858/how-do-i-account-for-site-in-a-dbrda-while-evaluating-the-effect-of-variables-th", "split": "train", "split_group": "b7a109258c68d4c0ad147c01da06f4600be94b148c00d9e8d67cbc16243ff6b8", "tags": ["r", "vegan", "redundancy-analysis"], "thread_id": "stats:676858", "title": "How do I account for site in a dbRDA while evaluating the effect of variables that are the same across all samples in a site?"}} {"accepted_answer": {"answer_html": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.
\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.
\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:
library(MatchIt); library(cobalt)\n\ndata("lalonde", package = "MatchIt")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\nYou can assess whether many units are assigned to the same subclass by using
\nwith(M1, table(treat, subclass))\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.
In general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.
\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.
\n", "answer_id": 676905, "answer_text": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.\n\n\n\n\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.\n\n\n\n\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:\n\n\n\n\nlibrary(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\n\n\n\n\nYou can assess whether many units are assigned to the same subclass by using\n\n\n\n\nwith(M1, table(treat, subclass))\n\n\n\n\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.\n\n\n\n\nIn general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.\n\n\n\n\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.", "answer_url": "https://stats.stackexchange.com/a/676905", "author": "Noah", "author_url": "https://stats.stackexchange.com/users/116195/noah", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-18T15:26:28+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": 676867, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Noah", "profile_url": "https://stats.stackexchange.com/users/116195/noah", "user_type": "registered"}, "created_at": "2026-08-18T15:26:28+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "CB48996D-4B71-49A4-AD23-E5B278A942D5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB48996D-4B71-49A4-AD23-E5B278A942D5/view-source"}], "score": 3, "updated_at": "2026-08-18T15:26:28+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "library(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676905, "sha256": "ab755c77438b83e047bd4f641c2842b48dc9b58095cdba2b3ddf91d1705442ed", "source_url": "https://stats.stackexchange.com/a/676905"}], "other_answers": [], "product": "code_qa", "question": "I was using full matching (using MatchIt, method = \"full\") to estimate the ATE. Now I want to extend this to examine a moderation effect by a categorical variable. I am fitting separate propensity score models within each moderator subgroup, and setting the estimand to ATE as well.\nI am getting quite high weights in separate groups (maximum of 22 in 1 group and 15 in the other - which as I understand is a way high), as well as relatively low ESS. I tried to apply calipers, which did help to improve the max weights (subgroup 1: 22.4 → 13.2; subgroup 2: 14.8 → 8.0) and ESS (subgroup 1: 74 → 111; subgroup 2: 93 → 156), balance was also mainly improved. It led to discarding 20 out of 275 observations in one subgroup and 6 out of 251 in the other.\nAs I understand the result may not anymore correspond to the ATE. After applying the calipers I am targeting slightly different populations, correct? How reasonable it is then to compare these subgroup estimates in order to draw conclusions about moderation in this case? any additional diagnostics I should try? should I avoid calipers in moderation at all?", "record_id": "Scientific-Code-and-Analysis-QA:stats:676867", "selected_answer": {"answer_html": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.
\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.
\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:
library(MatchIt); library(cobalt)\n\ndata("lalonde", package = "MatchIt")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\nYou can assess whether many units are assigned to the same subclass by using
\nwith(M1, table(treat, subclass))\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.
In general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.
\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.
\n", "answer_id": 676905, "answer_text": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.\n\n\n\n\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.\n\n\n\n\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:\n\n\n\n\nlibrary(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\n\n\n\n\nYou can assess whether many units are assigned to the same subclass by using\n\n\n\n\nwith(M1, table(treat, subclass))\n\n\n\n\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.\n\n\n\n\nIn general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.\n\n\n\n\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.", "answer_url": "https://stats.stackexchange.com/a/676905", "author": "Noah", "author_url": "https://stats.stackexchange.com/users/116195/noah", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-18T15:26:28+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": 676867, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Noah", "profile_url": "https://stats.stackexchange.com/users/116195/noah", "user_type": "registered"}, "created_at": "2026-08-18T15:26:28+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "CB48996D-4B71-49A4-AD23-E5B278A942D5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB48996D-4B71-49A4-AD23-E5B278A942D5/view-source"}], "score": 3, "updated_at": "2026-08-18T15:26:28+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 676905, "answers": [{"answer_html": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.
\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.
\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:
library(MatchIt); library(cobalt)\n\ndata("lalonde", package = "MatchIt")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = "full", estimand = "ATE", tol = 1e-7,\n link = "linear.logit", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\nYou can assess whether many units are assigned to the same subclass by using
\nwith(M1, table(treat, subclass))\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.
In general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.
\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.
\n", "answer_id": 676905, "answer_text": "Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample still resembles the overall population based on how few units were discarded.\n\n\n\n\nIt's worth remembering also that the subgroups don't need to resemble each other for you to perform subgroup analysis or study moderation. However, you won't be able to conclude that it is the moderator itself that causes the difference in effect estimates (if there is one); any difference could simply be due to differences in the compositions of the subgroups, which may be further exacerbated by the imposition of the caliper.\n\n\n\n\nMy advice would be first to try different methods of increasing the ESS, such as using the min.controls and max.controls arguments to prevent too many units assigned to one subclass. See an example below on the lalonde dataset, where using the max.controls option both improves balance and increases the ESS of the smaller group (which affects precision the most), and is a bit better than using a caliper:\n\n\n\n\nlibrary(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race)\n\n# Full matching with max.controls limited\nM2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n max.controls = 10)\n\n# Full matching with caliper on PS\nM3 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n link = \"linear.logit\", exact = ~race,\n caliper = .1)\n\nbal.tab(M1, weights = list(max.c = M2, cal = M3))\n#> Balance Measures\n#> Type Diff.matchit Diff.max.c Diff.cal\n#> distance Distance 0.0391 0.0300 0.0068\n#> age Contin. -0.1377 0.0318 -0.0370\n#> educ Contin. 0.1166 0.0524 0.0335\n#> race_black Binary -0.0000 0.0000 -0.0000\n#> race_hispan Binary -0.0000 0.0000 -0.0000\n#> race_white Binary -0.0000 0.0000 0.0000\n#> married Binary -0.0061 -0.0026 -0.0129\n#> nodegree Binary -0.0878 -0.0569 -0.0815\n#> re74 Contin. -0.3139 -0.1761 -0.2054\n#> re75 Contin. -0.2884 -0.1247 -0.2248\n#> \n#> Effective sample sizes\n#> Control Treated\n#> All 429. 185. \n#> matchit 257.09 26.49\n#> max.c 156.88 86.58\n#> cal 210.74 43.47\n\n\n\n\n\nYou can assess whether many units are assigned to the same subclass by using\n\n\n\n\nwith(M1, table(treat, subclass))\n\n\n\n\n\nDoing this on M1 reveals that one subclass contains 89 control units and 1 treated unit, yielding more extreme weights: that treated unit receives a weight of 90. With M2, no more than 10 control units per treated unit are in each subclass, by definition, so no treated units receive a weight larger than 11. Decreasing the variability of the weights increases the ESS.\n\n\n\n\nIn general, I would avoid calipers unless it's impossible to achieve balance without them. There are often enough ways to adjust a matching specification that you can achieve the properties of the matched sample you desire without resorting to a caliper. I would also recommend trying weighting methods before using a caliper unless your field looks down on weighting.\n\n\n\n\nIf you do decide to use a caliper, see how relaxed of a caliper you can use to achieve your goals; a relaxed caliper will discard fewer units, making your results more generalizable to your population of interest. All that said, if your sample isn't a representative sample from a population, it doesn't matter whether the result generalize: your caliper matched sample is no less representative of a meaningful population than your original sample.", "answer_url": "https://stats.stackexchange.com/a/676905", "author": "Noah", "author_url": "https://stats.stackexchange.com/users/116195/noah", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-18T15:26:28+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": 676867, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Noah", "profile_url": "https://stats.stackexchange.com/users/116195/noah", "user_type": "registered"}, "created_at": "2026-08-18T15:26:28+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "CB48996D-4B71-49A4-AD23-E5B278A942D5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB48996D-4B71-49A4-AD23-E5B278A942D5/view-source"}], "score": 3, "updated_at": "2026-08-18T15:26:28+00:00"}], "domain": "statistics", "external_links": [], "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": "user31214993", "question_author_url": "https://stats.stackexchange.com/users/490497/user31214993", "question_author_user_type": "registered", "question_created_at": "2026-08-14T14:13:25+00:00", "question_html": "I was using full matching (using MatchIt, method = "full") to estimate the ATE. Now I want to extend this to examine a moderation effect by a categorical variable. I am fitting separate propensity score models within each moderator subgroup, and setting the estimand to ATE as well.\nI am getting quite high weights in separate groups (maximum of 22 in 1 group and 15 in the other - which as I understand is a way high), as well as relatively low ESS. I tried to apply calipers, which did help to improve the max weights (subgroup 1: 22.4 → 13.2; subgroup 2: 14.8 → 8.0) and ESS (subgroup 1: 74 → 111; subgroup 2: 93 → 156), balance was also mainly improved. It led to discarding 20 out of 275 observations in one subgroup and 6 out of 251 in the other.\nAs I understand the result may not anymore correspond to the ATE. After applying the calipers I am targeting slightly different populations, correct? How reasonable it is then to compare these subgroup estimates in order to draw conclusions about moderation in this case? any additional diagnostics I should try? should I avoid calipers in moderation at all?
\n", "question_id": 676867, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I was using full matching (using MatchIt, method = \"full\") to estimate the ATE. Now I want to extend this to examine a moderation effect by a categorical variable. I am fitting separate propensity score models within each moderator subgroup, and setting the estimand to ATE as well.\nI am getting quite high weights in separate groups (maximum of 22 in 1 group and 15 in the other - which as I understand is a way high), as well as relatively low ESS. I tried to apply calipers, which did help to improve the max weights (subgroup 1: 22.4 → 13.2; subgroup 2: 14.8 → 8.0) and ESS (subgroup 1: 74 → 111; subgroup 2: 93 → 156), balance was also mainly improved. It led to discarding 20 out of 275 observations in one subgroup and 6 out of 251 in the other.\nAs I understand the result may not anymore correspond to the ATE. After applying the calipers I am targeting slightly different populations, correct? How reasonable it is then to compare these subgroup estimates in order to draw conclusions about moderation in this case? any additional diagnostics I should try? should I avoid calipers in moderation at all?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "user31214993", "profile_url": "https://stats.stackexchange.com/users/490497/user31214993", "user_type": "registered"}, "created_at": "2026-08-14T14:13:25+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "E972484E-5136-4868-B279-F1B4F45BA217", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E972484E-5136-4868-B279-F1B4F45BA217/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676867/can-i-use-caliper-in-moderation-analysis-with-ate-is-the-target-estimand", "split": "train", "split_group": "b48d86f70b30568513b23fc942f009f575dd2790b7c2253380088fa85fbbcec7", "tags": ["interaction", "matching", "treatment-effect"], "thread_id": "stats:676867", "title": "Can I use caliper in moderation analysis with ATE is the target estimand?"}} {"accepted_answer": {"answer_html": "(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.
\n(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no "information leakage" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.
\n(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.
\n", "answer_id": 676887, "answer_text": "(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.\n\n\n\n\n(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no \"information leakage\" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.\n\n\n\n\n(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.", "answer_url": "https://stats.stackexchange.com/a/676887", "author": "Christian Hennig", "author_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-16T11:19:56+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-08-16T11:19:56+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB/view-source"}], "score": 5, "updated_at": "2026-08-16T11:19:56+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "set.seed(2026)\n\n# Set up a regression\n#\nN <- 100\np <- N - 3\nX <- matrix(rnorm(N * p), N, p)\nB <- rbinom(p, 1, 0.3)\nEy <- X %*% B\ne <- rnorm(N, 0, 8)\ny <- Ey + e\n\n# Fit to all X variables using OLS\n#\nL_ols <- lm(y ~ X)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_ols <- sum((y - predict(L_ols))^2)/(N - p - 1)\n\n# Now apply PCA\n\npca <- prcomp(X)\n\n# Extract the first five PCs (adjust this and see what happens to the performance)\n#\nX_pca <- pca$x[, 1:(5)]\n\n# Fit a regression to the PCs\n#\nL_pca <- lm(y ~ X_pca)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_pca <- sum((y - predict(L_pca))^2)/(N - dim(X_pca)[2] - 1)\n\n# Compare performance (smaller is better)\n#\nprint(mse_ols)\nprint(mse_pca)\n\n# I get 37.17123 and 78.09094, respectively, so the regression on five PCs\n# is much worse, but the regression on the PCs is possible, definitely!\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676875, "sha256": "83b92e32f3481c32f864e266e5b1a8c2498a0e79f593a7bfb01f507538e35cf0", "source_url": "https://stats.stackexchange.com/a/676875"}], "other_answers": [{"answer_html": "The principal components (PCs) are not guaranteed to be good predictors. PCA is performed without any regard for an outcome ($y$) variable and, alone, is not a prediction technique. However, the PCs most definitely can be entered into a regression model. See below for an example in R.
\nset.seed(2026)\n\n# Set up a regression\n#\nN <- 100\np <- N - 3\nX <- matrix(rnorm(N * p), N, p)\nB <- rbinom(p, 1, 0.3)\nEy <- X %*% B\ne <- rnorm(N, 0, 8)\ny <- Ey + e\n\n# Fit to all X variables using OLS\n#\nL_ols <- lm(y ~ X)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_ols <- sum((y - predict(L_ols))^2)/(N - p - 1)\n\n# Now apply PCA\n\npca <- prcomp(X)\n\n# Extract the first five PCs (adjust this and see what happens to the performance)\n#\nX_pca <- pca$x[, 1:(5)]\n\n# Fit a regression to the PCs\n#\nL_pca <- lm(y ~ X_pca)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_pca <- sum((y - predict(L_pca))^2)/(N - dim(X_pca)[2] - 1)\n\n# Compare performance (smaller is better)\n#\nprint(mse_ols)\nprint(mse_pca)\n\n# I get 37.17123 and 78.09094, respectively, so the regression on five PCs\n# is much worse, but the regression on the PCs is possible, definitely!\n\nI did this with a linear regression, but if you have a categorical outcome (“classification” type of problem), you could use the PCs in a (multinomial) logistic regression or a sigmoid/softmax neural network and then measure performance by log loss, Brier score, or any of the other measures of performance used for classification-type problems.
\n", "answer_id": 676875, "answer_text": "The principal components (PCs) are not guaranteed to be good predictors. PCA is performed without any regard for an outcome ($y$) variable and, alone, is not a prediction technique. However, the PCs most definitely can be entered into a regression model. See below for an example in R.\n\n\n\n\nset.seed(2026)\n\n# Set up a regression\n#\nN <- 100\np <- N - 3\nX <- matrix(rnorm(N * p), N, p)\nB <- rbinom(p, 1, 0.3)\nEy <- X %*% B\ne <- rnorm(N, 0, 8)\ny <- Ey + e\n\n# Fit to all X variables using OLS\n#\nL_ols <- lm(y ~ X)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_ols <- sum((y - predict(L_ols))^2)/(N - p - 1)\n\n# Now apply PCA\n\npca <- prcomp(X)\n\n# Extract the first five PCs (adjust this and see what happens to the performance)\n#\nX_pca <- pca$x[, 1:(5)]\n\n# Fit a regression to the PCs\n#\nL_pca <- lm(y ~ X_pca)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_pca <- sum((y - predict(L_pca))^2)/(N - dim(X_pca)[2] - 1)\n\n# Compare performance (smaller is better)\n#\nprint(mse_ols)\nprint(mse_pca)\n\n# I get 37.17123 and 78.09094, respectively, so the regression on five PCs\n# is much worse, but the regression on the PCs is possible, definitely!\n\n\n\n\n\nI did this with a linear regression, but if you have a categorical outcome (“classification” type of problem), you could use the PCs in a (multinomial) logistic regression or a sigmoid/softmax neural network and then measure performance by log loss, Brier score, or any of the other measures of performance used for classification-type problems.", "answer_url": "https://stats.stackexchange.com/a/676875", "author": "Dave", "author_url": "https://stats.stackexchange.com/users/247274/dave", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-15T10:57:03+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dave", "profile_url": "https://stats.stackexchange.com/users/247274/dave", "user_type": "registered"}, "created_at": "2026-08-15T10:57:03+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7A2458ED-B2DA-472F-BF39-53D6AC4C1287", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7A2458ED-B2DA-472F-BF39-53D6AC4C1287/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dave", "profile_url": "https://stats.stackexchange.com/users/247274/dave", "user_type": "registered"}, "created_at": "2026-08-15T11:09:18+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "9698C0C6-9232-4A7F-8A30-A5C0AA5D85D2", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9698C0C6-9232-4A7F-8A30-A5C0AA5D85D2/view-source"}], "score": 6, "updated_at": "2026-08-15T11:09:18+00:00"}, {"answer_html": "Prediction is not the only thing we do, so whether PCA can be used for prediction is not the only question to ask.
\nWikipedia lists the following
\nA long time ago I did some of the last, looking at patterns from quantitative electroencephalography, where we had data on a huge number of neurons. We tried to use the PCA results to categorize people into various injuries, determine if they had had a concussion, and so on, with less need for a neurologist. This could then be done e.g. on a battlefield, or a sporting event, or emergency room that lacked a neurologist.
\nI haven't kept up with that field, so I'm not sure what happened there, but our initial results were promising.
\n", "answer_id": 676876, "answer_text": "Prediction is not the only thing we do, so whether PCA can be used for prediction is not the only question to ask.\n\n\n\n\nWikipedia (https://en.wikipedia.org/wiki/Principal_component_analysis#Applications) lists the following\n\n\n\n\n\nIntelligence testing\n\n\n\n\nResidential differentiation\n\n\n\n\nDevelopment indexes\n\n\n\n\nPopulation genetics\n\n\n\n\nMarket research\n\n\n\n\nVarious uses in quantitative finance\n\n\n\n\nVarious uses in neuroscience\n\n\n\n\n\nA long time ago I did some of the last, looking at patterns from quantitative electroencephalography, where we had data on a huge number of neurons. We tried to use the PCA results to categorize people into various injuries, determine if they had had a concussion, and so on, with less need for a neurologist. This could then be done e.g. on a battlefield, or a sporting event, or emergency room that lacked a neurologist.\n\n\n\n\nI haven't kept up with that field, so I'm not sure what happened there, but our initial results were promising.", "answer_url": "https://stats.stackexchange.com/a/676876", "author": "Peter Flom", "author_url": "https://stats.stackexchange.com/users/686/peter-flom", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-15T11:16:14+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Peter Flom", "profile_url": "https://stats.stackexchange.com/users/686/peter-flom", "user_type": "registered"}, "created_at": "2026-08-15T11:16:14+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "5F1D4B92-63F4-42E2-B24E-133C561E4D0A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/5F1D4B92-63F4-42E2-B24E-133C561E4D0A/view-source"}], "score": 2, "updated_at": "2026-08-15T11:16:14+00:00"}, {"answer_html": "PCA gives you a projection, and that can (and is sucessfully) be used to produce lower-dimensional input for various predictive models. Principal component regression (PCA-CLS) being possibly the most widely known, but in my field also PCA-LDA for classification is widely used (our data generation processes fit nicely with the maths of PCA), and PCA is at the core of SIMCA, an important one-class classifier/class model.
\nAs Christian Hennig's answer details, there is no general guarantee that a projection and dimension reduction by PCA as part of the modeling pipeline is going to help. But there are certain types of data and applications where there is good reason to expect that it does; and of course this can and should be verified.
\nE.g. I'm analytical chemist. We have essentially spent 100 years optimizing our measurements to yield data that nicely approximates linear combinations of concentration x pure component spectra. And PCA or PLS do indeed work nicely on such data. Plus, many industrial applications don't focus on minor components independent of the major sources of variance but rather need quick and non-destructive measurements of the major components which also have largest variance.
In a modeling pipeline unsupervised PCA projection -> predictive model in the narrower sense, the unsupervised nature of the PCA can be particularly helpful if lots of unlabelled data are available, but only a few labelled instances: the PCA projection (with dimension reduction) can then still be fit on the large unlabelled data base, and the (2nd) supervised part of the training can profit from fitting in the lower dimensional PC score space.\nThis scenario is quite common in chemometric modeling of spectroscopic data, where spectra are easy and cheap to acquire (and often non-destructive), while labels require reference (chemical) analyses which are expensive and often also restricted due to being destructive.
\nOtherwise, if labels are available for all training data, most people in my field would immediately go for the supervised analogue to PCA, PLS.
\n", "answer_id": 676896, "answer_text": "PCA gives you a projection, and that can (and is sucessfully) be used to produce lower-dimensional input for various predictive models. Principal component regression (PCA-CLS) being possibly the most widely known, but in my field also PCA-LDA for classification is widely used (our data generation processes fit nicely with the maths of PCA), and PCA is at the core of SIMCA (https://en.wikipedia.org/wiki/Soft_independent_modelling_of_class_analogies), an important one-class classifier/class model.\n\n\n\n\nAs Christian Hennig's answer (https://stats.stackexchange.com/a/676887/4598) details, there is no general guarantee that a projection and dimension reduction by PCA as part of the modeling pipeline is going to help. But there are certain types of data and applications where there is good reason to expect that it does; and of course this can and should be verified.\n\nE.g. I'm analytical chemist. We have essentially spent 100 years optimizing our measurements to yield data that nicely approximates linear combinations of concentration x pure component spectra. And PCA or PLS do indeed work nicely on such data. Plus, many industrial applications don't focus on minor components independent of the major sources of variance but rather need quick and non-destructive measurements of the major components which also have largest variance.\n\n\n\n\nIn a modeling pipeline unsupervised PCA projection -> predictive model in the narrower sense, the unsupervised nature of the PCA can be particularly helpful if lots of unlabelled data are available, but only a few labelled instances: the PCA projection (with dimension reduction) can then still be fit on the large unlabelled data base, and the (2nd) supervised part of the training can profit from fitting in the lower dimensional PC score space.\nThis scenario is quite common in chemometric modeling of spectroscopic data, where spectra are easy and cheap to acquire (and often non-destructive), while labels require reference (chemical) analyses which are expensive and often also restricted due to being destructive.\n\n\n\n\nOtherwise, if labels are available for all training data, most people in my field would immediately go for the supervised analogue to PCA, PLS.", "answer_url": "https://stats.stackexchange.com/a/676896", "author": "cbeleites", "author_url": "https://stats.stackexchange.com/users/4598/cbeleites", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-17T17:03:30+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "cbeleites", "profile_url": "https://stats.stackexchange.com/users/4598/cbeleites", "user_type": "registered"}, "created_at": "2026-08-17T17:03:30+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "3A1FC35A-72A0-4215-A06C-3D8E4B7FB085", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3A1FC35A-72A0-4215-A06C-3D8E4B7FB085/view-source"}], "score": 3, "updated_at": "2026-08-17T17:03:30+00:00"}], "product": "code_qa", "question": "I've been reading up on pca. I've seen some people say that you cannot use pca for making predictions especially for linear regression models because it makes principal components that capture the most variability and not necessarily the actual relationships.\n\n\n\n\nHowever, I've seen principal components be reverted to their original variables and then used to make predictions in example cases. I am confused about which one is correct.\n\n\n\n\nI don't really understand the point even using pca if you can't make predictions off of the data. Is this just a linear regression-specific issue and not a classification problem/doesn't apply to other models?", "record_id": "Scientific-Code-and-Analysis-QA:stats:676874", "selected_answer": {"answer_html": "(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.
\n(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no "information leakage" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.
\n(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.
\n", "answer_id": 676887, "answer_text": "(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.\n\n\n\n\n(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no \"information leakage\" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.\n\n\n\n\n(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.", "answer_url": "https://stats.stackexchange.com/a/676887", "author": "Christian Hennig", "author_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-16T11:19:56+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-08-16T11:19:56+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB/view-source"}], "score": 5, "updated_at": "2026-08-16T11:19:56+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": 676887, "answers": [{"answer_html": "The principal components (PCs) are not guaranteed to be good predictors. PCA is performed without any regard for an outcome ($y$) variable and, alone, is not a prediction technique. However, the PCs most definitely can be entered into a regression model. See below for an example in R.
\nset.seed(2026)\n\n# Set up a regression\n#\nN <- 100\np <- N - 3\nX <- matrix(rnorm(N * p), N, p)\nB <- rbinom(p, 1, 0.3)\nEy <- X %*% B\ne <- rnorm(N, 0, 8)\ny <- Ey + e\n\n# Fit to all X variables using OLS\n#\nL_ols <- lm(y ~ X)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_ols <- sum((y - predict(L_ols))^2)/(N - p - 1)\n\n# Now apply PCA\n\npca <- prcomp(X)\n\n# Extract the first five PCs (adjust this and see what happens to the performance)\n#\nX_pca <- pca$x[, 1:(5)]\n\n# Fit a regression to the PCs\n#\nL_pca <- lm(y ~ X_pca)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_pca <- sum((y - predict(L_pca))^2)/(N - dim(X_pca)[2] - 1)\n\n# Compare performance (smaller is better)\n#\nprint(mse_ols)\nprint(mse_pca)\n\n# I get 37.17123 and 78.09094, respectively, so the regression on five PCs\n# is much worse, but the regression on the PCs is possible, definitely!\n\nI did this with a linear regression, but if you have a categorical outcome (“classification” type of problem), you could use the PCs in a (multinomial) logistic regression or a sigmoid/softmax neural network and then measure performance by log loss, Brier score, or any of the other measures of performance used for classification-type problems.
\n", "answer_id": 676875, "answer_text": "The principal components (PCs) are not guaranteed to be good predictors. PCA is performed without any regard for an outcome ($y$) variable and, alone, is not a prediction technique. However, the PCs most definitely can be entered into a regression model. See below for an example in R.\n\n\n\n\nset.seed(2026)\n\n# Set up a regression\n#\nN <- 100\np <- N - 3\nX <- matrix(rnorm(N * p), N, p)\nB <- rbinom(p, 1, 0.3)\nEy <- X %*% B\ne <- rnorm(N, 0, 8)\ny <- Ey + e\n\n# Fit to all X variables using OLS\n#\nL_ols <- lm(y ~ X)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_ols <- sum((y - predict(L_ols))^2)/(N - p - 1)\n\n# Now apply PCA\n\npca <- prcomp(X)\n\n# Extract the first five PCs (adjust this and see what happens to the performance)\n#\nX_pca <- pca$x[, 1:(5)]\n\n# Fit a regression to the PCs\n#\nL_pca <- lm(y ~ X_pca)\n\n# Calculate the MSE, considering the parameter count\n#\nmse_pca <- sum((y - predict(L_pca))^2)/(N - dim(X_pca)[2] - 1)\n\n# Compare performance (smaller is better)\n#\nprint(mse_ols)\nprint(mse_pca)\n\n# I get 37.17123 and 78.09094, respectively, so the regression on five PCs\n# is much worse, but the regression on the PCs is possible, definitely!\n\n\n\n\n\nI did this with a linear regression, but if you have a categorical outcome (“classification” type of problem), you could use the PCs in a (multinomial) logistic regression or a sigmoid/softmax neural network and then measure performance by log loss, Brier score, or any of the other measures of performance used for classification-type problems.", "answer_url": "https://stats.stackexchange.com/a/676875", "author": "Dave", "author_url": "https://stats.stackexchange.com/users/247274/dave", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-15T10:57:03+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dave", "profile_url": "https://stats.stackexchange.com/users/247274/dave", "user_type": "registered"}, "created_at": "2026-08-15T10:57:03+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7A2458ED-B2DA-472F-BF39-53D6AC4C1287", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7A2458ED-B2DA-472F-BF39-53D6AC4C1287/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Dave", "profile_url": "https://stats.stackexchange.com/users/247274/dave", "user_type": "registered"}, "created_at": "2026-08-15T11:09:18+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "9698C0C6-9232-4A7F-8A30-A5C0AA5D85D2", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9698C0C6-9232-4A7F-8A30-A5C0AA5D85D2/view-source"}], "score": 6, "updated_at": "2026-08-15T11:09:18+00:00"}, {"answer_html": "Prediction is not the only thing we do, so whether PCA can be used for prediction is not the only question to ask.
\nWikipedia lists the following
\nA long time ago I did some of the last, looking at patterns from quantitative electroencephalography, where we had data on a huge number of neurons. We tried to use the PCA results to categorize people into various injuries, determine if they had had a concussion, and so on, with less need for a neurologist. This could then be done e.g. on a battlefield, or a sporting event, or emergency room that lacked a neurologist.
\nI haven't kept up with that field, so I'm not sure what happened there, but our initial results were promising.
\n", "answer_id": 676876, "answer_text": "Prediction is not the only thing we do, so whether PCA can be used for prediction is not the only question to ask.\n\n\n\n\nWikipedia (https://en.wikipedia.org/wiki/Principal_component_analysis#Applications) lists the following\n\n\n\n\n\nIntelligence testing\n\n\n\n\nResidential differentiation\n\n\n\n\nDevelopment indexes\n\n\n\n\nPopulation genetics\n\n\n\n\nMarket research\n\n\n\n\nVarious uses in quantitative finance\n\n\n\n\nVarious uses in neuroscience\n\n\n\n\n\nA long time ago I did some of the last, looking at patterns from quantitative electroencephalography, where we had data on a huge number of neurons. We tried to use the PCA results to categorize people into various injuries, determine if they had had a concussion, and so on, with less need for a neurologist. This could then be done e.g. on a battlefield, or a sporting event, or emergency room that lacked a neurologist.\n\n\n\n\nI haven't kept up with that field, so I'm not sure what happened there, but our initial results were promising.", "answer_url": "https://stats.stackexchange.com/a/676876", "author": "Peter Flom", "author_url": "https://stats.stackexchange.com/users/686/peter-flom", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-15T11:16:14+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Peter Flom", "profile_url": "https://stats.stackexchange.com/users/686/peter-flom", "user_type": "registered"}, "created_at": "2026-08-15T11:16:14+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "5F1D4B92-63F4-42E2-B24E-133C561E4D0A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/5F1D4B92-63F4-42E2-B24E-133C561E4D0A/view-source"}], "score": 2, "updated_at": "2026-08-15T11:16:14+00:00"}, {"answer_html": "(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.
\n(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no "information leakage" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.
\n(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.
\n", "answer_id": 676887, "answer_text": "(a) Principal components absolutely can be used for making predictions. Principal component analysis (PCA) is not a prediction method itself, but you can compute principal components on your predictors and then use these to predict the response. This can be done in linear regression (principal components regression), but also with other prediction models and algorithms.\n\n\n\n\n(b) It is true that PCA, when run on the predictors, does not use the response, and therefore there is no guarantee whatsoever that the first PCs are actually good at predicting the response. PCA reduces information in the first place, and because there is no guarantee that what is kept really has the most relevant information for prediction, in many situations reducing dimension by principal components will not improve the predictive model and may very well make it worse. That said, occasionally it can be good (there is no guarantee that the information kept by PCA is not the most useful either). You could use independent test data or cross-validation and the like to find that out. But be careful then to compute principal components only on the training data and make sure that there is no \"information leakage\" otherwise, for example by model selection like number of PCs, which may require double cross-validation or a three-fold split when running on top of comparing PC regression and the like with alternative prediction methods. If the number of observations is healthy compared to the number of variables, not doing any dimension reduction at all and just using the original variables is often better than PC regression and any other dimension reduction.\n\n\n\n\n(c) Although most often not optimal for prediction, there is an advantage of PCA as dimension reduction method for regression compared with dimension reduction approaches that use the response (assuming that you want or need to do dimension reduction, which is not necessarily a good idea, see above). Regression as a standard will model the response as random and the predictors as fixed (and one can pretend that even if they are not, standard regression theory is fine conditionally on the observed predictors). Data dependent manipulation and model selection will invalidate standard distribution theory of regression, which involves the p-values of t- and F-tests and cofidence intervals for parameters. But this only applies to using the random parts of the data, i.e., running PCA on predictors only will not affect standard inference, as opposed to, for example, stepwise regression or Lasso variable selection. This however will only hold if the response is not used for choosing the number of PCs.", "answer_url": "https://stats.stackexchange.com/a/676887", "author": "Christian Hennig", "author_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-16T11:19:56+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-08-16T11:19:56+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEE7BB07-5E87-461B-ABE2-DE62FF2A56AB/view-source"}], "score": 5, "updated_at": "2026-08-16T11:19:56+00:00"}, {"answer_html": "PCA gives you a projection, and that can (and is sucessfully) be used to produce lower-dimensional input for various predictive models. Principal component regression (PCA-CLS) being possibly the most widely known, but in my field also PCA-LDA for classification is widely used (our data generation processes fit nicely with the maths of PCA), and PCA is at the core of SIMCA, an important one-class classifier/class model.
\nAs Christian Hennig's answer details, there is no general guarantee that a projection and dimension reduction by PCA as part of the modeling pipeline is going to help. But there are certain types of data and applications where there is good reason to expect that it does; and of course this can and should be verified.
\nE.g. I'm analytical chemist. We have essentially spent 100 years optimizing our measurements to yield data that nicely approximates linear combinations of concentration x pure component spectra. And PCA or PLS do indeed work nicely on such data. Plus, many industrial applications don't focus on minor components independent of the major sources of variance but rather need quick and non-destructive measurements of the major components which also have largest variance.
In a modeling pipeline unsupervised PCA projection -> predictive model in the narrower sense, the unsupervised nature of the PCA can be particularly helpful if lots of unlabelled data are available, but only a few labelled instances: the PCA projection (with dimension reduction) can then still be fit on the large unlabelled data base, and the (2nd) supervised part of the training can profit from fitting in the lower dimensional PC score space.\nThis scenario is quite common in chemometric modeling of spectroscopic data, where spectra are easy and cheap to acquire (and often non-destructive), while labels require reference (chemical) analyses which are expensive and often also restricted due to being destructive.
\nOtherwise, if labels are available for all training data, most people in my field would immediately go for the supervised analogue to PCA, PLS.
\n", "answer_id": 676896, "answer_text": "PCA gives you a projection, and that can (and is sucessfully) be used to produce lower-dimensional input for various predictive models. Principal component regression (PCA-CLS) being possibly the most widely known, but in my field also PCA-LDA for classification is widely used (our data generation processes fit nicely with the maths of PCA), and PCA is at the core of SIMCA (https://en.wikipedia.org/wiki/Soft_independent_modelling_of_class_analogies), an important one-class classifier/class model.\n\n\n\n\nAs Christian Hennig's answer (https://stats.stackexchange.com/a/676887/4598) details, there is no general guarantee that a projection and dimension reduction by PCA as part of the modeling pipeline is going to help. But there are certain types of data and applications where there is good reason to expect that it does; and of course this can and should be verified.\n\nE.g. I'm analytical chemist. We have essentially spent 100 years optimizing our measurements to yield data that nicely approximates linear combinations of concentration x pure component spectra. And PCA or PLS do indeed work nicely on such data. Plus, many industrial applications don't focus on minor components independent of the major sources of variance but rather need quick and non-destructive measurements of the major components which also have largest variance.\n\n\n\n\nIn a modeling pipeline unsupervised PCA projection -> predictive model in the narrower sense, the unsupervised nature of the PCA can be particularly helpful if lots of unlabelled data are available, but only a few labelled instances: the PCA projection (with dimension reduction) can then still be fit on the large unlabelled data base, and the (2nd) supervised part of the training can profit from fitting in the lower dimensional PC score space.\nThis scenario is quite common in chemometric modeling of spectroscopic data, where spectra are easy and cheap to acquire (and often non-destructive), while labels require reference (chemical) analyses which are expensive and often also restricted due to being destructive.\n\n\n\n\nOtherwise, if labels are available for all training data, most people in my field would immediately go for the supervised analogue to PCA, PLS.", "answer_url": "https://stats.stackexchange.com/a/676896", "author": "cbeleites", "author_url": "https://stats.stackexchange.com/users/4598/cbeleites", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-17T17:03:30+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": 676874, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "cbeleites", "profile_url": "https://stats.stackexchange.com/users/4598/cbeleites", "user_type": "registered"}, "created_at": "2026-08-17T17:03:30+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "3A1FC35A-72A0-4215-A06C-3D8E4B7FB085", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3A1FC35A-72A0-4215-A06C-3D8E4B7FB085/view-source"}], "score": 3, "updated_at": "2026-08-17T17:03:30+00:00"}], "domain": "statistics", "external_links": ["https://en.wikipedia.org/wiki/Principal_component_analysis#Applications", "https://en.wikipedia.org/wiki/Soft_independent_modelling_of_class_analogies"], "medical_sensitive": false, "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": "Karl Suh", "question_author_url": "https://stats.stackexchange.com/users/513622/karl-suh", "question_author_user_type": "registered", "question_created_at": "2026-08-15T04:30:32+00:00", "question_html": "I've been reading up on pca. I've seen some people say that you cannot use pca for making predictions especially for linear regression models because it makes principal components that capture the most variability and not necessarily the actual relationships.
\nHowever, I've seen principal components be reverted to their original variables and then used to make predictions in example cases. I am confused about which one is correct.
\nI don't really understand the point even using pca if you can't make predictions off of the data. Is this just a linear regression-specific issue and not a classification problem/doesn't apply to other models?
\n", "question_id": 676874, "question_license": "CC BY-SA 4.0", "question_score": 5, "question_text": "I've been reading up on pca. I've seen some people say that you cannot use pca for making predictions especially for linear regression models because it makes principal components that capture the most variability and not necessarily the actual relationships.\n\n\n\n\nHowever, I've seen principal components be reverted to their original variables and then used to make predictions in example cases. I am confused about which one is correct.\n\n\n\n\nI don't really understand the point even using pca if you can't make predictions off of the data. Is this just a linear regression-specific issue and not a classification problem/doesn't apply to other models?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Karl Suh", "profile_url": "https://stats.stackexchange.com/users/513622/karl-suh", "user_type": "registered"}, "created_at": "2026-08-15T04:30:32+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "47012D84-2D0B-46BA-AE42-079A86DD6563", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/47012D84-2D0B-46BA-AE42-079A86DD6563/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-15T12:40:24+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "B197227E-EAF9-49DD-B742-0B419AF26E38", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/B197227E-EAF9-49DD-B742-0B419AF26E38/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-08-17T12:50:40+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "3799EB1C-3EFE-4A46-9106-11DCDC93F431", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3799EB1C-3EFE-4A46-9106-11DCDC93F431/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676874/can-you-use-pca-to-make-predictions-are-the-issues-with-predictions-specific-to", "split": "holdout", "split_group": "4be5949efaf8b799490f24666dac196270482a96c23b0b08367ced5183ffdf2c", "tags": ["regression", "pca"], "thread_id": "stats:676874", "title": "Can you use PCA to make predictions? are the issues with predictions specific to linear regression?"}} {"accepted_answer": {"answer_html": "I would suggest you look at a changing a couple of things:
\nThe distribution of Age is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.
If you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.
\nThe fs smooths by Taxon aren't really doing much because they are very restricted in terms of basis functions.
There is potential for an identifiability issue as you include a Taxon random intercept through the fs smooths, and then again through the ranef structure.
Identifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the random argument and the fs basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.
You will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is To Fa for example?).
Unless you think the mean of Asfc for individual taxa changes over time smoothly, then there is no reason to use the taxon specific fs smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of Asfc per Facet? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need Taxon at the highest level of the random effect structure.
Finally, your model assume that the response Acsf values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are not observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.
\n\nAs an aside, how do I only plot the first plot?
\n
Use the select argument to gratia' draw() function. This is a generic function so you need to look at the help for the gam method.
I would suggest you look at a changing a couple of things:
\nThe distribution of Age is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.
If you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.
\nThe fs smooths by Taxon aren't really doing much because they are very restricted in terms of basis functions.
There is potential for an identifiability issue as you include a Taxon random intercept through the fs smooths, and then again through the ranef structure.
Identifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the random argument and the fs basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.
You will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is To Fa for example?).
Unless you think the mean of Asfc for individual taxa changes over time smoothly, then there is no reason to use the taxon specific fs smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of Asfc per Facet? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need Taxon at the highest level of the random effect structure.
Finally, your model assume that the response Acsf values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are not observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.
\n\nAs an aside, how do I only plot the first plot?
\n
Use the select argument to gratia' draw() function. This is a generic function so you need to look at the help for the gam method.
I would suggest you look at a changing a couple of things:
\nThe distribution of Age is quite skewed, with some data squished up around 0 age. I would suggest trying to spread these values by out transforming Age, say via a square root transformation.
If you look at the smooth of Age, most of the smooth is supported by by a few unique time points - the whole right hand side of the plot. Those unique ages are having a potentially bigger influence on the shape of the function than the ages that are all squished up at the left of the x axis. Spreading out the ages allows all the data to influence the smooth more evenly. You can still present the results on the Age scale, What we want to avoid is unnecessary wiggles because the smooth adapted to widely spaced values on the original scale.
\nThe fs smooths by Taxon aren't really doing much because they are very restricted in terms of basis functions.
There is potential for an identifiability issue as you include a Taxon random intercept through the fs smooths, and then again through the ranef structure.
Identifiability refers to the model's ability to unique identify (estimate a value for) each parameter in the model. You are including a random intercept for taxon through the random argument and the fs basis also includes a random intercept term for taxon. As you have included the same variable in the model twice, the model has no way of knowing how to apportion variance in the response between these terms. This will often cause estimation problems and even if the models fit OK, you will likely have larger standard errors than if you didn't have the identifiability problem.
You will have to explain what you are trying or aiming to do rather than show what you did and ask if it is OK; it is not clear what the aim of the analysis, what model you are trying to fit, or how the data are structured, etc. (what is To Fa for example?).
Unless you think the mean of Asfc for individual taxa changes over time smoothly, then there is no reason to use the taxon specific fs smooths. The random effect structure you propose seems reasonable, except I'm unclear from your description if you have multiple observations of Asfc per Facet? Or is facet informative in some way (inside vs top surface for example). If you don't have multiple observations per facet, you don't need the lowermost level in your ranef structure I believe. If individual taxa have different mean values of complexity (which I understand to be true broadly, but perhaps not in your specific group of taxa) then I think you do need Taxon at the highest level of the random effect structure.
Finally, your model assume that the response Acsf values are conditional distributed Gaussian, meaning any value, negative or positive, is possible. If it is measuring complexity, that implies to me that negative values of the response are not observable, which would suggest the Gaussian is not appropriate. But perhaps this is not the case; the partial residuals don't look too bad, but proper model diagnostics would be need to confirm this. You also might need to consider the problem of temporal autocorrelation, although the Age smooth will help with that to some extent.
\n\nAs an aside, how do I only plot the first plot?
\n
Use the select argument to gratia' draw() function. This is a generic function so you need to look at the help for the gam method.
I have ~1400 measurements of teeth from ~40 species (taxon) that go back in time ~35mya (Age).\nThe data is noisy, so there is repetition in measurements from specimens that requires nesting as a random effect.
\nI wish to see if there are trends in this data through time. I can see the trends as individual taxon boxplots if I roughly order them by time, but I would highly prefer Age as a continuous variable and the repetition accounted for.
\nThe problem is that taxa (i.e. species) generally exist for 1my or less, and there are large gaps, so if I understand gamms properly (not a given here lol) then the smoothing splines will be (in my simple terms) trying to extrapolate/estimate the curves for a species across the entire dataset where they don't really exist. I have tried to compensate for this using factor smoothing for taxon.
\nTo cut to the point after much testing and fiddling, I came up with this:
\ntemp3 <- gamm4(Asfc ~ s(Age, k = 8, bs = "tp") + s(Age, taxon, bs = "fs", k = 3), data = df, random = ~(1|taxon/Specimen/To/Fa))\ntemp4 <- gamm4(Asfc ~ s(Age, k = 8, bs = "tp") + s(Age, taxon, bs = "fs", k = 3), data = df, random = ~(1|Specimen/To/Fa))\ndraw(temp3$gam, residuals = TRUE)\n\nAnd I get something like this:\n
For this data am I "gamm-ing" correctly? The second plot suggests errr no, or is that just the intercept and slope for taxon influence?
\nShould taxon be in the random effect structure? There are many specimens of each taxon.
\nAs an aside, how do I only plot the first plot?
\n------ Edit for clarification from questions (and comments) below ------
\nEach measurement is in this example a "complexity" value of a single facet (Fa has four levels), from a tooth (To has 8 levels). There are 1 to 8 measurements per Specimen requiring it to be a random effect. Each Specimen does belong to a species, though Species may or may not require nesting, or inclusion in the model per se, since most species have a single value for age, or are spread over 0.5 million years at most, it is highly correlated to Age and may be superfluous. Asfc is continuous, well normalised, and is considered gaussian.
\nThis is an updated model with model check based on comments : gamm4(Asfc ~ s(sqrtAge, k = 8, bs ="tp"), data = df, random = ~(1|Specimen/ToothNoLR/Facet))\n
RE check_model() I'm doing this to look for verifiable trends, not for prediction. I realise the large gaps would make the latter difficult, so this is more exploratory to see if a signal is present.
$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3606.394\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen (Intercept) 0.4767 \n ToothNoLR:Specimen (Intercept) 0.3814 \n Specimen (Intercept) 0.6024 \n Xr s(sqrt(Age)) 7.7972 \n Residual 0.4563 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen, 1430; ToothNoLR:Specimen, 542; Specimen, 421; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n 0.008243 -0.872465 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = "tp")\n\nEstimated degrees of freedom:\n5.56 total = 6.56 \n\nlmer.REML score: 3606.394 \n\nattr(,"class")\n[1] "gamm4" "list" \n\n------ 2nd edit updating random effect structure ------\nHere is the model with taxon added. The CI's are worse, but I suspect it is a "truer" model. gamm4(Asfc ~ s(sqrt(Age), k = 8, bs ="tp"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))
The check shows a more even spread of residuals.
\n\nThese are the new results.
\n> temp3 <- gamm4(Asfc ~ s(sqrt(Age), k = 8, bs ="tp"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n> temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.052\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4786 \n ToothNoLR:Specimen:taxon (Intercept) 0.3614 \n Specimen:taxon (Intercept) 0.5246 \n taxon (Intercept) 0.4379 \n Xr s(sqrt(Age)) 4.5753 \n Residual 0.4561 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\n X(Intercept) Xs(sqrt(Age))Fx1 \n -0.04013 -0.01014 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(sqrt(Age), k = 8, bs = "tp")\n\nEstimated degrees of freedom:\n4.3 total = 5.3 \n\nlmer.REML score: 3566.053\n\nCompare them to the results where Age is not sqrt()'ed
> temp3 <- gamm4(Asfc ~ s(Age, k = 8, bs ="tp"), data = df, random = ~(1|taxon/Specimen/ToothNoLR/Facet))\n> temp3\n$mer\nLinear mixed model fit by REML ['lmerMod']\nREML criterion at convergence: 3566.762\nRandom effects:\n Groups Name Std.Dev.\n Facet:ToothNoLR:Specimen:taxon (Intercept) 0.4651 \n ToothNoLR:Specimen:taxon (Intercept) 0.3611 \n Specimen:taxon (Intercept) 0.5317 \n taxon (Intercept) 0.3790 \n Xr s(Age) 7.4438 \n Residual 0.4692 \nNumber of obs: 1442, groups: Facet:ToothNoLR:Specimen:taxon, 1430; ToothNoLR:Specimen:taxon, 542; Specimen:taxon, 423; taxon, 46; Xr, 6\nFixed Effects:\nX(Intercept) Xs(Age)Fx1 \n -0.04286 -0.98535 \n\n$gam\n\nFamily: gaussian \nLink function: identity \n\nFormula:\nAsfc ~ s(Age, k = 8, bs = "tp")\n\nEstimated degrees of freedom:\n4.77 total = 5.77 \n\nlmer.REML score: 3566.762 \n\nI would appreciate any help in interpreting all this.
\n------ Edit ------\nIn reply to the posterior predictive check. Removal of Facet.\n
\ntemp3 without Facet in nesting, temp4 with Facet in nesting.
> compare_performance(temp3, temp4)\n# Comparison of Model Performance Indices\n\nName | Model | AIC (weights) | BIC (weights) | R2 | RMSE | Sigma\n-----------------------------------------------------------------------\ntemp3 | gamm4 | 4031.8 (0.475) | 4065.0 (0.484) | 0.049 | 0.572 | 0.573\ntemp4 | gamm4 | 4031.6 (0.525) | 4064.8 (0.516) | 0.049 | 0.274 | 0.275\n\n------ quick edit ------\nSo, yes, when I check $mer I get these results, and it appears to be(?), the missing "components" to complete the response?:
> model_performance(temp3$mer)\n# Indices of model performance\n\nAIC | AICc | BIC | R2 (cond.) | R2 (marg.) | ICC | RMSE | Sigma\n--------------------------------------------------------------------------\n3581.9 | 3582.0 | 3618.9 | 0.579 | 1.298e-04 | 0.579 | 0.572 | 0.660\n\n> icc(temp3$mer, by_group = TRUE)\n\nGroup | ICC\n--------------------------------\nToothNoLR:Specimen:taxon | 0.127\nSpecimen:taxon | 0.267\ntaxon | 0.185\n> check_model(temp3$mer)\n\nJust the lmer component predictive curve.\n
> check_model(temp3) Throws an error, so it seems it is incapable of incorporating both $mer and $gam into the check.
\n\nis trying to use all the data a flawed concept to begin with?
\n
No. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are "missing completely at random" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.
\n\n\nis this even a valid approach to begin with...?
\n
Your most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.
\n\n\nwhat is the "best" approach?
\n
For MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.
\nA standard general approach is multiple imputation. Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.
\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.
\nStef van Buuren's Flexible Imputation of Missing Data is a comprehensive guide to the process, which is implemented in his R mice package. Chapter 3 of Regression Modeling Strategies by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms and Hmisc packages.
\n\nDoes the validity depend on the pattern of missing data?
\n
Yes, in two ways.
\nFirst, multiple imputation works correctly if the data are "missing at random" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.
\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.
\nThe references linked above go into much more detail.
\n", "answer_id": 676936, "answer_text": "is trying to use all the data a flawed concept to begin with?\n\n\n\n\n\n\n\nNo. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are \"missing completely at random\" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.\n\n\n\n\n\n\n\nis this even a valid approach to begin with...?\n\n\n\n\n\n\n\nYour most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.\n\n\n\n\n\n\n\nwhat is the \"best\" approach?\n\n\n\n\n\n\n\nFor MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.\n\n\n\n\nA standard general approach is multiple imputation (https://stats.stackexchange.com/tags/multiple-imputation/info). Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.\n\n\n\n\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.\n\n\n\n\nStef van Buuren's Flexible Imputation of Missing Data (https://stefvanbuuren.name/fimd/) is a comprehensive guide to the process, which is implemented in his R mice package (https://cran.r-project.org/package=mice). Chapter 3 of Regression Modeling Strategies (https://hbiostat.org/rmsc/missing) by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms (https://cran.r-project.org/package=rms) and Hmisc (https://cran.r-project.org/package=Hmisc) packages.\n\n\n\n\n\n\n\nDoes the validity depend on the pattern of missing data?\n\n\n\n\n\n\n\nYes, in two ways.\n\n\n\n\nFirst, multiple imputation works correctly if the data are \"missing at random\" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.\n\n\n\n\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.\n\n\n\n\nThe references linked above go into much more detail.", "answer_url": "https://stats.stackexchange.com/a/676936", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-22T20:30:48+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": 676935, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-22T20:30:48+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "3A662AF2-F298-45A5-889D-7BDCBFDD001E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3A662AF2-F298-45A5-889D-7BDCBFDD001E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-23T17:43:21+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10/view-source"}], "score": 5, "updated_at": "2026-08-23T17:43:21+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "\n\nis trying to use all the data a flawed concept to begin with?
\n
No. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are "missing completely at random" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.
\n\n\nis this even a valid approach to begin with...?
\n
Your most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.
\n\n\nwhat is the "best" approach?
\n
For MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.
\nA standard general approach is multiple imputation. Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.
\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.
\nStef van Buuren's Flexible Imputation of Missing Data is a comprehensive guide to the process, which is implemented in his R mice package. Chapter 3 of Regression Modeling Strategies by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms and Hmisc packages.
\n\nDoes the validity depend on the pattern of missing data?
\n
Yes, in two ways.
\nFirst, multiple imputation works correctly if the data are "missing at random" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.
\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.
\nThe references linked above go into much more detail.
\n", "answer_id": 676936, "answer_text": "is trying to use all the data a flawed concept to begin with?\n\n\n\n\n\n\n\nNo. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are \"missing completely at random\" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.\n\n\n\n\n\n\n\nis this even a valid approach to begin with...?\n\n\n\n\n\n\n\nYour most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.\n\n\n\n\n\n\n\nwhat is the \"best\" approach?\n\n\n\n\n\n\n\nFor MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.\n\n\n\n\nA standard general approach is multiple imputation (https://stats.stackexchange.com/tags/multiple-imputation/info). Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.\n\n\n\n\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.\n\n\n\n\nStef van Buuren's Flexible Imputation of Missing Data (https://stefvanbuuren.name/fimd/) is a comprehensive guide to the process, which is implemented in his R mice package (https://cran.r-project.org/package=mice). Chapter 3 of Regression Modeling Strategies (https://hbiostat.org/rmsc/missing) by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms (https://cran.r-project.org/package=rms) and Hmisc (https://cran.r-project.org/package=Hmisc) packages.\n\n\n\n\n\n\n\nDoes the validity depend on the pattern of missing data?\n\n\n\n\n\n\n\nYes, in two ways.\n\n\n\n\nFirst, multiple imputation works correctly if the data are \"missing at random\" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.\n\n\n\n\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.\n\n\n\n\nThe references linked above go into much more detail.", "answer_url": "https://stats.stackexchange.com/a/676936", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-22T20:30:48+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": 676935, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-22T20:30:48+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "3A662AF2-F298-45A5-889D-7BDCBFDD001E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3A662AF2-F298-45A5-889D-7BDCBFDD001E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-23T17:43:21+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10/view-source"}], "score": 5, "updated_at": "2026-08-23T17:43:21+00:00"}], "domain": "statistics", "external_links": ["https://cran.r-project.org/package=Hmisc", "https://cran.r-project.org/package=mice", "https://cran.r-project.org/package=rms", "https://hbiostat.org/rmsc/missing", "https://stefvanbuuren.name/fimd/", "https://stefvanbuuren.name/fimd/sec-simplesolutions.html"], "medical_sensitive": false, "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": "A Friendly Fish", "question_author_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "question_author_user_type": "registered", "question_created_at": "2026-08-22T12:39:55+00:00", "question_html": "I observe 3 variables, $y_0$, $y_1$, and $y_2$, but am missing some of the observations for $y_1$, so I only have a subsample of $h$ observations of $y_1$ and all $n$ observations of $y_0$ and $y_2$. My goal is to study the relationship between $y_0$ and $y_1$ while controlling for $y_2$ while taking full advantage of all observations. Thus, instead of using only $h$ observations to run the multiple regression ${y_1}_h \\sim {y_0}_h + {y_2}_h$ where the second subscript represents whether we are using just $h$ (or all $n$) observations, I am instead first running ${y_0}_n \\sim {y_2}_n$ and ${y_1}_h \\sim {y_2}_h$ and then regressing the residuals from these two regressions on each other: $r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$. Of course, I only use the $h$ corresponding residuals from the ${y_0}_n \\sim {y_2}_n$ regression of $n$ points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only $h$ data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where $n$ is 40 and $h$ is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the "best" approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?
\n# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))["y0h","Pr(>|t|)"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))["r_ly0ONy2_n_h","Pr(>|t|)"]\n}\ncat("Multiple: ", mean(multiple < 0.05), "\\n")\n# Multiple: 0.0529 \ncat(" Stage: ", mean(stage < 0.05), "\\n")\n# Stage: 0.0527 \n\nObserve that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)
\nUPDATE (1/2):\nI ran simulation code to compare some of the key models, ("Full") one where we actually aren't missing data, ("Half") one where we only use $h$ observations, ("Estimated B") where we regress $y_0$ on $y_2$ using all data points and then use the $h$ residuals as the independent variable in a regression with the residuals of $y_1$ regressed on $y_2$ (for the $h$ $y_1$ points we observe) and ("Perfect A", "Perfect B") then two versions where I calculate the perfect residuals of $y_0$ on $y_2$ using the exactly correct slope:
\n\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))["y0"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))["y0h"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))["y0rph"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))["y0rph"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))["y0reh"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n "Full Model (sfm)" = sfm,\n "Half Model (shm)" = shm,\n "Perfect A (shpa)" = shpa,\n "Perfect B (shpb)" = shpb,\n "Estimated B (sheb)" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n\nAs you can see in the results above, the "Estimated B" version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points ("Half Model"), but it does have a bias.
\nUPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from section 1.3.2 of this book and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:
\n| Model | \nMean | \nVariance | \nBias | \nBias_Sq | \nMSE | \nValid_Runs | \n
|---|---|---|---|---|---|---|
| Full Model (N=40) | \n0.66563 | \n0.02497 | \n-0.00103 | \n0.00000 | \n0.02497 | \n9947 | \n
| Half Model (H=20) | \n0.66289 | \n0.05542 | \n-0.00377 | \n0.00001 | \n0.05543 | \n9947 | \n
| Estimated B | \n0.64330 | \n0.05259 | \n-0.02337 | \n0.00055 | \n0.05313 | \n9947 | \n
| Lavaan Pairwise | \n0.65849 | \n0.07174 | \n-0.00818 | \n0.00007 | \n0.07180 | \n9947 | \n
I am including the code i ran below:
\n# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages("lavaan")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- "\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n"\n\ncat("Running", num_sims, "simulations. Please wait...\\n")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = "pairwise.complete.obs")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == "y0", "est"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))["y0"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))["y0h"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))["y0reh"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n "Full Model (N=40)" = sfm,\n "Half Model (H=20)" = shm,\n "Estimated B" = sheb,\n "Lavaan Pairwise" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat("\\n--- Simulation Results ---\\n")\nprint(round(results_matrix, 5))\n\n", "question_id": 676935, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I observe 3 variables, $y_0$, $y_1$, and $y_2$, but am missing some of the observations for $y_1$, so I only have a subsample of $h$ observations of $y_1$ and all $n$ observations of $y_0$ and $y_2$. My goal is to study the relationship between $y_0$ and $y_1$ while controlling for $y_2$ while taking full advantage of all observations. Thus, instead of using only $h$ observations to run the multiple regression ${y_1}_h \\sim {y_0}_h + {y_2}_h$ where the second subscript represents whether we are using just $h$ (or all $n$) observations, I am instead first running ${y_0}_n \\sim {y_2}_n$ and ${y_1}_h \\sim {y_2}_h$ and then regressing the residuals from these two regressions on each other: $r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$. Of course, I only use the $h$ corresponding residuals from the ${y_0}_n \\sim {y_2}_n$ regression of $n$ points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only $h$ data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where $n$ is 40 and $h$ is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the \"best\" approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?\n\n\n\n\n# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))[\"y0h\",\"Pr(>|t|)\"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))[\"r_ly0ONy2_n_h\",\"Pr(>|t|)\"]\n}\ncat(\"Multiple: \", mean(multiple < 0.05), \"\\n\")\n# Multiple: 0.0529 \ncat(\" Stage: \", mean(stage < 0.05), \"\\n\")\n# Stage: 0.0527 \n\n\n\n\n\nObserve that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)\n\n\n\n\nUPDATE (1/2):\nI ran simulation code to compare some of the key models, (\"Full\") one where we actually aren't missing data, (\"Half\") one where we only use $h$ observations, (\"Estimated B\") where we regress $y_0$ on $y_2$ using all data points and then use the $h$ residuals as the independent variable in a regression with the residuals of $y_1$ regressed on $y_2$ (for the $h$ $y_1$ points we observe) and (\"Perfect A\", \"Perfect B\") then two versions where I calculate the perfect residuals of $y_0$ on $y_2$ using the exactly correct slope:\n\n\n\n\n\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))[\"y0rph\"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))[\"y0rph\"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (sfm)\" = sfm,\n \"Half Model (shm)\" = shm,\n \"Perfect A (shpa)\" = shpa,\n \"Perfect B (shpb)\" = shpb,\n \"Estimated B (sheb)\" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n\n\n\n\n\nAs you can see in the results above, the \"Estimated B\" version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points (\"Half Model\"), but it does have a bias.\n\n\n\n\nUPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from section 1.3.2 of this book (https://stefvanbuuren.name/fimd/sec-simplesolutions.html) and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:\n\n\n\n\n\n\n\n\n\nModel\nMean\nVariance\nBias\nBias_Sq\nMSE\nValid_Runs\n\n\n\n\n\n\n\n\n\tFull Model (N=40)\n\t0.66563\n\t0.02497\n\t-0.00103\n\t0.00000\n\t0.02497\n\t9947\n\n\n\n\n\n\n\tHalf Model (H=20)\n\t0.66289\n\t0.05542\n\t-0.00377\n\t0.00001\n\t0.05543\n\t9947\n\n\n\n\n\n\n\tEstimated B\n\t0.64330\n\t0.05259\n\t-0.02337\n\t0.00055\n\t0.05313\n\t9947\n\n\n\n\n\n\n\tLavaan Pairwise\n\t0.65849\n\t0.07174\n\t-0.00818\n\t0.00007\n\t0.07180\n\t9947\n\n\n\n\n\n\n\n\n\nI am including the code i ran below:\n\n\n\n\n# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(\"lavaan\")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- \"\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n\"\n\ncat(\"Running\", num_sims, \"simulations. Please wait...\\n\")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = \"pairwise.complete.obs\")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == \"y0\", \"est\"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (N=40)\" = sfm,\n \"Half Model (H=20)\" = shm,\n \"Estimated B\" = sheb,\n \"Lavaan Pairwise\" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(\"\\n--- Simulation Results ---\\n\")\nprint(round(results_matrix, 5))", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-22T12:39:55+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "E204A8FC-AC6E-48BB-AF80-E203CBC8615E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E204A8FC-AC6E-48BB-AF80-E203CBC8615E/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-22T20:46:45+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "18F1A87E-216E-4249-8293-E060F71CC55D", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/18F1A87E-216E-4249-8293-E060F71CC55D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-23T15:52:35+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "70469448-256D-43B2-80C1-746F337D6247", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/70469448-256D-43B2-80C1-746F337D6247/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-23T16:01:52+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "8C27F26B-7F68-4C8C-AF88-BCBF88FC34D5", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/8C27F26B-7F68-4C8C-AF88-BCBF88FC34D5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-23T16:53:21+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "7CE38AE1-F9CC-4D58-8A36-87CDCD90FB30", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7CE38AE1-F9CC-4D58-8A36-87CDCD90FB30/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "A Friendly Fish", "profile_url": "https://stats.stackexchange.com/users/398015/a-friendly-fish", "user_type": "registered"}, "created_at": "2026-08-23T17:02:49+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "AC468C9B-BCFF-4264-A45F-3229DC6759C1", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AC468C9B-BCFF-4264-A45F-3229DC6759C1/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how", "split": "train", "split_group": "0e07c1b9aeb4ed16810975d0835aae0ada37766b2c187a88bd4ee1b79bc9bf36", "tags": ["regression", "multiple-regression", "degrees-of-freedom", "type-i-and-ii-errors", "two-stage-least-squares"], "thread_id": "stats:676935", "title": "missing data: break multiple regression into stages; how?"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "Model <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeControl(msMaxIter=1000),\n weights = varIdent(form=~1|YearsTreatments),data = mydata)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676937, "sha256": "186bb1fbe667f4f1ab0dc3d65addbccd015f26d2465a66f918a041890744f97c", "source_url": "https://stats.stackexchange.com/questions/676937/treatment-comparisons-in-repeated-measures-mixed-model-ancova-with-a-baseline-co"}], "other_answers": [], "product": "code_qa", "question": "Hi could anyone please help me with this I would be really grateful. I am performing an mixed model ANCOVA to evaluate changes in a response variable (Height) over time and differences among treatments. The baseline measurement is included as a continuous covariate to account for initial differences among individuals. Because the same individuals were measured repeatedly over time, the repeated-measures structure is also accounted for in the model.The experiment is a block split plot experimental design of forestry experiment.\n\n\n\n\nMy model includes treatment, time, and the baseline covariate, including their interactions. I mean-centered the baseline covariate so that a value of zero represents the average baseline value.\n\n\n\n\nModel <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeControl(msMaxIter=1000),\n weights = varIdent(form=~1|YearsTreatments),data = mydata)\n\n\n\n\n\nFor post-hoc comparisons, I am using the emmeans package to compare treatments within each time point while setting the centered baseline covariate to zero (my model is box cox transformed). Therefore, these comparisons represent treatment differences for individuals with an average baseline value.\n\n\n\n\nIs this an appropriate way to perform and interpret the ANCOVA? In particular, if the treatment × time × baseline covariate interaction is significant, is it still appropriate to compare treatments within each time point using emmeans at the mean baseline value? My main objective is not related to initial height effect on the performance seedlings growth over time.Thanks", "record_id": "Scientific-Code-and-Analysis-QA:stats:676937", "selected_answer": {"answer_html": "If the treatment × time × baseline covariate interaction is significant, then the association between treatment/time and outcome depends on the value of the baseline covariate. It thus would make sense to evaluate treatment effects within each time point over a range of baseline covariate values. That should be easy to do with emmeans and will document whether the "statistically significant" 3-way interaction has much practical significance.
You should also consider, however, whether your model is mis-specified. Sometimes an apparently significant interaction term arises from a model that doesn't adequately capture the functional form of the association between outcome and predictors, in your case the outcome Height_BC and the baseline covariate H_2007_BC_c. A flexible fit of H_2007_BC_c with a regression spline or other generalized additive model might remove the need for the 3-way interaction.
That would seem to make sense in your application; a tree that is already near some practical maximum height might be expected to have less growth or response to treatment than a short tree would. I don't see how your model linear in H_2007_BC_c would capture that.
If the treatment × time × baseline covariate interaction is significant, then the association between treatment/time and outcome depends on the value of the baseline covariate. It thus would make sense to evaluate treatment effects within each time point over a range of baseline covariate values. That should be easy to do with emmeans and will document whether the "statistically significant" 3-way interaction has much practical significance.
You should also consider, however, whether your model is mis-specified. Sometimes an apparently significant interaction term arises from a model that doesn't adequately capture the functional form of the association between outcome and predictors, in your case the outcome Height_BC and the baseline covariate H_2007_BC_c. A flexible fit of H_2007_BC_c with a regression spline or other generalized additive model might remove the need for the 3-way interaction.
That would seem to make sense in your application; a tree that is already near some practical maximum height might be expected to have less growth or response to treatment than a short tree would. I don't see how your model linear in H_2007_BC_c would capture that.
Hi could anyone please help me with this I would be really grateful. I am performing an mixed model ANCOVA to evaluate changes in a response variable (Height) over time and differences among treatments. The baseline measurement is included as a continuous covariate to account for initial differences among individuals. Because the same individuals were measured repeatedly over time, the repeated-measures structure is also accounted for in the model.The experiment is a block split plot experimental design of forestry experiment.
\nMy model includes treatment, time, and the baseline covariate, including their interactions. I mean-centered the baseline covariate so that a value of zero represents the average baseline value.
\nModel <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeControl(msMaxIter=1000),\n weights = varIdent(form=~1|YearsTreatments),data = mydata)\n\nFor post-hoc comparisons, I am using the emmeans package to compare treatments within each time point while setting the centered baseline covariate to zero (my model is box cox transformed). Therefore, these comparisons represent treatment differences for individuals with an average baseline value.
\nIs this an appropriate way to perform and interpret the ANCOVA? In particular, if the treatment × time × baseline covariate interaction is significant, is it still appropriate to compare treatments within each time point using emmeans at the mean baseline value? My main objective is not related to initial height effect on the performance seedlings growth over time.Thanks
\n", "question_id": 676937, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Hi could anyone please help me with this I would be really grateful. I am performing an mixed model ANCOVA to evaluate changes in a response variable (Height) over time and differences among treatments. The baseline measurement is included as a continuous covariate to account for initial differences among individuals. Because the same individuals were measured repeatedly over time, the repeated-measures structure is also accounted for in the model.The experiment is a block split plot experimental design of forestry experiment.\n\n\n\n\nMy model includes treatment, time, and the baseline covariate, including their interactions. I mean-centered the baseline covariate so that a value of zero represents the average baseline value.\n\n\n\n\nModel <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeControl(msMaxIter=1000),\n weights = varIdent(form=~1|YearsTreatments),data = mydata)\n\n\n\n\n\nFor post-hoc comparisons, I am using the emmeans package to compare treatments within each time point while setting the centered baseline covariate to zero (my model is box cox transformed). Therefore, these comparisons represent treatment differences for individuals with an average baseline value.\n\n\n\n\nIs this an appropriate way to perform and interpret the ANCOVA? In particular, if the treatment × time × baseline covariate interaction is significant, is it still appropriate to compare treatments within each time point using emmeans at the mean baseline value? My main objective is not related to initial height effect on the performance seedlings growth over time.Thanks", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-22T22:19:04+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "2B53CAE3-9898-4BAD-A47C-F21FC6D2CDFE", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2B53CAE3-9898-4BAD-A47C-F21FC6D2CDFE/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-23T02:20:37+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "40D430F5-C4EA-404C-9500-73565E0A45AD", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/40D430F5-C4EA-404C-9500-73565E0A45AD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-23T02:26:05+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "9C8ADAEC-43F3-4E44-8D85-BE8C1ABA317C", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9C8ADAEC-43F3-4E44-8D85-BE8C1ABA317C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-23T02:31:15+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "F764FBDD-D5CE-4BB8-A654-2117D3C158FC", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F764FBDD-D5CE-4BB8-A654-2117D3C158FC/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Birma29", "profile_url": "https://stats.stackexchange.com/users/515697/birma29", "user_type": "registered"}, "created_at": "2026-08-23T14:48:42+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "A8739EA4-04E9-4855-B47E-7D431C971826", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A8739EA4-04E9-4855-B47E-7D431C971826/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-23T18:55:33+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "AA29DDF8-382A-4143-9646-FEE4954D97AA", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AA29DDF8-382A-4143-9646-FEE4954D97AA/view-source"}, {"content_license": null, "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-08-23T19:00:42+00:00", "raw_file": "raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json", "raw_sha256": "a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f", "revision_guid": "15EA9028-E0DB-4270-92D2-951EAA324FC1", "revision_number": 7, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/15EA9028-E0DB-4270-92D2-951EAA324FC1/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-24T15:03:00+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "DBC6C8CE-6537-48D0-B89E-53BB5FA32C91", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/DBC6C8CE-6537-48D0-B89E-53BB5FA32C91/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676937/treatment-comparisons-in-repeated-measures-mixed-model-ancova-with-a-baseline-co", "split": "train", "split_group": "39b688f3328bca92a43e0fb3eaf3d5aa37df78aa89e0d509aecbd58742da06f6", "tags": ["mixed-model", "lme4-nlme", "covariance", "ancova", "lsmeans"], "thread_id": "stats:676937", "title": "Treatment Comparisons in Repeated-Measures mixed model ANCOVA with a Baseline Covariate"}} {"accepted_answer": {"answer_html": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)
\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}
\nI guess I must have been so eager to verify the original results that I conditioned myself to "see" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.
\n", "answer_id": 676993, "answer_text": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)\n\n\n\n\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}\n\n\n\n\nI guess I must have been so eager to verify the original results that I conditioned myself to \"see\" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.", "answer_url": "https://stats.stackexchange.com/a/676993", "author": "Ettore S", "author_url": "https://stats.stackexchange.com/users/513606/ettore-s", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-28T23:08:55+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": 676952, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:08:55+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E33B0B4F-D54D-46E9-8E25-81C77E90B942", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:15:33+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "71D393BD-A8FB-4799-92AF-8FD04BFA27AE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}], "score": 0, "updated_at": "2026-08-28T23:15:33+00:00"}, "code_blocks": [{"block_index": 0, "code_text": " n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676952, "sha256": "fe8ee795d4c0d8f93e4394aef787c0dca0457bed49da29328a16bd289f7ec7c0", "source_url": "https://stats.stackexchange.com/questions/676952/hessian-with-invariably-positive-elements-for-zero-truncated-negative-binomial-r"}], "other_answers": [], "product": "code_qa", "question": "In the context of zero-truncated negative binomial regression (see this other post (https://stats.stackexchange.com/q/676385/513606)) , twice-differentiating the loglikelihood yields a well-known result (see e.g., footnote 5 in this paper (https://www.jstor.org/stable/2096628)):\n\n\n\n\n$$\n\\begin{aligned}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} -\\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{\\left(-2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T\n\\end{aligned}\n$$\n\n\n\n\nwhere:\n\n\n\n\n\n$y_i > 0 \\quad (i=1,2,\\dots,n)$ denotes the observed realisations (observations enter a zero-truncated sample only after the first count occurs);\n\n\n\n\n$\\mathbf{x}^T_i$ is the $i$-th row of the regression data matrix;\n\n\n\n\n$\\boldsymbol{\\beta}$ is the unknown vector of regression coefficients (to be estimated);\n\n\n\n\n$\\alpha$ is another unknown parameter to be estimated, namely the reciprocal of the so-called dispersion parameter ($\\alpha$ is inherited from the Poisson-Gamma mixture that brings about the unconstrained Negative Binomial see e.g., p.745, in this book (https://archive.org/details/econometricanaly0000gree_f4x3/econometricanaly0000gree_f4x3)).\n\n\n\n\nAlso notice that the first summation is just the Hessian of the \"parent\" specification: that one works fine i.e., its elements are negative as expected.\n\n\n\n\n\nThe above equation is correct as far as I can tell. Yet when I implement it in practice, it seems to invariably yield an Hessian with positive elements.\n\n\n\n\nMaybe this is a silly question, and it all depends on initialisation strategies etc.: but is it possible to ascertain whether the above-mentioned Hessian is, somehow, \"bound to\" have positive elements?\n\n\n\n\nI thought this should be a no brainer and I confess I didn't expect struggling on its implementation. Having re-checked the equations and code multiple times now, and tried different numerical examples, I begin to worry about being unable to get an Hessian with negative elements - which is what I need to implement the method of maximum likelihood using, say, textbook Newton-Raphson iterations.\n\n\n\n\nI appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.\n\n\n\n\nExample\n\n\n\n\nFor the sake of illustration, consider data(medpar) available from the R package COUNT. The data subset data_medpar <- medpar[,c(\"los\", \"died\", \"hmo\", \"type2\", \"type3\")] corresponds to the example reported in this STATA documentation for tnbreg (https://www.stata.com/manuals13/rtnbreg.pdf).\n\n\n\n\n\n\n\nInitialising the regression coefficients with a zero-truncated Poisson model gives me (intercept: 2.265; died: -0.248; hmo: -0.075; type2: 0.250; type3: 0.750) -- call this vector beta_iter;\n\n\n\n\n\n\n\n\n\nFollowing the alternating method of glm.nb from package MASS I also obtain an initial guess for $\\alpha$, call this scalar p_alpha <- 1.903 (what STATA calls alpha in the document is the recirpocal $\\theta=\\alpha^{-1}=0.525$ i.e. the so-called dispersion parameter).\n\n\n\n\n\n\n\n\n\nWith X the data matrix (including the intercept) and y the response variable vector corresponding to los I plug p_lambda = exp(X %*% beta_iter) and p_alpha in my R implementation below - which I believe should correspond to the second derivatives in question:\n\n\n\n\n n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n\n\n\n\n\n\n\n\n\nAnd I get a positive Hessian - as I always do\n\n\n\n\n> Hessian_iter\n [,1] [,2] [,3] [,4] [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,] 53431.28 53431.282 6036.786 12451.468 14079.196\n[3,] 24465.22 6036.786 24465.222 4528.242 1145.349\n[4,] 43243.07 12451.468 4528.242 43243.069 0.000\n[5,] 39578.77 14079.196 1145.349 0.000 39578.773\n\n\n\n\n\nAny thoughts? Am I missing anything trivial here? Thanks in advance.", "record_id": "Scientific-Code-and-Analysis-QA:stats:676952", "selected_answer": {"answer_html": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)
\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}
\nI guess I must have been so eager to verify the original results that I conditioned myself to "see" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.
\n", "answer_id": 676993, "answer_text": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)\n\n\n\n\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}\n\n\n\n\nI guess I must have been so eager to verify the original results that I conditioned myself to \"see\" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.", "answer_url": "https://stats.stackexchange.com/a/676993", "author": "Ettore S", "author_url": "https://stats.stackexchange.com/users/513606/ettore-s", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-28T23:08:55+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": 676952, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:08:55+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E33B0B4F-D54D-46E9-8E25-81C77E90B942", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:15:33+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "71D393BD-A8FB-4799-92AF-8FD04BFA27AE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}], "score": 0, "updated_at": "2026-08-28T23:15:33+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": 676993, "answers": [{"answer_html": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)
\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}
\nI guess I must have been so eager to verify the original results that I conditioned myself to "see" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.
\n", "answer_id": 676993, "answer_text": "As it turns out there is a mistake in Grogger and Carson's second derivatives of the zero-truncated negative binomial loglikelihood function wrt the regression parameters: blink and you'll miss it (the sign in one of the exponents should have been outside the parenthesis, probably a typo in the original)\n\n\n\n\n\\begin{align}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} - \\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^\\color{blue}{-\\left(2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T \n\\end{align}\n\n\n\n\nI guess I must have been so eager to verify the original results that I conditioned myself to \"see\" the original notation as correct - even when going through my own derivations over and over again. Few days away from this problem must have broken this perverse loop.", "answer_url": "https://stats.stackexchange.com/a/676993", "author": "Ettore S", "author_url": "https://stats.stackexchange.com/users/513606/ettore-s", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-28T23:08:55+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": 676952, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:08:55+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E33B0B4F-D54D-46E9-8E25-81C77E90B942", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E33B0B4F-D54D-46E9-8E25-81C77E90B942/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-28T23:15:33+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "71D393BD-A8FB-4799-92AF-8FD04BFA27AE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/71D393BD-A8FB-4799-92AF-8FD04BFA27AE/view-source"}], "score": 0, "updated_at": "2026-08-28T23:15:33+00:00"}], "domain": "statistics", "external_links": ["https://archive.org/details/econometricanaly0000gree_f4x3/econometricanaly0000gree_f4x3", "https://www.jstor.org/stable/2096628", "https://www.stata.com/manuals13/rtnbreg.pdf"], "medical_sensitive": false, "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": "Ettore S", "question_author_url": "https://stats.stackexchange.com/users/513606/ettore-s", "question_author_user_type": "registered", "question_created_at": "2026-08-24T16:36:39+00:00", "question_html": "In the context of zero-truncated negative binomial regression (see this other post) , twice-differentiating the loglikelihood yields a well-known result (see e.g., footnote 5 in this paper):
\n$$\n\\begin{aligned}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} -\\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{\\left(-2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T\n\\end{aligned}\n$$
\nwhere:
\nThe above equation is correct as far as I can tell. Yet when I implement it in practice, it seems to invariably yield an Hessian with positive elements.
\nMaybe this is a silly question, and it all depends on initialisation strategies etc.: but is it possible to ascertain whether the above-mentioned Hessian is, somehow, "bound to" have positive elements?
\nI thought this should be a no brainer and I confess I didn't expect struggling on its implementation. Having re-checked the equations and code multiple times now, and tried different numerical examples, I begin to worry about being unable to get an Hessian with negative elements - which is what I need to implement the method of maximum likelihood using, say, textbook Newton-Raphson iterations.
\nI appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.
\nFor the sake of illustration, consider data(medpar) available from the R package COUNT. The data subset data_medpar <- medpar[,c("los", "died", "hmo", "type2", "type3")] corresponds to the example reported in this STATA documentation for tnbreg.
Initialising the regression coefficients with a zero-truncated Poisson model gives me (intercept: 2.265; died: -0.248; hmo: -0.075; type2: 0.250; type3: 0.750) -- call this vector beta_iter;
Following the alternating method of glm.nb from package MASS I also obtain an initial guess for $\\alpha$, call this scalar p_alpha <- 1.903 (what STATA calls alpha in the document is the recirpocal $\\theta=\\alpha^{-1}=0.525$ i.e. the so-called dispersion parameter).
With X the data matrix (including the intercept) and y the response variable vector corresponding to los I plug p_lambda = exp(X %*% beta_iter) and p_alpha in my R implementation below - which I believe should correspond to the second derivatives in question:
n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n\nAnd I get a positive Hessian - as I always do
\n> Hessian_iter\n [,1] [,2] [,3] [,4] [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,] 53431.28 53431.282 6036.786 12451.468 14079.196\n[3,] 24465.22 6036.786 24465.222 4528.242 1145.349\n[4,] 43243.07 12451.468 4528.242 43243.069 0.000\n[5,] 39578.77 14079.196 1145.349 0.000 39578.773\n\nAny thoughts? Am I missing anything trivial here? Thanks in advance.
\n", "question_id": 676952, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "In the context of zero-truncated negative binomial regression (see this other post (https://stats.stackexchange.com/q/676385/513606)) , twice-differentiating the loglikelihood yields a well-known result (see e.g., footnote 5 in this paper (https://www.jstor.org/stable/2096628)):\n\n\n\n\n$$\n\\begin{aligned}\n\t\\frac{\\partial^2}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\ell_\\mathrm{ZTNB}{\\left(\\boldsymbol{\\beta},\\alpha\\right)} &= -\\sum_{i=1}^n{\\frac{1+\\alpha^{-1} y_i}{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^2}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T} -\\sum_{i=1}^n\\left\\{\\frac{\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\left(1+\\alpha\\right)}-e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(\\alpha^{-1}+1\\right)\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{\\left(-2+\\alpha\\right)}}{1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}} +\\right. \\nonumber \\\\ \n\t& \\quad \\left. -\\frac{e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-2(1+\\alpha)}}{\\left[1-\\left(1+\\alpha^{-1} e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\right)^{-\\alpha}\\right]^2}\\right\\}e^{\\mathbf{x}_i^T\\boldsymbol{\\beta}}\\mathbf{x}_i\\mathbf{x}_i^T\n\\end{aligned}\n$$\n\n\n\n\nwhere:\n\n\n\n\n\n$y_i > 0 \\quad (i=1,2,\\dots,n)$ denotes the observed realisations (observations enter a zero-truncated sample only after the first count occurs);\n\n\n\n\n$\\mathbf{x}^T_i$ is the $i$-th row of the regression data matrix;\n\n\n\n\n$\\boldsymbol{\\beta}$ is the unknown vector of regression coefficients (to be estimated);\n\n\n\n\n$\\alpha$ is another unknown parameter to be estimated, namely the reciprocal of the so-called dispersion parameter ($\\alpha$ is inherited from the Poisson-Gamma mixture that brings about the unconstrained Negative Binomial see e.g., p.745, in this book (https://archive.org/details/econometricanaly0000gree_f4x3/econometricanaly0000gree_f4x3)).\n\n\n\n\nAlso notice that the first summation is just the Hessian of the \"parent\" specification: that one works fine i.e., its elements are negative as expected.\n\n\n\n\n\nThe above equation is correct as far as I can tell. Yet when I implement it in practice, it seems to invariably yield an Hessian with positive elements.\n\n\n\n\nMaybe this is a silly question, and it all depends on initialisation strategies etc.: but is it possible to ascertain whether the above-mentioned Hessian is, somehow, \"bound to\" have positive elements?\n\n\n\n\nI thought this should be a no brainer and I confess I didn't expect struggling on its implementation. Having re-checked the equations and code multiple times now, and tried different numerical examples, I begin to worry about being unable to get an Hessian with negative elements - which is what I need to implement the method of maximum likelihood using, say, textbook Newton-Raphson iterations.\n\n\n\n\nI appreciate any pointer to help me understand what I might be getting wrong - a simple illustrative example below.\n\n\n\n\nExample\n\n\n\n\nFor the sake of illustration, consider data(medpar) available from the R package COUNT. The data subset data_medpar <- medpar[,c(\"los\", \"died\", \"hmo\", \"type2\", \"type3\")] corresponds to the example reported in this STATA documentation for tnbreg (https://www.stata.com/manuals13/rtnbreg.pdf).\n\n\n\n\n\n\n\nInitialising the regression coefficients with a zero-truncated Poisson model gives me (intercept: 2.265; died: -0.248; hmo: -0.075; type2: 0.250; type3: 0.750) -- call this vector beta_iter;\n\n\n\n\n\n\n\n\n\nFollowing the alternating method of glm.nb from package MASS I also obtain an initial guess for $\\alpha$, call this scalar p_alpha <- 1.903 (what STATA calls alpha in the document is the recirpocal $\\theta=\\alpha^{-1}=0.525$ i.e. the so-called dispersion parameter).\n\n\n\n\n\n\n\n\n\nWith X the data matrix (including the intercept) and y the response variable vector corresponding to los I plug p_lambda = exp(X %*% beta_iter) and p_alpha in my R implementation below - which I believe should correspond to the second derivatives in question:\n\n\n\n\n n_regressors <- ncol(X)\n n_observ <- nrow(X)\n phi_sub <- (1 + p_theta*p_lambda)\n H_parent <- ((1 + p_theta*y) / phi_sub^2)*p_lambda\n if(zerotrunc){\n phi_sub_1a <- (1 / (phi_sub)^(1+p_alpha))\n phi <- (1/(1 + p_theta*p_lambda)^p_alpha) \n H_zt_A <- ( p_lambda*phi_sub_1a / (1 - phi) )^2\n H_zt_B <- ( p_lambda*phi_sub_1a - (p_lambda^2 * (p_theta + 1) * phi_sub^(-2+p_alpha)) ) / (1 - phi)\n }\n\n Hessian_iter <- matrix(0L,nrow = n_regressors, ncol = n_regressors)\n for(i in 1:n_observ){\n x <- X[i,]\n x <- as.numeric(x)\n outprod_X <- (x %o% x) \n A <- H_parent[i]\n if(zerotrunc){\n B <- H_zt_A[i]\n C <- H_zt_B[i]\n } else {\n B <- C <- 0\n }\n Hessian_iter <- Hessian_iter - ( A - B + C )*outprod_X \n }\n\n\n\n\n\n\n\n\n\nAnd I get a positive Hessian - as I always do\n\n\n\n\n> Hessian_iter\n [,1] [,2] [,3] [,4] [,5]\n[1,] 200849.45 53431.282 24465.222 43243.069 39578.773\n[2,] 53431.28 53431.282 6036.786 12451.468 14079.196\n[3,] 24465.22 6036.786 24465.222 4528.242 1145.349\n[4,] 43243.07 12451.468 4528.242 43243.069 0.000\n[5,] 39578.77 14079.196 1145.349 0.000 39578.773\n\n\n\n\n\nAny thoughts? Am I missing anything trivial here? Thanks in advance.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-24T16:36:39+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "07E45709-2DC4-449E-9EF1-F194BCC37017", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/07E45709-2DC4-449E-9EF1-F194BCC37017/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ettore S", "profile_url": "https://stats.stackexchange.com/users/513606/ettore-s", "user_type": "registered"}, "created_at": "2026-08-24T16:44:54+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "62966E35-E17B-49AB-8C07-589F8E1C8272", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/62966E35-E17B-49AB-8C07-589F8E1C8272/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676952/hessian-with-invariably-positive-elements-for-zero-truncated-negative-binomial-r", "split": "test", "split_group": "7b59a2f46aa3d8cb6ef7b86f03502a2ea8a90a231427a0a51d2360f8ed2dd472", "tags": ["nonlinear-regression", "count-data", "negative-binomial-distribution", "hessian", "truncated-distributions"], "thread_id": "stats:676952", "title": "Hessian with invariably positive elements for zero-truncated negative binomial regression"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "data(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676959, "sha256": "64967942425141864eb927a2a7cb6a1dc7e759da705a95dcd025ba9c190e166e", "source_url": "https://stats.stackexchange.com/a/676959"}, {"block_index": 3, "code_text": "predict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676959, "sha256": "8d8e20779f4179423d77d243048d7e5f763f42bf264089a5019e3583544c0a46", "source_url": "https://stats.stackexchange.com/a/676959"}, {"block_index": 4, "code_text": "m3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676959, "sha256": "ce7646376cb93ca32ea69ecd574e3065621a1d537fe4b63606bb4d392e01ff13", "source_url": "https://stats.stackexchange.com/a/676959"}], "other_answers": [], "product": "code_qa", "question": "For homework assignment regarding stepwise regression (along with forward and backwards) the professor said to scale all the data except for the response and categorical variables.\n\n\n\n\nI suppose I somewhat can understand the categorical variables they can only be binary values. However I don't understand why the response variable was excluded.\n\n\n\n\nWhen scaling data for other models we usually scale the entire dataset so I'm confused why in this instance it's not included.", "record_id": "Scientific-Code-and-Analysis-QA:stats:676958", "selected_answer": {"answer_html": "In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:
\ndata(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n\nCoefficients in m2 are simply m1 coefficients divided by sd(mpg):
sd(mtcars$mpg)\n#> [1] 6.026948\n\nround(coef(m1)[-1] / coef(m2)[-1], 2)\n#> scale(wt) scale(hp) scale(disp) \n#> 6.03 6.03 6.03\n\nThey carry no additional information. P-values are identical, so stepwise selection makes the same decision either way:
\nsummary(m1)$coefficients[-1, "Pr(>|t|)"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nsummary(m2)$coefficients[-1, "Pr(>|t|)"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nMoreover, the response is what we actually care about understanding. Scaling it means predictions are in standard deviations of mpg rather than miles per gallon, which is harder to interpret and communicate:
\npredict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n\nScaling predictors matters because it puts variables with different units on the same footing, making coefficient magnitudes comparable across predictors. The response does not need this. We are not comparing it to anything, we are trying to explain it.
\nFor categorical variables, scaling a 0/1 indicator loses interpretability. The coefficient of an unscaled binary variable represents the difference between groups in the original units of the response:
\nm3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n\nfactor(cyl) gives separate interpretable coefficients for each cylinder group relative to the 4-cylinder baseline directly answering how much mpg changes going from 4 to 6 or 8 cylinders. scale(cyl) collapses this into a single slope assuming equal spacing between cylinder counts, and the coefficient is now per standard deviation of cyl rather than per cylinder group.
Created on 2026-08-25 with reprex v2.1.1
\n", "answer_id": 676959, "answer_text": "In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:\n\n\n\n\ndata(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n\n\n\n\n\nCoefficients in m2 are simply m1 coefficients divided by sd(mpg):\n\n\n\n\nsd(mtcars$mpg)\n#> [1] 6.026948\n\nround(coef(m1)[-1] / coef(m2)[-1], 2)\n#> scale(wt) scale(hp) scale(disp) \n#> 6.03 6.03 6.03\n\n\n\n\n\nThey carry no additional information. P-values are identical, so stepwise selection makes the same decision either way:\n\n\n\n\nsummary(m1)$coefficients[-1, \"Pr(>|t|)\"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nsummary(m2)$coefficients[-1, \"Pr(>|t|)\"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\n\n\n\n\nMoreover, the response is what we actually care about understanding. Scaling it means predictions are in standard deviations of mpg rather than miles per gallon, which is harder to interpret and communicate:\n\n\n\n\npredict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n\n\n\n\n\nScaling predictors matters because it puts variables with different units on the same footing, making coefficient magnitudes comparable across predictors. The response does not need this. We are not comparing it to anything, we are trying to explain it.\n\n\n\n\nFor categorical variables, scaling a 0/1 indicator loses interpretability. The coefficient of an unscaled binary variable represents the difference between groups in the original units of the response:\n\n\n\n\nm3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n\n\n\n\n\nfactor(cyl) gives separate interpretable coefficients for each cylinder group relative to the 4-cylinder baseline directly answering how much mpg changes going from 4 to 6 or 8 cylinders. scale(cyl) collapses this into a single slope assuming equal spacing between cylinder counts, and the coefficient is now per standard deviation of cyl rather than per cylinder group.\n\n\n\n\nCreated on 2026-08-25 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/676959", "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-25T19:05:50+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": 676958, "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-25T19:05:50+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "572E3B4E-1F43-4F40-91AA-292255EC61E9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/572E3B4E-1F43-4F40-91AA-292255EC61E9/view-source"}], "score": 11, "updated_at": "2026-08-25T19:05:50+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:
\ndata(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n\nCoefficients in m2 are simply m1 coefficients divided by sd(mpg):
sd(mtcars$mpg)\n#> [1] 6.026948\n\nround(coef(m1)[-1] / coef(m2)[-1], 2)\n#> scale(wt) scale(hp) scale(disp) \n#> 6.03 6.03 6.03\n\nThey carry no additional information. P-values are identical, so stepwise selection makes the same decision either way:
\nsummary(m1)$coefficients[-1, "Pr(>|t|)"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nsummary(m2)$coefficients[-1, "Pr(>|t|)"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nMoreover, the response is what we actually care about understanding. Scaling it means predictions are in standard deviations of mpg rather than miles per gallon, which is harder to interpret and communicate:
\npredict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n\nScaling predictors matters because it puts variables with different units on the same footing, making coefficient magnitudes comparable across predictors. The response does not need this. We are not comparing it to anything, we are trying to explain it.
\nFor categorical variables, scaling a 0/1 indicator loses interpretability. The coefficient of an unscaled binary variable represents the difference between groups in the original units of the response:
\nm3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n\nfactor(cyl) gives separate interpretable coefficients for each cylinder group relative to the 4-cylinder baseline directly answering how much mpg changes going from 4 to 6 or 8 cylinders. scale(cyl) collapses this into a single slope assuming equal spacing between cylinder counts, and the coefficient is now per standard deviation of cyl rather than per cylinder group.
Created on 2026-08-25 with reprex v2.1.1
\n", "answer_id": 676959, "answer_text": "In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:\n\n\n\n\ndata(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 20.0906 -3.7190 -2.1362 -0.1161\n\nround(coef(m2), 4)\n#> (Intercept) scale(wt) scale(hp) scale(disp) \n#> 0.0000 -0.6171 -0.3544 -0.0193\n\n\n\n\n\nCoefficients in m2 are simply m1 coefficients divided by sd(mpg):\n\n\n\n\nsd(mtcars$mpg)\n#> [1] 6.026948\n\nround(coef(m1)[-1] / coef(m2)[-1], 2)\n#> scale(wt) scale(hp) scale(disp) \n#> 6.03 6.03 6.03\n\n\n\n\n\nThey carry no additional information. P-values are identical, so stepwise selection makes the same decision either way:\n\n\n\n\nsummary(m1)$coefficients[-1, \"Pr(>|t|)\"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\nsummary(m2)$coefficients[-1, \"Pr(>|t|)\"]\n#> scale(wt) scale(hp) scale(disp) \n#> 0.001330991 0.010971032 0.928507029\n\n\n\n\n\nMoreover, the response is what we actually care about understanding. Scaling it means predictions are in standard deviations of mpg rather than miles per gallon, which is harder to interpret and communicate:\n\n\n\n\npredict(m1, newdata = data.frame(wt = 3, hp = 100, disp = 200))\n#> 1 \n#> 22.39978\n\npred_scaled <- predict(m2, newdata = data.frame(wt = 3, hp = 100, disp = 200))\npred_scaled\n#> 1 \n#> 0.3831378\npred_scaled * sd(mtcars$mpg) + mean(mtcars$mpg)\n#> 1 \n#> 22.39978\n\n\n\n\n\nScaling predictors matters because it puts variables with different units on the same footing, making coefficient magnitudes comparable across predictors. The response does not need this. We are not comparing it to anything, we are trying to explain it.\n\n\n\n\nFor categorical variables, scaling a 0/1 indicator loses interpretability. The coefficient of an unscaled binary variable represents the difference between groups in the original units of the response:\n\n\n\n\nm3 <- lm(mpg ~ scale(wt) + scale(hp) + factor(cyl), data = mtcars)\nm4 <- lm(mpg ~ scale(wt) + scale(hp) + scale(cyl), data = mtcars)\n\ncoef(m3)\n#> (Intercept) scale(wt) scale(hp) factor(cyl)6 factor(cyl)8 \n#> 22.219236 -3.112868 -1.585160 -3.359025 -3.185884\ncoef(m4)\n#> (Intercept) scale(wt) scale(hp) scale(cyl) \n#> 20.090625 -3.098748 -1.236744 -1.681654\n\n\n\n\n\nfactor(cyl) gives separate interpretable coefficients for each cylinder group relative to the 4-cylinder baseline directly answering how much mpg changes going from 4 to 6 or 8 cylinders. scale(cyl) collapses this into a single slope assuming equal spacing between cylinder counts, and the coefficient is now per standard deviation of cyl rather than per cylinder group.\n\n\n\n\nCreated on 2026-08-25 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/676959", "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-25T19:05:50+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": 676958, "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-25T19:05:50+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "572E3B4E-1F43-4F40-91AA-292255EC61E9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/572E3B4E-1F43-4F40-91AA-292255EC61E9/view-source"}], "score": 11, "updated_at": "2026-08-25T19:05:50+00:00"}], "domain": "statistics", "external_links": ["https://reprex.tidyverse.org"], "medical_sensitive": false, "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": "Karl Suh", "question_author_url": "https://stats.stackexchange.com/users/513622/karl-suh", "question_author_user_type": "registered", "question_created_at": "2026-08-25T17:43:52+00:00", "question_html": "For homework assignment regarding stepwise regression (along with forward and backwards) the professor said to scale all the data except for the response and categorical variables.
\nI suppose I somewhat can understand the categorical variables they can only be binary values. However I don't understand why the response variable was excluded.
\nWhen scaling data for other models we usually scale the entire dataset so I'm confused why in this instance it's not included.
\n", "question_id": 676958, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "For homework assignment regarding stepwise regression (along with forward and backwards) the professor said to scale all the data except for the response and categorical variables.\n\n\n\n\nI suppose I somewhat can understand the categorical variables they can only be binary values. However I don't understand why the response variable was excluded.\n\n\n\n\nWhen scaling data for other models we usually scale the entire dataset so I'm confused why in this instance it's not included.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Karl Suh", "profile_url": "https://stats.stackexchange.com/users/513622/karl-suh", "user_type": "registered"}, "created_at": "2026-08-25T17:43:52+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "4082C60D-8D85-46BC-9D47-179A8B66E184", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/4082C60D-8D85-46BC-9D47-179A8B66E184/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-26T01:49:11+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "1BA401BC-F034-41AE-8F89-81E5097845A1", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/1BA401BC-F034-41AE-8F89-81E5097845A1/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676958/for-stepwise-regression-when-scaling-the-data-why-not-scale-the-response-and-ca", "split": "train", "split_group": "4fe50e1b22b7e2f9bed9d1b79bf1ec7f398cf2d4491c96672ea2ca7f02f416ed", "tags": ["standardization", "stepwise-regression"], "thread_id": "stats:676958", "title": "For stepwise regression, when scaling the data why not scale the response and categorical variables?"}} {"accepted_answer": {"answer_html": "You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).
\nIn your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being "other" or "everything else", or in this specific case, "anything but seagrass".
\n\n\ncould I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?
\n
Yes, that sounds OK. The relationship could be with something or things in the "not seagrass" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.
\n", "answer_id": 676973, "answer_text": "You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).\n\n\n\n\nIn your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being \"other\" or \"everything else\", or in this specific case, \"anything but seagrass\".\n\n\n\n\n\n\n\ncould I say something like \"fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover\"?\n\n\n\n\n\n\n\nYes, that sounds OK. The relationship could be with something or things in the \"not seagrass\" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.", "answer_url": "https://stats.stackexchange.com/a/676973", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-27T08:11:49+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": 676971, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-27T08:11:49+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "091B2890-FB1C-44AC-85E1-2C6A5AD73A18", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/091B2890-FB1C-44AC-85E1-2C6A5AD73A18/view-source"}], "score": 1, "updated_at": "2026-08-27T08:11:49+00:00"}, "code_blocks": [{"block_index": 1, "code_text": "# There are many zeros, so just showing a glimpse of the data here\n\n# ave_?? = species-specific seagrass \n# ave_sav = Average % cover of ALL aquatic vegetation\n# total_ave_sg = ave_tt + ave_hw + ave_sf + ave_rm (sum of average seagrass cover by species)\n\n> SAV <- shiny_toad %>% dplyr::select(CYR_Keyfield, total_count, ave_sav, total_ave_ma, \n+ total_ave_sg, ave_tt, ave_hw, ave_sf, ave_rm) %>%\n+ mutate(debris = ave_sav - (total_ave_sg + total_ave_ma)) %>%\n+ filter(debris >0 & total_count >0)\n> SAV[sample(nrow(SAV), 10), ]\n CYR_Keyfield total_count ave_sav total_ave_ma total_ave_sg ave_tt ave_hw ave_sf ave_rm debris\n103 C-2019-9-18-11 1 43.5 14.0 24.4 8.8 15.6 0 0 5.1\n90 C-2019-3-5-27 3 82.0 43.7 30.2 17.1 13.1 0 0 8.1\n70 C-2018-9-10-10 1 51.5 14.4 18.3 16.6 1.7 0 0 18.8\n79 C-2019-3-3-41 4 80.5 26.4 43.3 42.5 0.8 0 0 10.8\n116 C-2020-9-4-27 2 92.5 17.1 49.0 28.5 20.5 0 0 26.4\n14 C-2013-9-8-6 1 100.0 22.5 15.3 0.0 15.3 0 0 62.2\n126 C-2022-2-28-44 1 58.0 16.0 23.5 6.0 17.5 0 0 18.5\n62 C-2017-3-13-17 2 88.0 48.5 28.6 28.5 0.1 0 0 10.9\n4 C-2013-9-3-43 1 51.0 8.8 40.7 40.5 0.2 0 0 1.5\n132 C-2023-3-6-40 4 55.0 17.5 30.0 19.0 11.0 0 0 7.5\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676971, "sha256": "b1100c502751f045ff1b651b04807a59d3a1207fc2d8be9e5c39703fe2c3c434", "source_url": "https://stats.stackexchange.com/questions/676971/acceptable-conclusions-to-draw-from-incomplete-compositional-data-as-a-model-cov"}], "other_answers": [], "product": "code_qa", "question": "What can be inferred about the relationship between an outcome and a predictor variable (in a statistical model) that is only a piece of compositional data?\n\n\n\n\nI have submerged aquatic vegetation data (underwater seagrass, algae, etc.) by survey calendar year, month, day, and site (CYR_Keyfield). I want to model fish counts vs seagrass (only) cover, but seagrass is just a piece of total cover (ave_sav) in terms of area surveyed. The problem, as I see it, is when seagrass cover=0, that doesn't mean \"no vegetation cover at all\". I have background literature for why I think seagrass specifically is important, but I'm not sure the effect of seagrass can be separated without a proper control (downside of observational studies). It is analogous to testing the effects of \"drug A\", but not accounting for \"drug B\" mixed in. Modeling rows with seagrass-only cover removes about 90% of my data, so that's out.\n\n\n\n\nCount ~ All seagrass cover (%) + random site intercept\n\n\n\n\n\nCould I say something like \"fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover\"?\n\n\n\n\nWould this be sufficient to avoid a claim for a causal link?\n\n\n\n\nThis is observational data where each site is surveyed 10x for an average % cover of aquatic vegetation (out of 100% of total area surveyed and average is 1 m$^2$ cover). total_count is fish abundance.\n\n\n\n\nData:\n\n\n\n\n# There are many zeros, so just showing a glimpse of the data here\n\n# ave_?? = species-specific seagrass \n# ave_sav = Average % cover of ALL aquatic vegetation\n# total_ave_sg = ave_tt + ave_hw + ave_sf + ave_rm (sum of average seagrass cover by species)\n\n> SAV <- shiny_toad %>% dplyr::select(CYR_Keyfield, total_count, ave_sav, total_ave_ma, \n+ total_ave_sg, ave_tt, ave_hw, ave_sf, ave_rm) %>%\n+ mutate(debris = ave_sav - (total_ave_sg + total_ave_ma)) %>%\n+ filter(debris >0 & total_count >0)\n> SAV[sample(nrow(SAV), 10), ]\n CYR_Keyfield total_count ave_sav total_ave_ma total_ave_sg ave_tt ave_hw ave_sf ave_rm debris\n103 C-2019-9-18-11 1 43.5 14.0 24.4 8.8 15.6 0 0 5.1\n90 C-2019-3-5-27 3 82.0 43.7 30.2 17.1 13.1 0 0 8.1\n70 C-2018-9-10-10 1 51.5 14.4 18.3 16.6 1.7 0 0 18.8\n79 C-2019-3-3-41 4 80.5 26.4 43.3 42.5 0.8 0 0 10.8\n116 C-2020-9-4-27 2 92.5 17.1 49.0 28.5 20.5 0 0 26.4\n14 C-2013-9-8-6 1 100.0 22.5 15.3 0.0 15.3 0 0 62.2\n126 C-2022-2-28-44 1 58.0 16.0 23.5 6.0 17.5 0 0 18.5\n62 C-2017-3-13-17 2 88.0 48.5 28.6 28.5 0.1 0 0 10.9\n4 C-2013-9-3-43 1 51.0 8.8 40.7 40.5 0.2 0 0 1.5\n132 C-2023-3-6-40 4 55.0 17.5 30.0 19.0 11.0 0 0 7.5", "record_id": "Scientific-Code-and-Analysis-QA:stats:676971", "selected_answer": {"answer_html": "You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).
\nIn your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being "other" or "everything else", or in this specific case, "anything but seagrass".
\n\n\ncould I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?
\n
Yes, that sounds OK. The relationship could be with something or things in the "not seagrass" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.
\n", "answer_id": 676973, "answer_text": "You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).\n\n\n\n\nIn your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being \"other\" or \"everything else\", or in this specific case, \"anything but seagrass\".\n\n\n\n\n\n\n\ncould I say something like \"fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover\"?\n\n\n\n\n\n\n\nYes, that sounds OK. The relationship could be with something or things in the \"not seagrass\" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.", "answer_url": "https://stats.stackexchange.com/a/676973", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-27T08:11:49+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": 676971, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-27T08:11:49+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "091B2890-FB1C-44AC-85E1-2C6A5AD73A18", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/091B2890-FB1C-44AC-85E1-2C6A5AD73A18/view-source"}], "score": 1, "updated_at": "2026-08-27T08:11:49+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": 676973, "answers": [{"answer_html": "You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).
\nIn your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being "other" or "everything else", or in this specific case, "anything but seagrass".
\n\n\ncould I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?
\n
Yes, that sounds OK. The relationship could be with something or things in the "not seagrass" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.
\n", "answer_id": 676973, "answer_text": "You should think of compositions like this as really being for $c + 1$ classes of things. You are thinking of sea grass cover as a univariate term, but it is really a 2-d space of the positive continuous values $(0,1)^2$ whose pairs sum to 1 (or some other value if plants overlap, but then things get more complicated).\n\n\n\n\nIn your case $c = 1$, but you have 2 classes or states. I link to think of this extra class as being \"other\" or \"everything else\", or in this specific case, \"anything but seagrass\".\n\n\n\n\n\n\n\ncould I say something like \"fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover\"?\n\n\n\n\n\n\n\nYes, that sounds OK. The relationship could be with something or things in the \"not seagrass\" category but you can't tell that from your data. You would need to manipulate only sea grass to determine this.", "answer_url": "https://stats.stackexchange.com/a/676973", "author": "Gavin Simpson", "author_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-27T08:11:49+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": 676971, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Gavin Simpson", "profile_url": "https://stats.stackexchange.com/users/1390/gavin-simpson", "user_type": "registered"}, "created_at": "2026-08-27T08:11:49+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "091B2890-FB1C-44AC-85E1-2C6A5AD73A18", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/091B2890-FB1C-44AC-85E1-2C6A5AD73A18/view-source"}], "score": 1, "updated_at": "2026-08-27T08:11:49+00:00"}], "domain": "statistics", "external_links": [], "medical_sensitive": false, "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": "Nate", "question_author_url": "https://stats.stackexchange.com/users/337106/nate", "question_author_user_type": "registered", "question_created_at": "2026-08-26T20:02:31+00:00", "question_html": "What can be inferred about the relationship between an outcome and a predictor variable (in a statistical model) that is only a piece of compositional data?
\nI have submerged aquatic vegetation data (underwater seagrass, algae, etc.) by survey calendar year, month, day, and site (CYR_Keyfield). I want to model fish counts vs seagrass (only) cover, but seagrass is just a piece of total cover (ave_sav) in terms of area surveyed. The problem, as I see it, is when seagrass cover=0, that doesn't mean "no vegetation cover at all". I have background literature for why I think seagrass specifically is important, but I'm not sure the effect of seagrass can be separated without a proper control (downside of observational studies). It is analogous to testing the effects of "drug A", but not accounting for "drug B" mixed in. Modeling rows with seagrass-only cover removes about 90% of my data, so that's out.
Count ~ All seagrass cover (%) + random site intercept\n\nCould I say something like "fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover"?
\nWould this be sufficient to avoid a claim for a causal link?
\nThis is observational data where each site is surveyed 10x for an average % cover of aquatic vegetation (out of 100% of total area surveyed and average is 1 m$^2$ cover). total_count is fish abundance.
Data:
\n# There are many zeros, so just showing a glimpse of the data here\n\n# ave_?? = species-specific seagrass \n# ave_sav = Average % cover of ALL aquatic vegetation\n# total_ave_sg = ave_tt + ave_hw + ave_sf + ave_rm (sum of average seagrass cover by species)\n\n> SAV <- shiny_toad %>% dplyr::select(CYR_Keyfield, total_count, ave_sav, total_ave_ma, \n+ total_ave_sg, ave_tt, ave_hw, ave_sf, ave_rm) %>%\n+ mutate(debris = ave_sav - (total_ave_sg + total_ave_ma)) %>%\n+ filter(debris >0 & total_count >0)\n> SAV[sample(nrow(SAV), 10), ]\n CYR_Keyfield total_count ave_sav total_ave_ma total_ave_sg ave_tt ave_hw ave_sf ave_rm debris\n103 C-2019-9-18-11 1 43.5 14.0 24.4 8.8 15.6 0 0 5.1\n90 C-2019-3-5-27 3 82.0 43.7 30.2 17.1 13.1 0 0 8.1\n70 C-2018-9-10-10 1 51.5 14.4 18.3 16.6 1.7 0 0 18.8\n79 C-2019-3-3-41 4 80.5 26.4 43.3 42.5 0.8 0 0 10.8\n116 C-2020-9-4-27 2 92.5 17.1 49.0 28.5 20.5 0 0 26.4\n14 C-2013-9-8-6 1 100.0 22.5 15.3 0.0 15.3 0 0 62.2\n126 C-2022-2-28-44 1 58.0 16.0 23.5 6.0 17.5 0 0 18.5\n62 C-2017-3-13-17 2 88.0 48.5 28.6 28.5 0.1 0 0 10.9\n4 C-2013-9-3-43 1 51.0 8.8 40.7 40.5 0.2 0 0 1.5\n132 C-2023-3-6-40 4 55.0 17.5 30.0 19.0 11.0 0 0 7.5\n\n", "question_id": 676971, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "What can be inferred about the relationship between an outcome and a predictor variable (in a statistical model) that is only a piece of compositional data?\n\n\n\n\nI have submerged aquatic vegetation data (underwater seagrass, algae, etc.) by survey calendar year, month, day, and site (CYR_Keyfield). I want to model fish counts vs seagrass (only) cover, but seagrass is just a piece of total cover (ave_sav) in terms of area surveyed. The problem, as I see it, is when seagrass cover=0, that doesn't mean \"no vegetation cover at all\". I have background literature for why I think seagrass specifically is important, but I'm not sure the effect of seagrass can be separated without a proper control (downside of observational studies). It is analogous to testing the effects of \"drug A\", but not accounting for \"drug B\" mixed in. Modeling rows with seagrass-only cover removes about 90% of my data, so that's out.\n\n\n\n\nCount ~ All seagrass cover (%) + random site intercept\n\n\n\n\n\nCould I say something like \"fish counts were associated with an...(increase/decrease..whatever it happens to be) in total seagrass cover\"?\n\n\n\n\nWould this be sufficient to avoid a claim for a causal link?\n\n\n\n\nThis is observational data where each site is surveyed 10x for an average % cover of aquatic vegetation (out of 100% of total area surveyed and average is 1 m$^2$ cover). total_count is fish abundance.\n\n\n\n\nData:\n\n\n\n\n# There are many zeros, so just showing a glimpse of the data here\n\n# ave_?? = species-specific seagrass \n# ave_sav = Average % cover of ALL aquatic vegetation\n# total_ave_sg = ave_tt + ave_hw + ave_sf + ave_rm (sum of average seagrass cover by species)\n\n> SAV <- shiny_toad %>% dplyr::select(CYR_Keyfield, total_count, ave_sav, total_ave_ma, \n+ total_ave_sg, ave_tt, ave_hw, ave_sf, ave_rm) %>%\n+ mutate(debris = ave_sav - (total_ave_sg + total_ave_ma)) %>%\n+ filter(debris >0 & total_count >0)\n> SAV[sample(nrow(SAV), 10), ]\n CYR_Keyfield total_count ave_sav total_ave_ma total_ave_sg ave_tt ave_hw ave_sf ave_rm debris\n103 C-2019-9-18-11 1 43.5 14.0 24.4 8.8 15.6 0 0 5.1\n90 C-2019-3-5-27 3 82.0 43.7 30.2 17.1 13.1 0 0 8.1\n70 C-2018-9-10-10 1 51.5 14.4 18.3 16.6 1.7 0 0 18.8\n79 C-2019-3-3-41 4 80.5 26.4 43.3 42.5 0.8 0 0 10.8\n116 C-2020-9-4-27 2 92.5 17.1 49.0 28.5 20.5 0 0 26.4\n14 C-2013-9-8-6 1 100.0 22.5 15.3 0.0 15.3 0 0 62.2\n126 C-2022-2-28-44 1 58.0 16.0 23.5 6.0 17.5 0 0 18.5\n62 C-2017-3-13-17 2 88.0 48.5 28.6 28.5 0.1 0 0 10.9\n4 C-2013-9-3-43 1 51.0 8.8 40.7 40.5 0.2 0 0 1.5\n132 C-2023-3-6-40 4 55.0 17.5 30.0 19.0 11.0 0 0 7.5", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-08-26T20:02:31+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "BBA3A123-C04E-4867-9529-FDABB64EDA28", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/BBA3A123-C04E-4867-9529-FDABB64EDA28/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-08-27T08:29:59+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "2C063616-3FA6-44EE-924F-76F90F6F8FF5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2C063616-3FA6-44EE-924F-76F90F6F8FF5/view-source"}, {"content_license": null, "contributor": {"display_name": "kjetil b halvorsen", "profile_url": "https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen", "user_type": "moderator"}, "created_at": "2026-08-27T13:02:45+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "20074645-B552-43C0-B76B-009D7B7615A0", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/20074645-B552-43C0-B76B-009D7B7615A0/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-27T13:05:23+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "F65BAED3-ACE9-40FD-9E99-FB55CD1FAA2F", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/F65BAED3-ACE9-40FD-9E99-FB55CD1FAA2F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-08-27T13:19:25+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "55EC26AD-487A-4FD1-B6E0-348E7600A650", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/55EC26AD-487A-4FD1-B6E0-348E7600A650/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676971/acceptable-conclusions-to-draw-from-incomplete-compositional-data-as-a-model-cov", "split": "holdout", "split_group": "2b7ea007a91a90c8ab3592874d45af4342235e8995ca24e80227af4309c82293", "tags": ["mixed-model", "ecology", "observational-study", "compositional-data"], "thread_id": "stats:676971", "title": "Acceptable conclusions to draw from incomplete compositional data as a model covariate?"}}
{"accepted_answer": {"answer_html": "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.
age * (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.
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\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).
The reference level is Adults, so coefficients are interpreted as:
\ntime: pre-intervention slope for adults (prevalence per month)ageChildren:time: additional slope for children;The same logic applies for all ramp and step terms.
coef(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\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
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\nCreated on 2026-08-29 with reprex v2.1.1
\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": "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.
age * (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.
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\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).
The reference level is Adults, so coefficients are interpreted as:
\ntime: pre-intervention slope for adults (prevalence per month)ageChildren:time: additional slope for children;The same logic applies for all ramp and step terms.
coef(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\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
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\nCreated on 2026-08-29 with reprex v2.1.1
\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": "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.
age * (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.
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\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).
The reference level is Adults, so coefficients are interpreted as:
\ntime: pre-intervention slope for adults (prevalence per month)ageChildren:time: additional slope for children;The same logic applies for all ramp and step terms.
coef(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\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
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\nCreated on 2026-08-29 with reprex v2.1.1
\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": "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\n\nI started with children.
\nI constructed the ITS variables for the 3 interventions (step1, ramp1, step2, ramp2, step3, ramp3) following Schaffer et al. and Xiao et al.
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\nAccording to this thread, 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.
According to Schaffer et al., 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\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, 22].
\n
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\nShould I just apply the same strategy to adults? Or can such models handle correlated/stratified time series?
\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).
I have also read about nlme::gls() but I would like guidance/confirmation whether it is more appropriate.
BTW, I am not satisfied with the fit, but I will explore that once I have decided the modelling strategy.
\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", "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": "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.
\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.
\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.
\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.
\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": "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.
\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.
\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.
\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.
\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": "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?
\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.
here's some of the output of the final model, with fixed dispersion:
\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\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--- 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\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--- 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(can't add more plots, I guess)
\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": null, "code_blocks": [{"block_index": 0, "code_text": "data(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"weighted OUF AKDE\"[\"C\"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"OUF AKDE\"[\"C\"]))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 676997, "sha256": "23b3b5b39bc0cb13c12c87ccd189366e10e7b70ab1d9469fbec0536fc8e68a7f", "source_url": "https://stats.stackexchange.com/questions/676997/asking-for-advice-on-cleaning-gps-data-from-ble-trackers"}], "other_answers": [], "product": "code_qa", "question": "I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.\n\n\n\n\nHere is an example of how the data is collected:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Woh1NewX.png] (https://i.sstatic.net/Woh1NewX.png)\n\n\n\n\nFor finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.\n\n\n\n\nWhat I did to solve the issue:\n\n\n\n\n\nDuplicated timestamps\n\n\n\n\nDuplicated location points\n\n\n\n\nACC > 50 (Accuracy estimator in metres)\n\n\n\n\n\nThis left me with ~3000 rows of data for each cat.\n\n\n\n\nUsing ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:\n\n\n\n\ndata(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"weighted OUF AKDE\"[\"C\"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"OUF AKDE\"[\"C\"]))\n\n\n\n\n\nHere is the resulting home range plots of 1 cat:\n[image: L: Home range from wAKDE, R: Home range from AKDE ; source: https://i.sstatic.net/kXgSIQb8.png] (https://i.sstatic.net/kXgSIQb8.png)\n\n\n\n\nHere is the summary of wAKDE and AKDE respectively:\n[image: L: wAKDE, R: AKDE; source: https://i.sstatic.net/bZFkYz3U.png] (https://i.sstatic.net/bZFkYz3U.png)\n\n\n\n\nHere is the plot points of 1 cat across the campus (~2.5 months of data):\n[image: Plot points generated from R; source: https://i.sstatic.net/I6TIxhWk.png] (https://i.sstatic.net/I6TIxhWk.png)\n\n\n\n\nThe issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.\n\n\n\n\nMy questions:\n\n\n\n\n\nHow do I thin out my data? Other than removing obvious outliers, I tried to filter the data by creating new cluster points (in R I attempted to create a function to cluster points within a certain stationary threshold, and the centroid of this point would be the new point)\n\n\n\n\nHow do I account for inaccuracies, especially because this technology is quite new and the only accuracy estimator I have is ACC which I am unsure of how to calibrate it so that I can account for it in the ctmm package.\n\n\n\n\nWhy is the home range a circle?\n\n\n\n\nShould I be using AKDE to find home range or BBMM (Brownian bridge movement model)? BBMM which is better equipped to deal with auto-correlated and clustered position data than KDE home range estimator commonly used in wildlife studies. Specifically, BBMM allows estimation of probabilistic space-use, while accounting for position error and the uncertainty about paths taken between consecutive positions.\n\n\n\n\n\nApologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)", "record_id": "Scientific-Code-and-Analysis-QA:stats:676997", "selected_answer": {"answer_html": "Welcome to CV.
\nThis will not be an answer to your direct questions, nor will it be a particularly "statistical" answer, but a series of remarks, too long to fit in comments, which I hope can help, and a final remark, which unfortunately may not "help"...
First, wrt “Acc” (Accuracy), I would not put too much credibility on that metric. About the only way the receiver (phone) could make such an assessment would be based on signal strength (the stronger the signal, the closer it ought to be). But having worked with BLE, signal strength can be hampered by many factors: tag battery status, but also line of sight between sender and receiver. If there is no direct line of sight between the 2, signals can be dramatically affected:walls, and type of walls -e.g. concrete vs. sheetrock- glass, metal, body parts and location of the tag and/or receiver on the body (bodies, human or animal, with a high water content are very good absorbers of wireless signals), crowded locations (same reason), dense vegetation (again, water as an absorber), wireless interferences from other 2.4 GHz signals (which, btw, include common microwave ovens), etc. Yes, you can use it to reduce the size of your dataset, but I would not put too much trust between an estimated accuracy of 50m and, e.g. 100m, or 25m.
\nNote that the "typical" range for BLE in consumer products is around 25m to 30m; not sure what your beacon is capable of, but 100m seems challenging, even in (near) ideal conditions.
\nYou could (should?) “calibrate” your beacons; simply use a single beacon, and, e.g., your own phone, and see what kind of range you get (and what “Acc” you get). Do this in “clean” environments, and in challenging environments. This will at least give you a sense of how to interpret this “Acc”.
Wrt to thinning out your data, if you are truly only interested in the range of your cats (and not in other characteristics, such as where they seem to spend most of their time), I would use location as the main tool. Once a cat has been observed more than $k$ times (e.g. 3??) in the same general location (within $\\pm u \\text { m}$ - e.g. 10m, or 20m, or??) then you can eliminate all other measurements from this cat which are within $\\pm u \\text { m}$ (because you now determined that this location is part of the range of that cat, and you do not need further measurements).
\nAnother approach is to overlay your map with a $u \\cdot u \\text { m}$ grid, and consider a particular cell being part of the range of cat $c$ if that cat is seen $k$ times in this cell. Beyond that, just use the center of the grid as a single datapoint. Using a 20m x 20m grid, you would have (roughly) at most 50x80, i.e. 4000 datapoints per cat (if they roamed over the entire map, which, from your data, they do not do).
Last, unfortunately, is a bit of possibly (?) bad news. Your spread of “pings” for the cat you showed us seemed to be somehow “bound” by some topographic limits. This peaked my curiosity, so I used Google map to get a satellite view of your campus. See below:\n
\nThe area of greatest interest (to me at least) was the eastern bound, delimited by College Ave E (CAE). Why would cats not cross this road? Too much traffic? It turns that the area east of CAE appears to be densely wooded, with very few buildings. So is the absence of pings in that area due to the cat not crossing the road, or due to the absence of receivers in that area?
\nThe BLE beacons work if there is a relatively dense presence of phones in that area. But are there that many pedestrians (or cyclist) in that densely wooded area? I certainly do not know, but it would be legitimate concern.
\nSimilarly, to the west is a “border” made by Clementi Rd (CR), which appears much wider (hence more traffic?) than CAE. But to the west is a High School stadium, which again begs the question of the density of receivers...
\nAnd to the north, is again a wider street (Dover Road – DR). But beyond is a secondary school, and its athletic field, which may not be densely covered with Apple phones?
\nTo the south, the border is made by what appears to be a freeway, which would be a “natural” boundary for cats.\nLast, in general, feral cats are most active at dawn and dusk, times where the western high school, and the northern secondary school, would be void of students (and hence potential receivers).
\nThis last issue highlights a weakness of this “beacon” method; it depends on the presence of a dense network of phones, at all times where animals may be active. This may be the case for densely populated areas (downtowns? Or your main campus) and diurnal animals. But it gets challenged in your scenario.
\nOf course, if it is simply for a school project, I would not worry too much about this issue (I would still mention it in my final report), but if it is for a more formal project, I would definitively test this (e.g. by placing a few fixed gateways in the suspect areas).
Welcome to CV.
\nThis will not be an answer to your direct questions, nor will it be a particularly "statistical" answer, but a series of remarks, too long to fit in comments, which I hope can help, and a final remark, which unfortunately may not "help"...
First, wrt “Acc” (Accuracy), I would not put too much credibility on that metric. About the only way the receiver (phone) could make such an assessment would be based on signal strength (the stronger the signal, the closer it ought to be). But having worked with BLE, signal strength can be hampered by many factors: tag battery status, but also line of sight between sender and receiver. If there is no direct line of sight between the 2, signals can be dramatically affected:walls, and type of walls -e.g. concrete vs. sheetrock- glass, metal, body parts and location of the tag and/or receiver on the body (bodies, human or animal, with a high water content are very good absorbers of wireless signals), crowded locations (same reason), dense vegetation (again, water as an absorber), wireless interferences from other 2.4 GHz signals (which, btw, include common microwave ovens), etc. Yes, you can use it to reduce the size of your dataset, but I would not put too much trust between an estimated accuracy of 50m and, e.g. 100m, or 25m.
\nNote that the "typical" range for BLE in consumer products is around 25m to 30m; not sure what your beacon is capable of, but 100m seems challenging, even in (near) ideal conditions.
\nYou could (should?) “calibrate” your beacons; simply use a single beacon, and, e.g., your own phone, and see what kind of range you get (and what “Acc” you get). Do this in “clean” environments, and in challenging environments. This will at least give you a sense of how to interpret this “Acc”.
Wrt to thinning out your data, if you are truly only interested in the range of your cats (and not in other characteristics, such as where they seem to spend most of their time), I would use location as the main tool. Once a cat has been observed more than $k$ times (e.g. 3??) in the same general location (within $\\pm u \\text { m}$ - e.g. 10m, or 20m, or??) then you can eliminate all other measurements from this cat which are within $\\pm u \\text { m}$ (because you now determined that this location is part of the range of that cat, and you do not need further measurements).
\nAnother approach is to overlay your map with a $u \\cdot u \\text { m}$ grid, and consider a particular cell being part of the range of cat $c$ if that cat is seen $k$ times in this cell. Beyond that, just use the center of the grid as a single datapoint. Using a 20m x 20m grid, you would have (roughly) at most 50x80, i.e. 4000 datapoints per cat (if they roamed over the entire map, which, from your data, they do not do).
Last, unfortunately, is a bit of possibly (?) bad news. Your spread of “pings” for the cat you showed us seemed to be somehow “bound” by some topographic limits. This peaked my curiosity, so I used Google map to get a satellite view of your campus. See below:\n
\nThe area of greatest interest (to me at least) was the eastern bound, delimited by College Ave E (CAE). Why would cats not cross this road? Too much traffic? It turns that the area east of CAE appears to be densely wooded, with very few buildings. So is the absence of pings in that area due to the cat not crossing the road, or due to the absence of receivers in that area?
\nThe BLE beacons work if there is a relatively dense presence of phones in that area. But are there that many pedestrians (or cyclist) in that densely wooded area? I certainly do not know, but it would be legitimate concern.
\nSimilarly, to the west is a “border” made by Clementi Rd (CR), which appears much wider (hence more traffic?) than CAE. But to the west is a High School stadium, which again begs the question of the density of receivers...
\nAnd to the north, is again a wider street (Dover Road – DR). But beyond is a secondary school, and its athletic field, which may not be densely covered with Apple phones?
\nTo the south, the border is made by what appears to be a freeway, which would be a “natural” boundary for cats.\nLast, in general, feral cats are most active at dawn and dusk, times where the western high school, and the northern secondary school, would be void of students (and hence potential receivers).
\nThis last issue highlights a weakness of this “beacon” method; it depends on the presence of a dense network of phones, at all times where animals may be active. This may be the case for densely populated areas (downtowns? Or your main campus) and diurnal animals. But it gets challenged in your scenario.
\nOf course, if it is simply for a school project, I would not worry too much about this issue (I would still mention it in my final report), but if it is for a more formal project, I would definitively test this (e.g. by placing a few fixed gateways in the suspect areas).
I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.
\nHere is an example of how the data is collected:
\n\nFor finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.
\nWhat I did to solve the issue:
\nThis left me with ~3000 rows of data for each cat.
\nUsing ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:
\ndata(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression("weighted OUF AKDE"["C"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression("OUF AKDE"["C"]))\n\nHere is the resulting home range plots of 1 cat:\n
Here is the summary of wAKDE and AKDE respectively:\n
Here is the plot points of 1 cat across the campus (~2.5 months of data):\n
The issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.
\nMy questions:
\nApologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)
\n", "question_id": 676997, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its location to Apple's iCloud, which essentially makes up my data.\n\n\n\n\nHere is an example of how the data is collected:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Woh1NewX.png] (https://i.sstatic.net/Woh1NewX.png)\n\n\n\n\nFor finding home range of each cat, I am using R package ctmm to calculate Autocorrelated Kernel Density Estimator (AKDE). Before, I only removed ACCs > 100 which left me with ~14 000 rows of observations for each cat over the duration of 2.5 months, which ctmm was not able to handle. Hence, I wish to find a way to thin out the data (make it temporally less dense, since the smallest time interval I have currently is 1 second) while accounting for accuracy/ error estimates.\n\n\n\n\nWhat I did to solve the issue:\n\n\n\n\n\nDuplicated timestamps\n\n\n\n\nDuplicated location points\n\n\n\n\nACC > 50 (Accuracy estimator in metres)\n\n\n\n\n\nThis left me with ~3000 rows of data for each cat.\n\n\n\n\nUsing ctmm R package to derive home range from weighted AKDE (wAKDE) & AKDE:\n\n\n\n\ndata(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assumed to be 1.\n\n#wAKDE\nplot(putu,UD=wAKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"weighted OUF AKDE\"[\"C\"]))\n\n#AKDE\nplot(putu,UD=AKDE,xlim=EXT$x,ylim=EXT$y)\ntitle(expression(\"OUF AKDE\"[\"C\"]))\n\n\n\n\n\nHere is the resulting home range plots of 1 cat:\n[image: L: Home range from wAKDE, R: Home range from AKDE ; source: https://i.sstatic.net/kXgSIQb8.png] (https://i.sstatic.net/kXgSIQb8.png)\n\n\n\n\nHere is the summary of wAKDE and AKDE respectively:\n[image: L: wAKDE, R: AKDE; source: https://i.sstatic.net/bZFkYz3U.png] (https://i.sstatic.net/bZFkYz3U.png)\n\n\n\n\nHere is the plot points of 1 cat across the campus (~2.5 months of data):\n[image: Plot points generated from R; source: https://i.sstatic.net/I6TIxhWk.png] (https://i.sstatic.net/I6TIxhWk.png)\n\n\n\n\nThe issue here is that the estimate of home range seem to be giving me a circle, when there are clear contours to the data points.\n\n\n\n\nMy questions:\n\n\n\n\n\nHow do I thin out my data? Other than removing obvious outliers, I tried to filter the data by creating new cluster points (in R I attempted to create a function to cluster points within a certain stationary threshold, and the centroid of this point would be the new point)\n\n\n\n\nHow do I account for inaccuracies, especially because this technology is quite new and the only accuracy estimator I have is ACC which I am unsure of how to calibrate it so that I can account for it in the ctmm package.\n\n\n\n\nWhy is the home range a circle?\n\n\n\n\nShould I be using AKDE to find home range or BBMM (Brownian bridge movement model)? BBMM which is better equipped to deal with auto-correlated and clustered position data than KDE home range estimator commonly used in wildlife studies. Specifically, BBMM allows estimation of probabilistic space-use, while accounting for position error and the uncertainty about paths taken between consecutive positions.\n\n\n\n\n\nApologies for the information dump, I am relatively new to movement ecology and R so any advice/ corrections for any of the points mentioned will be greatly appreciated. :)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "yuen kei", "profile_url": "https://stats.stackexchange.com/users/516045/yuen-kei", "user_type": "registered"}, "created_at": "2026-08-29T12:41:14+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "D14E0134-8761-4D18-9603-809C2EE8BF6C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D14E0134-8761-4D18-9603-809C2EE8BF6C/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-30T03:37:51+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "9EC2BF4F-7493-47E5-9507-BE468E30BE43", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/9EC2BF4F-7493-47E5-9507-BE468E30BE43/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/676997/asking-for-advice-on-cleaning-gps-data-from-ble-trackers", "split": "train", "split_group": "e6076ac1bffe41919709726776bef5ec5e60aef3dc627347d256d7ca034cc2d9", "tags": ["r", "distributions", "ecology"], "thread_id": "stats:676997", "title": "Asking for advice on cleaning GPS data from BLE trackers"}} {"accepted_answer": {"answer_html": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.
\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.
\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$
\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$
\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).
\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.
\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.
\nR code for the simulationThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution for suggestions on improving this.
#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = "xy", col = gray(3/4),\n main = "Joint estimates",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = "Red")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = "Black")\n\nhist(log(Sim[1, ]), main = "", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = "", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))\n\n", "answer_id": 677036, "answer_text": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.\n\n\n\n\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/tCnpe77y.png] (https://i.sstatic.net/tCnpe77y.png)\n\n\n\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$\n\n\n\n\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$\n\n\n\n\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).\n\n\n\n\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.\n\n\n\n\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.\n\n\n\n\n\n\n\nR code for the simulation\n\n\n\n\nThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution (https://en.wikipedia.org/wiki/Beta_distribution#Two_unknown_parameters_2) for suggestions on improving this.\n\n\n\n\n#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = \"xy\", col = gray(3/4),\n main = \"Joint estimates\",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = \"Red\")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = \"Black\")\n\nhist(log(Sim[1, ]), main = \"\", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = \"\", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))", "answer_url": "https://stats.stackexchange.com/a/677036", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T15:28:17+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": 677021, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-09-01T15:28:17+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "562F742D-E466-46BD-8A9B-E3CC5920C263", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/562F742D-E466-46BD-8A9B-E3CC5920C263/view-source"}], "score": 8, "updated_at": "2026-09-01T15:28:17+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = \"xy\", col = gray(3/4),\n main = \"Joint estimates\",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = \"Red\")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = \"Black\")\n\nhist(log(Sim[1, ]), main = \"\", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = \"\", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677036, "sha256": "b83ca8136b43e28bbec688e77ef8b88b496efc85ffa2018c2dd15fc9a4ec89cc", "source_url": "https://stats.stackexchange.com/a/677036"}], "other_answers": [], "product": "code_qa", "question": "Suppose $X_1, \\dots, X_n \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha, \\beta)$, and I want to estimate the parameters by maximum likelihood.\n\n\n\n\nI know that:\n$$\\hat\\mu = \\frac{\\hat\\alpha}{\\hat\\alpha + \\hat\\beta}, \\qquad \\hat\\sigma^2 = \\frac{\\hat\\alpha\\hat\\beta}{(\\hat\\alpha+\\hat\\beta)^2(\\hat\\alpha+\\hat\\beta+1)}.$$\n\n\n\n\nIf $\\hat\\alpha$ and $\\hat\\beta$ can only be found numerically, how do we know if $\\hat\\alpha, \\hat\\beta, \\hat\\mu, \\hat\\sigma^2$ are biased or unbiased? (and how large is the bias)", "record_id": "Scientific-Code-and-Analysis-QA:stats:677021", "selected_answer": {"answer_html": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.
\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.
\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$
\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$
\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).
\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.
\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.
\nR code for the simulationThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution for suggestions on improving this.
#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = "xy", col = gray(3/4),\n main = "Joint estimates",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = "Red")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = "Black")\n\nhist(log(Sim[1, ]), main = "", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = "", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))\n\n", "answer_id": 677036, "answer_text": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.\n\n\n\n\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/tCnpe77y.png] (https://i.sstatic.net/tCnpe77y.png)\n\n\n\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$\n\n\n\n\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$\n\n\n\n\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).\n\n\n\n\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.\n\n\n\n\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.\n\n\n\n\n\n\n\nR code for the simulation\n\n\n\n\nThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution (https://en.wikipedia.org/wiki/Beta_distribution#Two_unknown_parameters_2) for suggestions on improving this.\n\n\n\n\n#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = \"xy\", col = gray(3/4),\n main = \"Joint estimates\",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = \"Red\")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = \"Black\")\n\nhist(log(Sim[1, ]), main = \"\", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = \"\", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))", "answer_url": "https://stats.stackexchange.com/a/677036", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T15:28:17+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": 677021, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-09-01T15:28:17+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "562F742D-E466-46BD-8A9B-E3CC5920C263", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/562F742D-E466-46BD-8A9B-E3CC5920C263/view-source"}], "score": 8, "updated_at": "2026-09-01T15:28:17+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677036, "answers": [{"answer_html": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.
\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.
\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$
\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$
\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).
\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.
\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.
\nR code for the simulationThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution for suggestions on improving this.
#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = "xy", col = gray(3/4),\n main = "Joint estimates",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = "Red")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = "Black")\n\nhist(log(Sim[1, ]), main = "", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = "", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = "Red", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))\n\n", "answer_id": 677036, "answer_text": "Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the estimates (using MLE or any other method you might choose to study). The distribution of these simulated estimates, relative to the chosen parameter values, shows you just about everything you might want to know about how your estimator behaves for these parameter values. To understand the estimator generally, repeat for a spectrum of parameter values.\n\n\n\n\nAs an example, here is a summary of one thousand Maximum Likelihood estimates made for samples of size $30$ from a Beta$(2, 3)$ distribution.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/tCnpe77y.png] (https://i.sstatic.net/tCnpe77y.png)\n\n\n\n\nThe leftmost panel plots all one thousand $(\\hat\\alpha,\\hat\\beta)$ pairs on log-log axes (because the distributions of the estimates are positively skewed). The red dot indicates the true parameter value $(\\alpha,\\beta)$ while the block triangle indicates the arithmetic means of the estimates: those will approximate the expectation $E[(\\hat\\alpha,\\hat\\beta)].$\n\n\n\n\nThe displacement of the black triangle from the red circle depicts the bias in $(\\hat\\alpha,\\hat\\beta).$\n\n\n\n\nThe histograms display the univariate distributions of the estimates and, likewise, plot the true values in red and the approximate expectations in black (dotted lines).\n\n\n\n\nThis simulation was large enough to establish there is a bias in both estimates: the ratios $E[\\hat\\alpha]/\\alpha$ and $E[\\hat\\beta]/\\beta$ are both approximately $1.10.$ That is, the estimates tend to be ten percent too large. This positive bias persists for all the combinations of $(\\alpha,\\beta)$ I have examined, covering a range from $1/2$ to $100.$ The amount of bias does vary with the parameters. It varies with the sample size, growing smaller as the sample size increases. The relative biases tend to be about equal, regardless.\n\n\n\n\nThese biases nearly cancel in the ratios used to compute $\\hat\\mu$ and $\\hat\\sigma^2.$ They are important only for small sample sizes and small values of the parameters, where the biases in $\\hat\\alpha$ and $\\hat\\beta$ can be enormous. But we would expect that when applying Maximum Likelihood to small samples, anyway.\n\n\n\n\n\n\n\nR code for the simulation\n\n\n\n\nThe implementation of the ML estimator MLE.beta is quick and dirty; it might perform poorly or fail when one or both parameters are less than $1.$ See the Wikipedia article on the Beta distribution (https://en.wikipedia.org/wiki/Beta_distribution#Two_unknown_parameters_2) for suggestions on improving this.\n\n\n\n\n#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(alpha, beta) - (alpha - 1) * lgm - (beta - 1) * lgm1\n}\n#\n# MLE for the Beta distribution.\n#\nMLE.beta <- function(x) {\n obj <- nlm(Lambda, log(theta), lgm = mean(log(x)), lgm1 = mean(log(1 - x)))\n exp(obj$estimate)\n}\n#------------------------------------------------------------------------------#\n#\n# Estimate the bias through simulation.\n#\ntheta <- c(alpha = 2, beta = 3)\nn <- 30\nset.seed(17)\nSim <- replicate(1e4, {\n x <- rbeta(n, theta[1], theta[2])\n MLE.beta(x)\n})\n#\n# Summarize the simulation.\n#\n# Rho <- cor(t(Sim))\nmeans <- rowMeans(Sim)\ndelta <- means - theta\nsigma <- apply(Sim, 1, sd) / sqrt(ncol(Sim)); names(sigma) <- names(delta)\nZ <- delta / sigma\n#\n# Compute more estimates.\n#\nf <- function(a, b) {\n mu <- a / (a + b)\n sigma2 <- a * b / ((a + b)^2 * (a + b + 1))\n rowMeans(rbind(mu, sigma2))\n}\nmusigma.hat <- f(Sim[1, ], Sim[2, ])\nmusigma <- f(theta[1], theta[2])\n#\n# Display the estimates.\n#\nround(rbind(`True value` = theta,\n `Relative bias` = (delta + theta) / theta,\n `Relative SE` = sigma / theta,\n `Z score` = Z,\n `mu and sigma^2` = musigma,\n `hat(mu) and hat(sigma^2)` = musigma.hat), 4)\n\n\npar(mfrow = c(1, 3))\nplot(t(Sim), asp = 1, log = \"xy\", col = gray(3/4),\n main = \"Joint estimates\",\n xlab = expression(hat(alpha)), ylab = expression(hat(beta)))\npoints(theta[1], theta[2], pch = 21, cex = 1.5, bg = \"Red\")\npoints(means[1], means[2], pch = 24, cex = 1.5, bg = \"Black\")\n\nhist(log(Sim[1, ]), main = \"\", xlab = expression(log(hat(alpha))))\nabline(v = log(theta[1]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[1, ])), lwd = 2, lty = 3)\nhist(log(Sim[2, ]), main = \"\", xlab = expression(log(hat(beta))))\nabline(v = log(theta[2]), col = \"Red\", lwd = 2)\nabline(v = log(mean(Sim[2, ])), lwd = 2, lty = 3)\npar(mfrow = c(1, 1))", "answer_url": "https://stats.stackexchange.com/a/677036", "author": "whuber", "author_url": "https://stats.stackexchange.com/users/919/whuber", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T15:28:17+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": 677021, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "whuber", "profile_url": "https://stats.stackexchange.com/users/919/whuber", "user_type": "moderator"}, "created_at": "2026-09-01T15:28:17+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "562F742D-E466-46BD-8A9B-E3CC5920C263", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/562F742D-E466-46BD-8A9B-E3CC5920C263/view-source"}], "score": 8, "updated_at": "2026-09-01T15:28:17+00:00"}], "domain": "statistics", "external_links": ["https://en.wikipedia.org/wiki/Beta_distribution#Two_unknown_parameters_2", "https://i.sstatic.net/tCnpe77y.png"], "medical_sensitive": false, "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": "adamkostanov", "question_author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "question_author_user_type": "registered", "question_created_at": "2026-08-31T15:30:58+00:00", "question_html": "Suppose $X_1, \\dots, X_n \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha, \\beta)$, and I want to estimate the parameters by maximum likelihood.
\nI know that:\n$$\\hat\\mu = \\frac{\\hat\\alpha}{\\hat\\alpha + \\hat\\beta}, \\qquad \\hat\\sigma^2 = \\frac{\\hat\\alpha\\hat\\beta}{(\\hat\\alpha+\\hat\\beta)^2(\\hat\\alpha+\\hat\\beta+1)}.$$
\nIf $\\hat\\alpha$ and $\\hat\\beta$ can only be found numerically, how do we know if $\\hat\\alpha, \\hat\\beta, \\hat\\mu, \\hat\\sigma^2$ are biased or unbiased? (and how large is the bias)
\n", "question_id": 677021, "question_license": "CC BY-SA 4.0", "question_score": 5, "question_text": "Suppose $X_1, \\dots, X_n \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha, \\beta)$, and I want to estimate the parameters by maximum likelihood.\n\n\n\n\nI know that:\n$$\\hat\\mu = \\frac{\\hat\\alpha}{\\hat\\alpha + \\hat\\beta}, \\qquad \\hat\\sigma^2 = \\frac{\\hat\\alpha\\hat\\beta}{(\\hat\\alpha+\\hat\\beta)^2(\\hat\\alpha+\\hat\\beta+1)}.$$\n\n\n\n\nIf $\\hat\\alpha$ and $\\hat\\beta$ can only be found numerically, how do we know if $\\hat\\alpha, \\hat\\beta, \\hat\\mu, \\hat\\sigma^2$ are biased or unbiased? (and how large is the bias)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-08-31T15:30:58+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "9E0825ED-D3A3-4B9D-A473-EAAC6F1F776C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9E0825ED-D3A3-4B9D-A473-EAAC6F1F776C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-01T15:34:43+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "E40FFCDD-0DA9-4AD3-8F2B-156FC54FF70B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E40FFCDD-0DA9-4AD3-8F2B-156FC54FF70B/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-01T15:40:03+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "B40F8A52-F9E0-4EFC-B9EE-1256CB7E1E1B", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/B40F8A52-F9E0-4EFC-B9EE-1256CB7E1E1B/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677021/if-an-mle-can-only-be-solved-numerically-how-do-we-know-if-it-is-biased-or-unbi", "split": "train", "split_group": "e281e2df35e214047c71a76e665e03cfecfa605e1301c0b2625e62afa44ac194", "tags": ["maximum-likelihood"], "thread_id": "stats:677021", "title": "If an MLE can only be solved numerically, how do we know if it is biased or unbiased?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "glm(Y ~ X * Z + C1 + C2, family = binomial)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677023, "sha256": "c4f9bf8f0235bd91571ecb82f9237cf525d1071c10a1c4cd61809e1b52959402", "source_url": "https://stats.stackexchange.com/questions/677023/does-an-interaction-term-affect-the-interpretation-of-the-other-covariates"}], "other_answers": [{"answer_html": "The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.
\nI don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, and C2 and show it that way.
\n", "answer_id": 677028, "answer_text": "The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.\n\n\n\n\nI don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, and C2 and show it that way.", "answer_url": "https://stats.stackexchange.com/a/677028", "author": "Peter Flom", "author_url": "https://stats.stackexchange.com/users/686/peter-flom", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-31T18:43:35+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": 677023, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Peter Flom", "profile_url": "https://stats.stackexchange.com/users/686/peter-flom", "user_type": "registered"}, "created_at": "2026-08-31T18:43:35+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "02A19662-7877-4049-B5F5-406036C72096", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/02A19662-7877-4049-B5F5-406036C72096/view-source"}], "score": 0, "updated_at": "2026-08-31T18:43:35+00:00"}], "product": "code_qa", "question": "Logistic regression:\n\n\n\n\nglm(Y ~ X * Z + C1 + C2, family = binomial)\n\n\n\n\n\nI know β_X and β_Z are conditional (effect when the other is 0) and shouldn't be read as main effects.\n\n\n\n\nDoes this also apply to C1, which isn't in the interaction? Or is exp(β_C1) still the ordinary adjusted OR, with the p value testing the ordinary null?\n\n\n\n\nAny textbook or paper that states this explicitly?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677023", "selected_answer": {"answer_html": "The original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example
\nIn Fox's Chapter 7, he discusses the interpretation of coefficients in the presence of interactions, quoting Nelder's principle of marginality as well (which is a nice bonus). Even though the quote is in the context of his discussion of OLS with dummy variables, Nelder's principle is important across generalized linear modeling. Hosmer and Lemeshow (p. 64 - 77) give much more detail on your question. I'll try to briefly summarize using one of their examples.
\nLet's consider a logistic model with a indicator "exposure" variable for sex ($X_1 = 1 \\text{, if Female}$), a continuous covariate $Z = \\text{Age}$, the interaction variable $X_{1}Z$ and a separate covariate $X_2$ (say the patient's BMI). The outcome is $Y = 1$ if a patient develops coronary heart disease (CHD), and $Y = 0$ otherwise.
\nOn the log-odds scale, if we assume the $\\text{Age} \\sim \\text{CHD}$ relationship is linear in both sexes, and we introduce an interaction along with additional adjustment for BMI, we have:
\n$$\n\\text{logit}(Y_i) = \\alpha + \\beta_1 X_{i1} + \\gamma Z_i + \\delta (X_1Z)_i + \\beta_2 X_{i2}\n$$
\nNow write down the model separately for the two sexes substituting $0$ and $1$ accordingly for $X_1$ in each case and moving things around algebraically:
\n$$\n\\begin{align}\n\\text{Female: } & \\text{logit}Y_i = (\\alpha + \\beta_1) + (\\gamma + \\delta)Z_i + \\beta_2 X_{i2}\\\\\n\\text{Male: } & \\text{logit}Y_i = \\alpha + \\gamma Z_i + \\beta_2 X_{i2}\n\\end{align}\n$$
\nThough it is easier to see if we had actual estimates for $\\alpha$, $\\beta_1$, $\\beta_2$, and $\\gamma$, we have a different intercept and $\\text{logit}(Y) \\sim \\text{Age}$ slope between Males and Females, but $\\beta_2$, the slope relating BMI to $\\text{logit}(Y)$ stays the same in both cases.
\nSo on the logit scale, you can still interpret the marginal effect of educational attainment in the same way, though of course it is conditional on the rest of the terms in the model. That is, the “main effect” of age remains interpretable, unlike the main effects for treatment and whatever lab value you're interested in.
\nThis changes a bit when we exponentiate, as we must estimate odds-ratios involving the interaction terms at specific values of each of the interacting variables. However, since the additional covariate (BMI in this case) is not involved in that messiness, we can still exponentiate and do well with that odds-ratio, but still keeping in mind that we've got an interaction in our model. In many cases, however, we may be uninterested in the BMI odds ratio (i.e., the covariate), and only include it to better reduce confounding of the other effects (perhaps the exposure). This gets us into advanced territory, so I'll leave it here.
\n", "answer_id": 677039, "answer_text": "Edit:\n\n\n\n\nThe original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example\n\n\n\n\n\n\n\n\nfrom Whuber: F. Mosteller and J. Tukey, Data Analysis and Regression (https://archive.org/details/dataanalysisregr0000most)\n\n\n\n\nfrom M--: P. Roback and J. Legler: Beyond Multiple Linear Regression (https://bookdown.org/roback/bookdown-BeyondMLR/)\n\n\n\n\nMy picks:\n\n\n\n\n\n\nOrdinary regression, and general issues with GLMS: Weisberg: Applied Linear Regression (https://www.wiley.com/en-br/shop/general-introductory-statistics/applied-linear-regression-4th-edition-p-9781118386088); Fox: Applied Regression Analysis and Generalized Linear Models (https://collegepublishing.sagepub.com/products/applied-regression-analysis-and-generalized-linear-models-3-237254)\n\n\n\n\nSpecific to logistic regression: Hosmer and Lemeshow: Applied Logistic Regression (https://onlinelibrary.wiley.com/doi/book/10.1002/9781118548387)\n\n\n\n\n\nIn Fox's Chapter 7, he discusses the interpretation of coefficients in the presence of interactions, quoting Nelder's principle of marginality as well (which is a nice bonus). Even though the quote is in the context of his discussion of OLS with dummy variables, Nelder's principle is important across generalized linear modeling. Hosmer and Lemeshow (p. 64 - 77) give much more detail on your question. I'll try to briefly summarize using one of their examples.\n\n\n\n\nLet's consider a logistic model with a indicator \"exposure\" variable for sex ($X_1 = 1 \\text{, if Female}$), a continuous covariate $Z = \\text{Age}$, the interaction variable $X_{1}Z$ and a separate covariate $X_2$ (say the patient's BMI). The outcome is $Y = 1$ if a patient develops coronary heart disease (CHD), and $Y = 0$ otherwise.\n\n\n\n\nOn the log-odds scale, if we assume the $\\text{Age} \\sim \\text{CHD}$ relationship is linear in both sexes, and we introduce an interaction along with additional adjustment for BMI, we have:\n\n\n\n\n$$\n\\text{logit}(Y_i) = \\alpha + \\beta_1 X_{i1} + \\gamma Z_i + \\delta (X_1Z)_i + \\beta_2 X_{i2}\n$$\n\n\n\n\nNow write down the model separately for the two sexes substituting $0$ and $1$ accordingly for $X_1$ in each case and moving things around algebraically:\n\n\n\n\n$$\n\\begin{align}\n\\text{Female: } & \\text{logit}Y_i = (\\alpha + \\beta_1) + (\\gamma + \\delta)Z_i + \\beta_2 X_{i2}\\\\\n\\text{Male: } & \\text{logit}Y_i = \\alpha + \\gamma Z_i + \\beta_2 X_{i2}\n\\end{align}\n$$\n\n\n\n\nThough it is easier to see if we had actual estimates for $\\alpha$, $\\beta_1$, $\\beta_2$, and $\\gamma$, we have a different intercept and $\\text{logit}(Y) \\sim \\text{Age}$ slope between Males and Females, but $\\beta_2$, the slope relating BMI to $\\text{logit}(Y)$ stays the same in both cases.\n\n\n\n\nSo on the logit scale, you can still interpret the marginal effect of educational attainment in the same way, though of course it is conditional on the rest of the terms in the model. That is, the “main effect” of age remains interpretable, unlike the main effects for treatment and whatever lab value you're interested in.\n\n\n\n\nThis changes a bit when we exponentiate, as we must estimate odds-ratios involving the interaction terms at specific values of each of the interacting variables. However, since the additional covariate (BMI in this case) is not involved in that messiness, we can still exponentiate and do well with that odds-ratio, but still keeping in mind that we've got an interaction in our model. In many cases, however, we may be uninterested in the BMI odds ratio (i.e., the covariate), and only include it to better reduce confounding of the other effects (perhaps the exposure). This gets us into advanced territory, so I'll leave it here.", "answer_url": "https://stats.stackexchange.com/a/677039", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T18:54:15+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": 677023, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-01T18:54:15+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "1C96DBED-01C4-408D-8ADC-73D384ED5F3D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1C96DBED-01C4-408D-8ADC-73D384ED5F3D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-02T01:11:13+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "EB91F46E-AE98-4B27-B146-70EE8551482D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EB91F46E-AE98-4B27-B146-70EE8551482D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "mastropi", "profile_url": "https://stats.stackexchange.com/users/217355/mastropi", "user_type": "registered"}, "created_at": "2026-09-02T11:36:08+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "EB25A932-6CB9-4775-9305-5FA8CA11BEE5", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EB25A932-6CB9-4775-9305-5FA8CA11BEE5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-02T19:56:28+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "0C25F4DB-255E-4A29-8217-4F07665C4131", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/0C25F4DB-255E-4A29-8217-4F07665C4131/view-source"}], "score": 5, "updated_at": "2026-09-02T19:56:28+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.
\nI don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, and C2 and show it that way.
\n", "answer_id": 677028, "answer_text": "The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.\n\n\n\n\nI don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, and C2 and show it that way.", "answer_url": "https://stats.stackexchange.com/a/677028", "author": "Peter Flom", "author_url": "https://stats.stackexchange.com/users/686/peter-flom", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-08-31T18:43:35+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": 677023, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Peter Flom", "profile_url": "https://stats.stackexchange.com/users/686/peter-flom", "user_type": "registered"}, "created_at": "2026-08-31T18:43:35+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "02A19662-7877-4049-B5F5-406036C72096", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/02A19662-7877-4049-B5F5-406036C72096/view-source"}], "score": 0, "updated_at": "2026-08-31T18:43:35+00:00"}, {"answer_html": "The original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example
\nIn Fox's Chapter 7, he discusses the interpretation of coefficients in the presence of interactions, quoting Nelder's principle of marginality as well (which is a nice bonus). Even though the quote is in the context of his discussion of OLS with dummy variables, Nelder's principle is important across generalized linear modeling. Hosmer and Lemeshow (p. 64 - 77) give much more detail on your question. I'll try to briefly summarize using one of their examples.
\nLet's consider a logistic model with a indicator "exposure" variable for sex ($X_1 = 1 \\text{, if Female}$), a continuous covariate $Z = \\text{Age}$, the interaction variable $X_{1}Z$ and a separate covariate $X_2$ (say the patient's BMI). The outcome is $Y = 1$ if a patient develops coronary heart disease (CHD), and $Y = 0$ otherwise.
\nOn the log-odds scale, if we assume the $\\text{Age} \\sim \\text{CHD}$ relationship is linear in both sexes, and we introduce an interaction along with additional adjustment for BMI, we have:
\n$$\n\\text{logit}(Y_i) = \\alpha + \\beta_1 X_{i1} + \\gamma Z_i + \\delta (X_1Z)_i + \\beta_2 X_{i2}\n$$
\nNow write down the model separately for the two sexes substituting $0$ and $1$ accordingly for $X_1$ in each case and moving things around algebraically:
\n$$\n\\begin{align}\n\\text{Female: } & \\text{logit}Y_i = (\\alpha + \\beta_1) + (\\gamma + \\delta)Z_i + \\beta_2 X_{i2}\\\\\n\\text{Male: } & \\text{logit}Y_i = \\alpha + \\gamma Z_i + \\beta_2 X_{i2}\n\\end{align}\n$$
\nThough it is easier to see if we had actual estimates for $\\alpha$, $\\beta_1$, $\\beta_2$, and $\\gamma$, we have a different intercept and $\\text{logit}(Y) \\sim \\text{Age}$ slope between Males and Females, but $\\beta_2$, the slope relating BMI to $\\text{logit}(Y)$ stays the same in both cases.
\nSo on the logit scale, you can still interpret the marginal effect of educational attainment in the same way, though of course it is conditional on the rest of the terms in the model. That is, the “main effect” of age remains interpretable, unlike the main effects for treatment and whatever lab value you're interested in.
\nThis changes a bit when we exponentiate, as we must estimate odds-ratios involving the interaction terms at specific values of each of the interacting variables. However, since the additional covariate (BMI in this case) is not involved in that messiness, we can still exponentiate and do well with that odds-ratio, but still keeping in mind that we've got an interaction in our model. In many cases, however, we may be uninterested in the BMI odds ratio (i.e., the covariate), and only include it to better reduce confounding of the other effects (perhaps the exposure). This gets us into advanced territory, so I'll leave it here.
\n", "answer_id": 677039, "answer_text": "Edit:\n\n\n\n\nThe original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example\n\n\n\n\n\n\n\n\nfrom Whuber: F. Mosteller and J. Tukey, Data Analysis and Regression (https://archive.org/details/dataanalysisregr0000most)\n\n\n\n\nfrom M--: P. Roback and J. Legler: Beyond Multiple Linear Regression (https://bookdown.org/roback/bookdown-BeyondMLR/)\n\n\n\n\nMy picks:\n\n\n\n\n\n\nOrdinary regression, and general issues with GLMS: Weisberg: Applied Linear Regression (https://www.wiley.com/en-br/shop/general-introductory-statistics/applied-linear-regression-4th-edition-p-9781118386088); Fox: Applied Regression Analysis and Generalized Linear Models (https://collegepublishing.sagepub.com/products/applied-regression-analysis-and-generalized-linear-models-3-237254)\n\n\n\n\nSpecific to logistic regression: Hosmer and Lemeshow: Applied Logistic Regression (https://onlinelibrary.wiley.com/doi/book/10.1002/9781118548387)\n\n\n\n\n\nIn Fox's Chapter 7, he discusses the interpretation of coefficients in the presence of interactions, quoting Nelder's principle of marginality as well (which is a nice bonus). Even though the quote is in the context of his discussion of OLS with dummy variables, Nelder's principle is important across generalized linear modeling. Hosmer and Lemeshow (p. 64 - 77) give much more detail on your question. I'll try to briefly summarize using one of their examples.\n\n\n\n\nLet's consider a logistic model with a indicator \"exposure\" variable for sex ($X_1 = 1 \\text{, if Female}$), a continuous covariate $Z = \\text{Age}$, the interaction variable $X_{1}Z$ and a separate covariate $X_2$ (say the patient's BMI). The outcome is $Y = 1$ if a patient develops coronary heart disease (CHD), and $Y = 0$ otherwise.\n\n\n\n\nOn the log-odds scale, if we assume the $\\text{Age} \\sim \\text{CHD}$ relationship is linear in both sexes, and we introduce an interaction along with additional adjustment for BMI, we have:\n\n\n\n\n$$\n\\text{logit}(Y_i) = \\alpha + \\beta_1 X_{i1} + \\gamma Z_i + \\delta (X_1Z)_i + \\beta_2 X_{i2}\n$$\n\n\n\n\nNow write down the model separately for the two sexes substituting $0$ and $1$ accordingly for $X_1$ in each case and moving things around algebraically:\n\n\n\n\n$$\n\\begin{align}\n\\text{Female: } & \\text{logit}Y_i = (\\alpha + \\beta_1) + (\\gamma + \\delta)Z_i + \\beta_2 X_{i2}\\\\\n\\text{Male: } & \\text{logit}Y_i = \\alpha + \\gamma Z_i + \\beta_2 X_{i2}\n\\end{align}\n$$\n\n\n\n\nThough it is easier to see if we had actual estimates for $\\alpha$, $\\beta_1$, $\\beta_2$, and $\\gamma$, we have a different intercept and $\\text{logit}(Y) \\sim \\text{Age}$ slope between Males and Females, but $\\beta_2$, the slope relating BMI to $\\text{logit}(Y)$ stays the same in both cases.\n\n\n\n\nSo on the logit scale, you can still interpret the marginal effect of educational attainment in the same way, though of course it is conditional on the rest of the terms in the model. That is, the “main effect” of age remains interpretable, unlike the main effects for treatment and whatever lab value you're interested in.\n\n\n\n\nThis changes a bit when we exponentiate, as we must estimate odds-ratios involving the interaction terms at specific values of each of the interacting variables. However, since the additional covariate (BMI in this case) is not involved in that messiness, we can still exponentiate and do well with that odds-ratio, but still keeping in mind that we've got an interaction in our model. In many cases, however, we may be uninterested in the BMI odds ratio (i.e., the covariate), and only include it to better reduce confounding of the other effects (perhaps the exposure). This gets us into advanced territory, so I'll leave it here.", "answer_url": "https://stats.stackexchange.com/a/677039", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-01T18:54:15+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": 677023, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-01T18:54:15+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "1C96DBED-01C4-408D-8ADC-73D384ED5F3D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1C96DBED-01C4-408D-8ADC-73D384ED5F3D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-02T01:11:13+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "EB91F46E-AE98-4B27-B146-70EE8551482D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EB91F46E-AE98-4B27-B146-70EE8551482D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "mastropi", "profile_url": "https://stats.stackexchange.com/users/217355/mastropi", "user_type": "registered"}, "created_at": "2026-09-02T11:36:08+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "EB25A932-6CB9-4775-9305-5FA8CA11BEE5", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EB25A932-6CB9-4775-9305-5FA8CA11BEE5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-02T19:56:28+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "0C25F4DB-255E-4A29-8217-4F07665C4131", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/0C25F4DB-255E-4A29-8217-4F07665C4131/view-source"}], "score": 5, "updated_at": "2026-09-02T19:56:28+00:00"}], "domain": "statistics", "external_links": ["https://archive.org/details/dataanalysisregr0000most", "https://bookdown.org/roback/bookdown-BeyondMLR/", "https://collegepublishing.sagepub.com/products/applied-regression-analysis-and-generalized-linear-models-3-237254", "https://onlinelibrary.wiley.com/doi/book/10.1002/9781118548387", "https://www.wiley.com/en-br/shop/general-introductory-statistics/applied-linear-regression-4th-edition-p-9781118386088"], "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": "Konstantinos Gkirgkiris", "question_author_url": "https://stats.stackexchange.com/users/466987/konstantinos-gkirgkiris", "question_author_user_type": "registered", "question_created_at": "2026-08-31T16:28:24+00:00", "question_html": "Logistic regression:
\nglm(Y ~ X * Z + C1 + C2, family = binomial)\n\nI know β_X and β_Z are conditional (effect when the other is 0) and shouldn't be read as main effects.
\nDoes this also apply to C1, which isn't in the interaction? Or is exp(β_C1) still the ordinary adjusted OR, with the p value testing the ordinary null?
\nAny textbook or paper that states this explicitly?
\n", "question_id": 677023, "question_license": "CC BY-SA 4.0", "question_score": 6, "question_text": "Logistic regression:\n\n\n\n\nglm(Y ~ X * Z + C1 + C2, family = binomial)\n\n\n\n\n\nI know β_X and β_Z are conditional (effect when the other is 0) and shouldn't be read as main effects.\n\n\n\n\nDoes this also apply to C1, which isn't in the interaction? Or is exp(β_C1) still the ordinary adjusted OR, with the p value testing the ordinary null?\n\n\n\n\nAny textbook or paper that states this explicitly?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Konstantinos Gkirgkiris", "profile_url": "https://stats.stackexchange.com/users/466987/konstantinos-gkirgkiris", "user_type": "registered"}, "created_at": "2026-08-31T16:28:24+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "625D283B-6E8B-49CC-9D39-A419938D290E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/625D283B-6E8B-49CC-9D39-A419938D290E/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-01T00:39:35+00:00", "raw_file": "raw/codex_api_v1/84bb317e707465a80f008019404ef1f770e152d74ef692d3b81c48903ec855cc_1790825232001984700_0.json", "raw_sha256": "75778d86d5325e15f4b491a748dc70ae6ac6ee98840d584e01ed28416cb71fbe", "revision_guid": "7B7DEF62-2D77-4CB5-B284-7203069E17E3", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/7B7DEF62-2D77-4CB5-B284-7203069E17E3/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677023/does-an-interaction-term-affect-the-interpretation-of-the-other-covariates", "split": "train", "split_group": "0a1bcd73d1b98426209a0c28354537686e3002366acc568482c8aa33acc3129f", "tags": ["regression", "r", "interaction"], "thread_id": "stats:677023", "title": "Does an interaction term affect the interpretation of the other covariates?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "library(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,\"gap\"],res$Tab[,\"SE.sim\"], method=\"Tibs2001SEmax\")\n}\ntable(gs)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677058, "sha256": "212e2ceb3c850f513b3e1edb810ceb6144894589560f4942090495af1165b2a0", "source_url": "https://stats.stackexchange.com/questions/677058/instability-of-gap-statistics"}], "other_answers": [], "product": "code_qa", "question": "While trying the gap statistics for K-Means to determine the number of clusters in the Iris dataset, I have noticed that the results are random. I have tried the following:\n\n\n\n\nlibrary(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,\"gap\"],res$Tab[,\"SE.sim\"], method=\"Tibs2001SEmax\")\n}\ntable(gs)\n\n\n\n\n\nNote that I have increased the number of initial random configurations (nstart) in kmeans() to 50 in order to remove the randomness from the clustering and I have set d.power=2 as recommended in the documentation of clusGap(). I turns out that the results are quite random and that the true number of clusters is never found:\n\n\n\n\ngs\n 4 5 \n10 10\n\n\n\n\n\nIs this a well-known behavior of the gap statistics? What can be recommended instead that has a less random behavior?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677058", "selected_answer": {"answer_html": "The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.
\nOther potential issues: Note that kmeans implicitly looks for clusters that are spherical and have the same within-cluster variation. This is not the case for the true groups in the Iris dataset. I'd indeed think that if you want to cluster this dataset into clusters according to the implicit kmeans assumptions, you'll do better with 4 or 5 clusters than with 3 or 2. It may go ever higher up when raising K.max. This explains why the "true" number of clusters is not found, but it doesn't explain the instability. However, the gap decision between 4 and 5 may be very ambiguous so that small changes in the random B datasets generated by the "parametric bootstrap" that gap uses may easily change the decision between 4 and 5. You could check this looking at the detailed output of several runs, checking how tight the decision between 4 and 5 actually is according to the "Tib2001SEmax" criterion.
\nAlso the function maxSE has implemented 5 different methods for deciding the number of clusters from the clusGap output. "Tib2001SEmax" is the one proposed in the original paper. The reason why there are four criteria offered on top of it is probably that a number of people (myself included) have found that "Tib2001SEmax" has issues in certain situations. The possibility of instability may be there for all five criteria, but personally I prefer "globalSEmax" and SE.factor=2, the latter at least when being worried more about overfitting than about putting together clusters that are not quite as homogeneous as you'd get when sticking more rigorously to "spherical and same within-cluster variation".
\nAt the end of the day kmeans is just not that good a clustering method for the Iris data when aiming at recovering the given groups. A Gaussian mixture with more flexible within-cluster covariance structure will do better.
\n", "answer_id": 677059, "answer_text": "The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.\n\n\n\n\nOther potential issues: Note that kmeans implicitly looks for clusters that are spherical and have the same within-cluster variation. This is not the case for the true groups in the Iris dataset. I'd indeed think that if you want to cluster this dataset into clusters according to the implicit kmeans assumptions, you'll do better with 4 or 5 clusters than with 3 or 2. It may go ever higher up when raising K.max. This explains why the \"true\" number of clusters is not found, but it doesn't explain the instability. However, the gap decision between 4 and 5 may be very ambiguous so that small changes in the random B datasets generated by the \"parametric bootstrap\" that gap uses may easily change the decision between 4 and 5. You could check this looking at the detailed output of several runs, checking how tight the decision between 4 and 5 actually is according to the \"Tib2001SEmax\" criterion.\n\n\n\n\nAlso the function maxSE has implemented 5 different methods for deciding the number of clusters from the clusGap output. \"Tib2001SEmax\" is the one proposed in the original paper. The reason why there are four criteria offered on top of it is probably that a number of people (myself included) have found that \"Tib2001SEmax\" has issues in certain situations. The possibility of instability may be there for all five criteria, but personally I prefer \"globalSEmax\" and SE.factor=2, the latter at least when being worried more about overfitting than about putting together clusters that are not quite as homogeneous as you'd get when sticking more rigorously to \"spherical and same within-cluster variation\".\n\n\n\n\nAt the end of the day kmeans is just not that good a clustering method for the Iris data when aiming at recovering the given groups. A Gaussian mixture with more flexible within-cluster covariance structure will do better.", "answer_url": "https://stats.stackexchange.com/a/677059", "author": "Christian Hennig", "author_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-03T12:08:52+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": 677058, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-09-03T12:08:52+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "14E907BD-0137-4FA2-93E2-A5C3763E1F24", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/14E907BD-0137-4FA2-93E2-A5C3763E1F24/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-09-03T12:19:59+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "892FF292-2C1A-4474-9F3F-50E0D978AB75", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/892FF292-2C1A-4474-9F3F-50E0D978AB75/view-source"}], "score": 5, "updated_at": "2026-09-03T12:19:59+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.
\nOther potential issues: Note that kmeans implicitly looks for clusters that are spherical and have the same within-cluster variation. This is not the case for the true groups in the Iris dataset. I'd indeed think that if you want to cluster this dataset into clusters according to the implicit kmeans assumptions, you'll do better with 4 or 5 clusters than with 3 or 2. It may go ever higher up when raising K.max. This explains why the "true" number of clusters is not found, but it doesn't explain the instability. However, the gap decision between 4 and 5 may be very ambiguous so that small changes in the random B datasets generated by the "parametric bootstrap" that gap uses may easily change the decision between 4 and 5. You could check this looking at the detailed output of several runs, checking how tight the decision between 4 and 5 actually is according to the "Tib2001SEmax" criterion.
\nAlso the function maxSE has implemented 5 different methods for deciding the number of clusters from the clusGap output. "Tib2001SEmax" is the one proposed in the original paper. The reason why there are four criteria offered on top of it is probably that a number of people (myself included) have found that "Tib2001SEmax" has issues in certain situations. The possibility of instability may be there for all five criteria, but personally I prefer "globalSEmax" and SE.factor=2, the latter at least when being worried more about overfitting than about putting together clusters that are not quite as homogeneous as you'd get when sticking more rigorously to "spherical and same within-cluster variation".
\nAt the end of the day kmeans is just not that good a clustering method for the Iris data when aiming at recovering the given groups. A Gaussian mixture with more flexible within-cluster covariance structure will do better.
\n", "answer_id": 677059, "answer_text": "The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.\n\n\n\n\nOther potential issues: Note that kmeans implicitly looks for clusters that are spherical and have the same within-cluster variation. This is not the case for the true groups in the Iris dataset. I'd indeed think that if you want to cluster this dataset into clusters according to the implicit kmeans assumptions, you'll do better with 4 or 5 clusters than with 3 or 2. It may go ever higher up when raising K.max. This explains why the \"true\" number of clusters is not found, but it doesn't explain the instability. However, the gap decision between 4 and 5 may be very ambiguous so that small changes in the random B datasets generated by the \"parametric bootstrap\" that gap uses may easily change the decision between 4 and 5. You could check this looking at the detailed output of several runs, checking how tight the decision between 4 and 5 actually is according to the \"Tib2001SEmax\" criterion.\n\n\n\n\nAlso the function maxSE has implemented 5 different methods for deciding the number of clusters from the clusGap output. \"Tib2001SEmax\" is the one proposed in the original paper. The reason why there are four criteria offered on top of it is probably that a number of people (myself included) have found that \"Tib2001SEmax\" has issues in certain situations. The possibility of instability may be there for all five criteria, but personally I prefer \"globalSEmax\" and SE.factor=2, the latter at least when being worried more about overfitting than about putting together clusters that are not quite as homogeneous as you'd get when sticking more rigorously to \"spherical and same within-cluster variation\".\n\n\n\n\nAt the end of the day kmeans is just not that good a clustering method for the Iris data when aiming at recovering the given groups. A Gaussian mixture with more flexible within-cluster covariance structure will do better.", "answer_url": "https://stats.stackexchange.com/a/677059", "author": "Christian Hennig", "author_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-03T12:08:52+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": 677058, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-09-03T12:08:52+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "14E907BD-0137-4FA2-93E2-A5C3763E1F24", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/14E907BD-0137-4FA2-93E2-A5C3763E1F24/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Christian Hennig", "profile_url": "https://stats.stackexchange.com/users/247165/christian-hennig", "user_type": "registered"}, "created_at": "2026-09-03T12:19:59+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "892FF292-2C1A-4474-9F3F-50E0D978AB75", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/892FF292-2C1A-4474-9F3F-50E0D978AB75/view-source"}], "score": 5, "updated_at": "2026-09-03T12:19:59+00:00"}], "domain": "statistics", "external_links": [], "medical_sensitive": false, "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": "cdalitz", "question_author_url": "https://stats.stackexchange.com/users/244807/cdalitz", "question_author_user_type": "registered", "question_created_at": "2026-09-03T11:39:13+00:00", "question_html": "While trying the gap statistics for K-Means to determine the number of clusters in the Iris dataset, I have noticed that the results are random. I have tried the following:
\nlibrary(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,"gap"],res$Tab[,"SE.sim"], method="Tibs2001SEmax")\n}\ntable(gs)\n\nNote that I have increased the number of initial random configurations (nstart) in kmeans() to 50 in order to remove the randomness from the clustering and I have set d.power=2 as recommended in the documentation of clusGap(). I turns out that the results are quite random and that the true number of clusters is never found:
gs\n 4 5 \n10 10\n\nIs this a well-known behavior of the gap statistics? What can be recommended instead that has a less random behavior?
\n", "question_id": 677058, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "While trying the gap statistics for K-Means to determine the number of clusters in the Iris dataset, I have noticed that the results are random. I have tried the following:\n\n\n\n\nlibrary(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,\"gap\"],res$Tab[,\"SE.sim\"], method=\"Tibs2001SEmax\")\n}\ntable(gs)\n\n\n\n\n\nNote that I have increased the number of initial random configurations (nstart) in kmeans() to 50 in order to remove the randomness from the clustering and I have set d.power=2 as recommended in the documentation of clusGap(). I turns out that the results are quite random and that the true number of clusters is never found:\n\n\n\n\ngs\n 4 5 \n10 10\n\n\n\n\n\nIs this a well-known behavior of the gap statistics? What can be recommended instead that has a less random behavior?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "cdalitz", "profile_url": "https://stats.stackexchange.com/users/244807/cdalitz", "user_type": "registered"}, "created_at": "2026-09-03T11:39:13+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "3E9F6246-CC0F-4366-81BC-A6A0C78ED5A6", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3E9F6246-CC0F-4366-81BC-A6A0C78ED5A6/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-09-03T16:10:42+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "59954FB6-BFDE-42B7-830F-F7F99AFF9B21", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/59954FB6-BFDE-42B7-830F-F7F99AFF9B21/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-03T19:42:12+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "BF52DD34-5A10-4522-BC49-DDE61AD72E0C", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/BF52DD34-5A10-4522-BC49-DDE61AD72E0C/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677058/instability-of-gap-statistics", "split": "train", "split_group": "9571fdd41c91a5063c5d50dd6546728a0beeeb9ea033a144996338e69417909e", "tags": ["clustering"], "thread_id": "stats:677058", "title": "Instability of gap statistics"}} {"accepted_answer": {"answer_html": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:
library(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv("https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = "re"),\n data = shiny_toad,\n method = "REML",\n family = nb(link = "log"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat("--- Temporal Autocorrelation Test for Season:", season, "---\\n")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste("Season:", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n
#> --- Temporal Autocorrelation Test for Season: WET ---\n\n
This is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.
\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):
\nHow to account for temporal autocorrelation in logistic regression with longitudinal data?
\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data?
\nCreated on 2026-09-03 with reprex v2.1.1
\n", "answer_id": 677064, "answer_text": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:\n\n\n\n\nlibrary(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv(\"https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv\") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\n\n\n\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = \"re\"),\n data = shiny_toad,\n method = \"REML\",\n family = nb(link = \"log\"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat(\"--- Temporal Autocorrelation Test for Season:\", season, \"---\\n\")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste(\"Season:\", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/6r3XH8BM.png]\n\n\n\n\n#> --- Temporal Autocorrelation Test for Season: WET ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/LfmXWxdr.png]\n\n\n\n\nThis is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.\n\n\n\n\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):\n\n\n\n\n\n\n\nHow to account for temporal autocorrelation in logistic regression with longitudinal data? (https://stats.stackexchange.com/q/395445)\n\n\n\n\n\n\n\n\n\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data? (https://stats.stackexchange.com/q/664160)\n\n\n\n\n\n\n\n\nCreated on 2026-09-03 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677064", "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-09-04T03:00:41+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": 677062, "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-09-04T03:00:41+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "33E2BC86-F580-4F03-B6B5-57A2E864905B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/33E2BC86-F580-4F03-B6B5-57A2E864905B/view-source"}], "score": 2, "updated_at": "2026-09-04T03:00:41+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "library(mgcv)\nlibrary(gratia)\nlibrary(DHARMa)\n\nsystem.time(\n by <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs=\"ts\", k=5) + \n s(DO, bs=\"ts\", k=5) +\n \n s(ave_sav, by = fDiet_presence) +\n fDiet_presence + \n \n s(fSite, bs=\"re\"),\n \n data = shiny_toad,\n method = \"REML\", \n family = nb(link = \"log\"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n##################\n\ndf <- sort(diff(sort(as.Date(shiny_toad$Date))), decreasing = TRUE)\n\n# 1. Generate the base simulated residuals once\nres <- simulateResiduals(by)\n\n# 2. Loop through each Season safely by manually subsetting the DHARMa object\nfor (Season in unique(shiny_toad$fSeason)) {\n \n cat(\"\\n--- Temporal Autocorrelation Test for Season:\", Season, \"---\\n\")\n \n # Create a logical index for the current Season\n Season_idx <- shiny_toad$fSeason == Season\n \n # Copy the base DHARMa object structure\n res_Season <- res\n \n # Manually slice all internal arrays to match only this Season's rows\n res_Season$scaledResiduals <- res$scaledResiduals[Season_idx]\n res_Season$simulatedResponse <- res$simulatedResponse[Season_idx, , drop = FALSE]\n res_Season$observedResponse <- res$observedResponse[Season_idx]\n res_Season$fittedPredictedResponse <- res$fittedPredictedResponse[Season_idx]\n res_Season$nObs <- sum(Season_idx)\n \n # Group the Season's residuals by CYR\n res_grouped <- recalculateResiduals(res_Season, group = shiny_toad$CYR[Season_idx])\n \n # Open a new plot window so they don't overwrite each other\n dev.new() \n \n # Run the test and plot\n testTemporalAutocorrelation(res_grouped, time = unique(shiny_toad$CYR[Season_idx]))\n \n # Add a title to the plot window to identify the Season\n mtext(paste(\"Season:\", Season), side = 3, line = -2, outer = TRUE, font = 2, cex = 1.2)\n}\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677062, "sha256": "6edeefd4ab605c4f39a1340c1da8a710ffcf2e5591146a18e6b1a6c23f6c035b", "source_url": "https://stats.stackexchange.com/questions/677062/how-to-check-for-temporal-auto-correlation-for-each-time-series-separately"}, {"block_index": 0, "code_text": "library(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv(\"https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv\") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677064, "sha256": "9324af2a552b94568ef3ddb3edf3d4c556edf3bd4e0e44c525a685c1d49c936a", "source_url": "https://stats.stackexchange.com/a/677064"}, {"block_index": 1, "code_text": "fit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = \"re\"),\n data = shiny_toad,\n method = \"REML\",\n family = nb(link = \"log\"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat(\"--- Temporal Autocorrelation Test for Season:\", season, \"---\\n\")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste(\"Season:\", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677064, "sha256": "ca23f80d15ba30c2d8cd5925020be422e07caf3b2ca9846a157a7530fe46c00b", "source_url": "https://stats.stackexchange.com/a/677064"}, {"block_index": 2, "code_text": "#> --- Temporal Autocorrelation Test for Season: WET ---\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677064, "sha256": "155479bd97793ff820e887b9df16a410ad412de6fcdae2902b1ee6bb854a35f7", "source_url": "https://stats.stackexchange.com/a/677064"}], "other_answers": [], "product": "code_qa", "question": "I have 2 time series in abundance that I'm modeling by a 2-level factor in mgcv , by \"fSeason\" (wet/dry), and following advice here (https://stackoverflow.com/questions/78182559/autocorrelation-in-gam-r), I should be splitting a test for auto-correlation by each factor level. I'm just not sure how to do that. Apologies for posting ChatGPT code, but I've been unsuccessful in my search everywhere else. DHARMa does have a test, but I was told it's only for a single time series. I don't think I can use the traditional AR(1) as the data are irregularly-spaced and I've never taken Bayesian statistics. Anyway, for now I'm just asking if the code AI generated is correctly identifying that I do have some, albeit weak, but significant temporal auto-correlation in the wet season. Any general advice is also welcome!\n\n\n\n\nData here (https://github.com/NateLaS/Toadfish/blob/main/share_version%20-%20toadfish.csv).\n\n\n\n\nlibrary(mgcv)\nlibrary(gratia)\nlibrary(DHARMa)\n\nsystem.time(\n by <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs=\"ts\", k=5) + \n s(DO, bs=\"ts\", k=5) +\n \n s(ave_sav, by = fDiet_presence) +\n fDiet_presence + \n \n s(fSite, bs=\"re\"),\n \n data = shiny_toad,\n method = \"REML\", \n family = nb(link = \"log\"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n##################\n\ndf <- sort(diff(sort(as.Date(shiny_toad$Date))), decreasing = TRUE)\n\n# 1. Generate the base simulated residuals once\nres <- simulateResiduals(by)\n\n# 2. Loop through each Season safely by manually subsetting the DHARMa object\nfor (Season in unique(shiny_toad$fSeason)) {\n \n cat(\"\\n--- Temporal Autocorrelation Test for Season:\", Season, \"---\\n\")\n \n # Create a logical index for the current Season\n Season_idx <- shiny_toad$fSeason == Season\n \n # Copy the base DHARMa object structure\n res_Season <- res\n \n # Manually slice all internal arrays to match only this Season's rows\n res_Season$scaledResiduals <- res$scaledResiduals[Season_idx]\n res_Season$simulatedResponse <- res$simulatedResponse[Season_idx, , drop = FALSE]\n res_Season$observedResponse <- res$observedResponse[Season_idx]\n res_Season$fittedPredictedResponse <- res$fittedPredictedResponse[Season_idx]\n res_Season$nObs <- sum(Season_idx)\n \n # Group the Season's residuals by CYR\n res_grouped <- recalculateResiduals(res_Season, group = shiny_toad$CYR[Season_idx])\n \n # Open a new plot window so they don't overwrite each other\n dev.new() \n \n # Run the test and plot\n testTemporalAutocorrelation(res_grouped, time = unique(shiny_toad$CYR[Season_idx]))\n \n # Add a title to the plot window to identify the Season\n mtext(paste(\"Season:\", Season), side = 3, line = -2, outer = TRUE, font = 2, cex = 1.2)\n}\n\n\n\n\n\n\nSite locations were haphazardly chosen (before my time) to monitor changes in fish abundance due to the construction of new canals (data posted here not collected with this statistical model/set of hypotheses in mind - its just available). Timing of surveys is based on tide level (need at least 60 cm/2 ft of water to survey near shore during the day (during reg. working hours). It takes about 4-7 days to survey every site start-to-finish. Timing is also weather dependant. Also it takes 4-5 months to sort, ID, weigh and measure everything we catch. March/Sept is just avoid swimming in really cold water and give time between sample processesing of new data.\n\n\n\n\n[image: ChatGPT result; source: https://i.sstatic.net/XIgn1m2c.png]", "record_id": "Scientific-Code-and-Analysis-QA:stats:677062", "selected_answer": {"answer_html": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:
library(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv("https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = "re"),\n data = shiny_toad,\n method = "REML",\n family = nb(link = "log"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat("--- Temporal Autocorrelation Test for Season:", season, "---\\n")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste("Season:", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n
#> --- Temporal Autocorrelation Test for Season: WET ---\n\n
This is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.
\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):
\nHow to account for temporal autocorrelation in logistic regression with longitudinal data?
\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data?
\nCreated on 2026-09-03 with reprex v2.1.1
\n", "answer_id": 677064, "answer_text": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:\n\n\n\n\nlibrary(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv(\"https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv\") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\n\n\n\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = \"re\"),\n data = shiny_toad,\n method = \"REML\",\n family = nb(link = \"log\"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat(\"--- Temporal Autocorrelation Test for Season:\", season, \"---\\n\")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste(\"Season:\", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/6r3XH8BM.png]\n\n\n\n\n#> --- Temporal Autocorrelation Test for Season: WET ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/LfmXWxdr.png]\n\n\n\n\nThis is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.\n\n\n\n\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):\n\n\n\n\n\n\n\nHow to account for temporal autocorrelation in logistic regression with longitudinal data? (https://stats.stackexchange.com/q/395445)\n\n\n\n\n\n\n\n\n\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data? (https://stats.stackexchange.com/q/664160)\n\n\n\n\n\n\n\n\nCreated on 2026-09-03 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677064", "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-09-04T03:00:41+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": 677062, "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-09-04T03:00:41+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "33E2BC86-F580-4F03-B6B5-57A2E864905B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/33E2BC86-F580-4F03-B6B5-57A2E864905B/view-source"}], "score": 2, "updated_at": "2026-09-04T03:00:41+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677064, "answers": [{"answer_html": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:
library(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv("https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = "re"),\n data = shiny_toad,\n method = "REML",\n family = nb(link = "log"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat("--- Temporal Autocorrelation Test for Season:", season, "---\\n")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste("Season:", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n
#> --- Temporal Autocorrelation Test for Season: WET ---\n\n
This is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.
\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):
\nHow to account for temporal autocorrelation in logistic regression with longitudinal data?
\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data?
\nCreated on 2026-09-03 with reprex v2.1.1
\n", "answer_id": 677064, "answer_text": "The AI-generated code manually slices {DHARMa}'s internal arrays, which is fragile. The cleaner approach would be to use recalculateResiduals() with NA for the other season's rows, letting DHARMa's NA handling drop them during grouping:\n\n\n\n\nlibrary(mgcv)\nlibrary(DHARMa)\nlibrary(dplyr)\n\nshiny_toad <- read.csv(\"https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv\") |>\n mutate(\n fSeason = factor(Season),\n fSite = factor(Site),\n Date = as.Date(Date)\n )\n\n\n\n\n\nfit <- gam(total_count ~\n s(CYR, by = fSeason) +\n fSeason +\n s(fSite, bs = \"re\"),\n data = shiny_toad,\n method = \"REML\",\n family = nb(link = \"log\"))\n\nres <- simulateResiduals(fit)\n\nused_idx <- as.integer(rownames(fit$model))\n\nfor (season in levels(shiny_toad$fSeason)) {\n cat(\"--- Temporal Autocorrelation Test for Season:\", season, \"---\\n\")\n \n idx <- shiny_toad$fSeason[used_idx] == season\n group_vec <- ifelse(idx, shiny_toad$CYR[used_idx], NA)\n \n res_grouped <- recalculateResiduals(res, group = group_vec)\n \n testTemporalAutocorrelation(res_grouped,\n time = unique(sort(shiny_toad$CYR[used_idx][idx])),\n plot = TRUE)\n title(paste(\"Season:\", season))\n}\n\n#> --- Temporal Autocorrelation Test for Season: DRY ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/6r3XH8BM.png]\n\n\n\n\n#> --- Temporal Autocorrelation Test for Season: WET ---\n\n\n\n\n\n[image: ; source: https://i.sstatic.net/LfmXWxdr.png]\n\n\n\n\nThis is essentially the same as what you got from your code, but without manual slicing and whatnot. The wet season shows significant temporal autocorrelation (Durbin-Watson p = 0.005) with an alternating high/low pattern in the residuals, suggesting the model is over- and under-predicting in alternating years. The dry season shows no significant autocorrelation (p = 0.41). But, you should note that the DRY season has no observations in 2021, so the test treats 2022 as immediately following 2020 and would not detect autocorrelation if there is any across that gap.\n\n\n\n\nFor general advice, take a look at these posts (tbh, I'm reaching the end of my rope on this topic):\n\n\n\n\n\n\n\nHow to account for temporal autocorrelation in logistic regression with longitudinal data? (https://stats.stackexchange.com/q/395445)\n\n\n\n\n\n\n\n\n\nR: How to test for, or visualize, autocorrelation in irregularly spaced count data? (https://stats.stackexchange.com/q/664160)\n\n\n\n\n\n\n\n\nCreated on 2026-09-03 with reprex v2.1.1 (https://reprex.tidyverse.org)", "answer_url": "https://stats.stackexchange.com/a/677064", "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-09-04T03:00:41+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": 677062, "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-09-04T03:00:41+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "33E2BC86-F580-4F03-B6B5-57A2E864905B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/33E2BC86-F580-4F03-B6B5-57A2E864905B/view-source"}], "score": 2, "updated_at": "2026-09-04T03:00:41+00:00"}], "domain": "statistics", "external_links": ["https://github.com/NateLaS/Toadfish/blob/main/share_version%20-%20toadfish.csv", "https://i.sstatic.net/6r3XH8BM.png", "https://i.sstatic.net/LfmXWxdr.png", "https://i.sstatic.net/XIgn1m2c.png", "https://raw.githubusercontent.com/NateLaS/Toadfish/main/share_version%20-%20toadfish.csv", "https://reprex.tidyverse.org"], "medical_sensitive": false, "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": "Nate", "question_author_url": "https://stats.stackexchange.com/users/337106/nate", "question_author_user_type": "registered", "question_created_at": "2026-09-03T14:57:31+00:00", "question_html": "I have 2 time series in abundance that I'm modeling by a 2-level factor in mgcv , by "fSeason" (wet/dry), and following advice here, I should be splitting a test for auto-correlation by each factor level. I'm just not sure how to do that. Apologies for posting ChatGPT code, but I've been unsuccessful in my search everywhere else. DHARMa does have a test, but I was told it's only for a single time series. I don't think I can use the traditional AR(1) as the data are irregularly-spaced and I've never taken Bayesian statistics. Anyway, for now I'm just asking if the code AI generated is correctly identifying that I do have some, albeit weak, but significant temporal auto-correlation in the wet season. Any general advice is also welcome!
Data here.
\nlibrary(mgcv)\nlibrary(gratia)\nlibrary(DHARMa)\n\nsystem.time(\n by <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs="ts", k=5) + \n s(DO, bs="ts", k=5) +\n \n s(ave_sav, by = fDiet_presence) +\n fDiet_presence + \n \n s(fSite, bs="re"),\n \n data = shiny_toad,\n method = "REML", \n family = nb(link = "log"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n##################\n\ndf <- sort(diff(sort(as.Date(shiny_toad$Date))), decreasing = TRUE)\n\n# 1. Generate the base simulated residuals once\nres <- simulateResiduals(by)\n\n# 2. Loop through each Season safely by manually subsetting the DHARMa object\nfor (Season in unique(shiny_toad$fSeason)) {\n \n cat("\\n--- Temporal Autocorrelation Test for Season:", Season, "---\\n")\n \n # Create a logical index for the current Season\n Season_idx <- shiny_toad$fSeason == Season\n \n # Copy the base DHARMa object structure\n res_Season <- res\n \n # Manually slice all internal arrays to match only this Season's rows\n res_Season$scaledResiduals <- res$scaledResiduals[Season_idx]\n res_Season$simulatedResponse <- res$simulatedResponse[Season_idx, , drop = FALSE]\n res_Season$observedResponse <- res$observedResponse[Season_idx]\n res_Season$fittedPredictedResponse <- res$fittedPredictedResponse[Season_idx]\n res_Season$nObs <- sum(Season_idx)\n \n # Group the Season's residuals by CYR\n res_grouped <- recalculateResiduals(res_Season, group = shiny_toad$CYR[Season_idx])\n \n # Open a new plot window so they don't overwrite each other\n dev.new() \n \n # Run the test and plot\n testTemporalAutocorrelation(res_grouped, time = unique(shiny_toad$CYR[Season_idx]))\n \n # Add a title to the plot window to identify the Season\n mtext(paste("Season:", Season), side = 3, line = -2, outer = TRUE, font = 2, cex = 1.2)\n}\n\n\nSite locations were haphazardly chosen (before my time) to monitor changes in fish abundance due to the construction of new canals (data posted here not collected with this statistical model/set of hypotheses in mind - its just available). Timing of surveys is based on tide level (need at least 60 cm/2 ft of water to survey near shore during the day (during reg. working hours). It takes about 4-7 days to survey every site start-to-finish. Timing is also weather dependant. Also it takes 4-5 months to sort, ID, weigh and measure everything we catch. March/Sept is just avoid swimming in really cold water and give time between sample processesing of new data.
\n
Well your current "random" approach is, pardon my choice of words, mildly horrific. I'm absolutely not opposed to experimentation, but you should always run a quick test with a simulated where you know the ground truth.
\nLet's make one were all the $\\mu$s are 0, with very different $\\sigma$ per group:
\nset.seed("1")\nn <- 1000\ndf <- data.frame(x = sample(c("A", "B"), n, replace = T, prob = c(7,3)))\ndf$y <- rnorm(n, sd = ifelse(df$x == "A", 1, 4))\n\nols_model<- lm(y ~ x, data = df)\nsummary(ols_model)\n\nwls_model<- lm(y ~ x, data = df, weights = 1/residuals(ols_model)^2)\nsummary(wls_model)\n\nWe know the all means are 0, i.e. p-values should not be too small but by assigning all the weight to observations close to the ols-model prediction you have generated a huge amount of overconfidence:
\n> summary(wls_model)\n\nCall:\nlm(formula = y ~ x, data = df, weights = 1/residuals(ols_model)^2)\n\nWeighted Residuals:\n Min 1Q Median 3Q Max \n-1.2312 -1.0023 -1.0003 0.9977 0.9998 \n\nCoefficients:\n Estimate Std. Error t value\n(Intercept) -0.027082 0.001709 -15.85\nxB -0.025303 0.003694 -6.85\n Pr(>|t|) \n(Intercept) < 2e-16 ***\nxB 1.29e-11 ***\n---\nSignif. codes: \n0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 1 on 998 degrees of freedom\nMultiple R-squared: 0.0449, Adjusted R-squared: 0.04395 \nF-statistic: 46.92 on 1 and 998 DF, p-value: 1.291e-11\n\nUnderstand heteroskedasticity a little better and probably use robust standard errors always, even if you have no reason to suspect it. For this, I recommend this Datacolada post by Uri Simonsohn: Heterofriendly: The Intuition for Why You Always Need Robust Standard Errors.
\nAlternatively you can model the residual standard deviation based on explanatory variables directly in glmmTMB using the dispformula. Note it works with log-link:
library(glmmTMB)\n# -1 in the dispformula is convenient here but not necessary\nm_tmb <- glmmTMB(y ~ x, dispformula = ~x-1, data = df) \nsummary(m_tmb)\nconfint(m_tmb)\nexp(confint(m_tmb)[3:4, ])\n\n\nThe standard errors for the coefficients are essentially identical to those in the robust(also called sandwich) estimator:
\nlibrary(sandwich)\nsqrt(diag(vcovHC(ols_model)))\n\ncompare outputs:
\n> sqrt(diag(vcovHC(ols_model)))\n(Intercept) xB \n 0.03938899 0.23850244 \n> summary(m_tmb)\n...\nConditional model:\n Estimate Std. Error z value\n(Intercept) -0.02917 0.03933 -0.742\nxB -0.02555 0.23773 -0.108\n Pr(>|z|)\n(Intercept) 0.458\nxB 0.914\n\n\n", "answer_id": 677077, "answer_text": "Well your current \"random\" approach is, pardon my choice of words, mildly horrific. I'm absolutely not opposed to experimentation, but you should always run a quick test with a simulated where you know the ground truth.\n\n\n\n\nLet's make one were all the $\\mu$s are 0, with very different $\\sigma$ per group:\n\n\n\n\nset.seed(\"1\")\nn <- 1000\ndf <- data.frame(x = sample(c(\"A\", \"B\"), n, replace = T, prob = c(7,3)))\ndf$y <- rnorm(n, sd = ifelse(df$x == \"A\", 1, 4))\n\nols_model<- lm(y ~ x, data = df)\nsummary(ols_model)\n\nwls_model<- lm(y ~ x, data = df, weights = 1/residuals(ols_model)^2)\nsummary(wls_model)\n\n\n\n\n\nWe know the all means are 0, i.e. p-values should not be too small but by assigning all the weight to observations close to the ols-model prediction you have generated a huge amount of overconfidence:\n\n\n\n\n> summary(wls_model)\n\nCall:\nlm(formula = y ~ x, data = df, weights = 1/residuals(ols_model)^2)\n\nWeighted Residuals:\n Min 1Q Median 3Q Max \n-1.2312 -1.0023 -1.0003 0.9977 0.9998 \n\nCoefficients:\n Estimate Std. Error t value\n(Intercept) -0.027082 0.001709 -15.85\nxB -0.025303 0.003694 -6.85\n Pr(>|t|) \n(Intercept) < 2e-16 ***\nxB 1.29e-11 ***\n---\nSignif. codes: \n0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 1 on 998 degrees of freedom\nMultiple R-squared: 0.0449, Adjusted R-squared: 0.04395 \nF-statistic: 46.92 on 1 and 998 DF, p-value: 1.291e-11\n\n\n\n\n\nWhat should you do?\n\n\n\n\nUnderstand heteroskedasticity a little better and probably use robust standard errors always, even if you have no reason to suspect it. For this, I recommend this Datacolada post by Uri Simonsohn: Heterofriendly: The Intuition for Why You Always Need Robust Standard Errors (https://datacolada.org/133).\n\n\n\n\nAlternatively you can model the residual standard deviation based on explanatory variables directly in glmmTMB using the dispformula. Note it works with log-link:\n\n\n\n\nlibrary(glmmTMB)\n# -1 in the dispformula is convenient here but not necessary\nm_tmb <- glmmTMB(y ~ x, dispformula = ~x-1, data = df) \nsummary(m_tmb)\nconfint(m_tmb)\nexp(confint(m_tmb)[3:4, ])\n\n\n\n\n\n\nThe standard errors for the coefficients are essentially identical to those in the robust(also called sandwich) estimator:\n\n\n\n\nlibrary(sandwich)\nsqrt(diag(vcovHC(ols_model)))\n\n\n\n\n\ncompare outputs:\n\n\n\n\n> sqrt(diag(vcovHC(ols_model)))\n(Intercept) xB \n 0.03938899 0.23850244 \n> summary(m_tmb)\n...\nConditional model:\n Estimate Std. Error z value\n(Intercept) -0.02917 0.03933 -0.742\nxB -0.02555 0.23773 -0.108\n Pr(>|z|)\n(Intercept) 0.458\nxB 0.914", "answer_url": "https://stats.stackexchange.com/a/677077", "author": "Lukas Lohse", "author_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-05T07:37:51+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": 677065, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lukas Lohse", "profile_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "user_type": "registered"}, "created_at": "2026-09-05T07:37:51+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "AF59F8AE-13A2-4F33-B6ED-5B8F9212D291", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AF59F8AE-13A2-4F33-B6ED-5B8F9212D291/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-09-06T11:16:54+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "6C75896D-FF63-4725-B64D-771290FD9D36", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/6C75896D-FF63-4725-B64D-771290FD9D36/view-source"}], "score": 2, "updated_at": "2026-09-06T11:16:54+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Well your current "random" approach is, pardon my choice of words, mildly horrific. I'm absolutely not opposed to experimentation, but you should always run a quick test with a simulated where you know the ground truth.
\nLet's make one were all the $\\mu$s are 0, with very different $\\sigma$ per group:
\nset.seed("1")\nn <- 1000\ndf <- data.frame(x = sample(c("A", "B"), n, replace = T, prob = c(7,3)))\ndf$y <- rnorm(n, sd = ifelse(df$x == "A", 1, 4))\n\nols_model<- lm(y ~ x, data = df)\nsummary(ols_model)\n\nwls_model<- lm(y ~ x, data = df, weights = 1/residuals(ols_model)^2)\nsummary(wls_model)\n\nWe know the all means are 0, i.e. p-values should not be too small but by assigning all the weight to observations close to the ols-model prediction you have generated a huge amount of overconfidence:
\n> summary(wls_model)\n\nCall:\nlm(formula = y ~ x, data = df, weights = 1/residuals(ols_model)^2)\n\nWeighted Residuals:\n Min 1Q Median 3Q Max \n-1.2312 -1.0023 -1.0003 0.9977 0.9998 \n\nCoefficients:\n Estimate Std. Error t value\n(Intercept) -0.027082 0.001709 -15.85\nxB -0.025303 0.003694 -6.85\n Pr(>|t|) \n(Intercept) < 2e-16 ***\nxB 1.29e-11 ***\n---\nSignif. codes: \n0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 1 on 998 degrees of freedom\nMultiple R-squared: 0.0449, Adjusted R-squared: 0.04395 \nF-statistic: 46.92 on 1 and 998 DF, p-value: 1.291e-11\n\nUnderstand heteroskedasticity a little better and probably use robust standard errors always, even if you have no reason to suspect it. For this, I recommend this Datacolada post by Uri Simonsohn: Heterofriendly: The Intuition for Why You Always Need Robust Standard Errors.
\nAlternatively you can model the residual standard deviation based on explanatory variables directly in glmmTMB using the dispformula. Note it works with log-link:
library(glmmTMB)\n# -1 in the dispformula is convenient here but not necessary\nm_tmb <- glmmTMB(y ~ x, dispformula = ~x-1, data = df) \nsummary(m_tmb)\nconfint(m_tmb)\nexp(confint(m_tmb)[3:4, ])\n\n\nThe standard errors for the coefficients are essentially identical to those in the robust(also called sandwich) estimator:
\nlibrary(sandwich)\nsqrt(diag(vcovHC(ols_model)))\n\ncompare outputs:
\n> sqrt(diag(vcovHC(ols_model)))\n(Intercept) xB \n 0.03938899 0.23850244 \n> summary(m_tmb)\n...\nConditional model:\n Estimate Std. Error z value\n(Intercept) -0.02917 0.03933 -0.742\nxB -0.02555 0.23773 -0.108\n Pr(>|z|)\n(Intercept) 0.458\nxB 0.914\n\n\n", "answer_id": 677077, "answer_text": "Well your current \"random\" approach is, pardon my choice of words, mildly horrific. I'm absolutely not opposed to experimentation, but you should always run a quick test with a simulated where you know the ground truth.\n\n\n\n\nLet's make one were all the $\\mu$s are 0, with very different $\\sigma$ per group:\n\n\n\n\nset.seed(\"1\")\nn <- 1000\ndf <- data.frame(x = sample(c(\"A\", \"B\"), n, replace = T, prob = c(7,3)))\ndf$y <- rnorm(n, sd = ifelse(df$x == \"A\", 1, 4))\n\nols_model<- lm(y ~ x, data = df)\nsummary(ols_model)\n\nwls_model<- lm(y ~ x, data = df, weights = 1/residuals(ols_model)^2)\nsummary(wls_model)\n\n\n\n\n\nWe know the all means are 0, i.e. p-values should not be too small but by assigning all the weight to observations close to the ols-model prediction you have generated a huge amount of overconfidence:\n\n\n\n\n> summary(wls_model)\n\nCall:\nlm(formula = y ~ x, data = df, weights = 1/residuals(ols_model)^2)\n\nWeighted Residuals:\n Min 1Q Median 3Q Max \n-1.2312 -1.0023 -1.0003 0.9977 0.9998 \n\nCoefficients:\n Estimate Std. Error t value\n(Intercept) -0.027082 0.001709 -15.85\nxB -0.025303 0.003694 -6.85\n Pr(>|t|) \n(Intercept) < 2e-16 ***\nxB 1.29e-11 ***\n---\nSignif. codes: \n0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 1 on 998 degrees of freedom\nMultiple R-squared: 0.0449, Adjusted R-squared: 0.04395 \nF-statistic: 46.92 on 1 and 998 DF, p-value: 1.291e-11\n\n\n\n\n\nWhat should you do?\n\n\n\n\nUnderstand heteroskedasticity a little better and probably use robust standard errors always, even if you have no reason to suspect it. For this, I recommend this Datacolada post by Uri Simonsohn: Heterofriendly: The Intuition for Why You Always Need Robust Standard Errors (https://datacolada.org/133).\n\n\n\n\nAlternatively you can model the residual standard deviation based on explanatory variables directly in glmmTMB using the dispformula. Note it works with log-link:\n\n\n\n\nlibrary(glmmTMB)\n# -1 in the dispformula is convenient here but not necessary\nm_tmb <- glmmTMB(y ~ x, dispformula = ~x-1, data = df) \nsummary(m_tmb)\nconfint(m_tmb)\nexp(confint(m_tmb)[3:4, ])\n\n\n\n\n\n\nThe standard errors for the coefficients are essentially identical to those in the robust(also called sandwich) estimator:\n\n\n\n\nlibrary(sandwich)\nsqrt(diag(vcovHC(ols_model)))\n\n\n\n\n\ncompare outputs:\n\n\n\n\n> sqrt(diag(vcovHC(ols_model)))\n(Intercept) xB \n 0.03938899 0.23850244 \n> summary(m_tmb)\n...\nConditional model:\n Estimate Std. Error z value\n(Intercept) -0.02917 0.03933 -0.742\nxB -0.02555 0.23773 -0.108\n Pr(>|z|)\n(Intercept) 0.458\nxB 0.914", "answer_url": "https://stats.stackexchange.com/a/677077", "author": "Lukas Lohse", "author_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-05T07:37:51+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": 677065, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lukas Lohse", "profile_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "user_type": "registered"}, "created_at": "2026-09-05T07:37:51+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "AF59F8AE-13A2-4F33-B6ED-5B8F9212D291", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AF59F8AE-13A2-4F33-B6ED-5B8F9212D291/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-09-06T11:16:54+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "6C75896D-FF63-4725-B64D-771290FD9D36", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/6C75896D-FF63-4725-B64D-771290FD9D36/view-source"}], "score": 2, "updated_at": "2026-09-06T11:16:54+00:00"}], "domain": "statistics", "external_links": ["https://datacolada.org/133"], "medical_sensitive": false, "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": "Taniya Polley", "question_author_url": "https://stats.stackexchange.com/users/406759/taniya-polley", "question_author_user_type": "registered", "question_created_at": "2026-09-04T09:58:25+00:00", "question_html": "I have got a dataset, I'm trying to perform weighted least square regression. But I'm a bit stuck at the bptest results I'm getting.
Here, the response variable is charges.
I ran the following code.
\nols_model <- lm(charges~., data = df)\n\nTo test heteroscedasticity, I tried with bptest and got the following result.
studentized Breusch-Pagan test\ndata: ols_model\nBP = 121.74, df = 8, p-value < 2.2e-16\n\nClearly I can see that heteroscedasticity is present. I'm trying to do a weighted least square regression. My question is how to estimate the weights? Randomly, I have done this:
\nwls_model <- lm(charges ~., data = df, weights = 1/residuals(ols_model)^2)\n\nnow, bptest result is
\n studentized Breusch-Pagan test\ndata: wls_model\nBP = 1.049e-06, df = 8, p-value = 1\n\nHere, p-value is 1.
\nI changed the code a bit to this:
\nwls_model <- lm(charges ~., data = df, weights = 1/abs(residuals(ols_model)))\nbptest(wls_model)\n\nand got,
\n studentized Breusch-Pagan test\ndata: wls_model\nBP = 0.024283, df = 8, p-value = 1\n\nHere is also the p-value is 1. What does it mean?
\nI'm struggling with it for days, any help is appreciated.
\n", "question_id": 677065, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I have got a dataset, I'm trying to perform weighted least square regression. But I'm a bit stuck at the bptest results I'm getting.\n\n\n\n\nHere, the response variable is charges.\n\n\n\n\nI ran the following code.\n\n\n\n\nols_model <- lm(charges~., data = df)\n\n\n\n\n\nTo test heteroscedasticity, I tried with bptest and got the following result.\n\n\n\n\n studentized Breusch-Pagan test\ndata: ols_model\nBP = 121.74, df = 8, p-value < 2.2e-16\n\n\n\n\n\nClearly I can see that heteroscedasticity is present. I'm trying to do a weighted least square regression. My question is how to estimate the weights? Randomly, I have done this:\n\n\n\n\nwls_model <- lm(charges ~., data = df, weights = 1/residuals(ols_model)^2)\n\n\n\n\n\nnow, bptest result is\n\n\n\n\n studentized Breusch-Pagan test\ndata: wls_model\nBP = 1.049e-06, df = 8, p-value = 1\n\n\n\n\n\nHere, p-value is 1.\n\n\n\n\nI changed the code a bit to this:\n\n\n\n\nwls_model <- lm(charges ~., data = df, weights = 1/abs(residuals(ols_model)))\nbptest(wls_model)\n\n\n\n\n\nand got,\n\n\n\n\n studentized Breusch-Pagan test\ndata: wls_model\nBP = 0.024283, df = 8, p-value = 1\n\n\n\n\n\nHere is also the p-value is 1. What does it mean?\n\n\n\n\nI'm struggling with it for days, any help is appreciated.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Taniya Polley", "profile_url": "https://stats.stackexchange.com/users/406759/taniya-polley", "user_type": "registered"}, "created_at": "2026-09-04T09:58:25+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "1D552DE1-4EDD-4089-9DB4-F81625A87D66", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1D552DE1-4EDD-4089-9DB4-F81625A87D66/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-09-04T11:59:00+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "CB9EEA9B-4D06-46E2-9771-D2DA63D3EF68", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB9EEA9B-4D06-46E2-9771-D2DA63D3EF68/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-05T02:22:46+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "85B683DD-67D1-425C-930B-22B9801796B9", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/85B683DD-67D1-425C-930B-22B9801796B9/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677065/interpretation-of-bptest-breusch-pagan-test-result-in-r", "split": "holdout", "split_group": "c763aa17e65a086ede0658f392eb86a8f7338db6699bac7b4de67150489c7722", "tags": ["r", "econometrics", "weighted-regression"], "thread_id": "stats:677065", "title": "Interpretation of bptest (Breusch-Pagan test) result in R"}} {"accepted_answer": {"answer_html": "I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:
# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n <dbl> <int>\n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.
I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n", "answer_id": 677089, "answer_text": "I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:
# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n <dbl> <int>\n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.
I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n", "answer_id": 677089, "answer_text": "I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:
# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n <dbl> <int>\n1 0 985\n2 1 102\n3 2 34\n4 3 10\n5 4 10\n6 5 2\n7 7 1\n8 18 1\n\nAs a Pearson residual, which DHARMa uses at refit = T, the 18 is just a bit over 2, so "fine". I maintain that your negative binomial model is perfectly compatible with your data, but you just don't have much data in the range where 18 is evidently possible, at least not compared with how rare they are.\nSimulations/forecasts will therefore be very uncertain. Inference about means might not be.
I couldn't run your model directly (variables like fDiet_presence are missing) but this is something you could replicate:
x <- predict(full_model)\nplot(x, shiny_toad$total_count, ylim = c(0, 25), xlim = c(-2, 1.1))\n# takes a few seconds\nfor (i in 1:250)\n points(x, simulationOutput$simulatedResponse[, i], col = rgb(1,0,0, alpha = 0.05), pch = 19)\npoints(x, shiny_toad$total_count)\ncurve(exp(x), add = T)\ncurve(qnbinom(0.99, size = 0.582, mu = exp(x)), add = T \n\n\n", "answer_id": 677089, "answer_text": "I see what's going on here. When refit = F DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at 18:\n\n\n\n\n# library(tidyverse)\n> shiny_toad %>% group_by(total_count) %>% \n+ summarise(n()) #%>% \n# A tibble: 8 × 2\n total_count `n()`\n Are long tails in a fitted vs. simulated residuals plot from DHARMa a sign of over-fitting (or any other issues)? Do they make the test for dispersion overly optimistic (p-value > 0.05)? I'm not sure if this is a problem simply because it's not significant, but are there ways to model theta in mgcv? Is it necessary here? No zero-inflation: ratioObsSim = 0.9977, p-value = 0.864, and only 1 outlier more than expected: outliers at both margin(s) = 1, observations = 1145, p-value = 0.36.
Data here
\nshiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_presence, ref = "no food")\n\nlibrary(mgcv)\nlibrary(DHARMa)\n\nsystem.time(\n full_model <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs="ts", k=5) +\n s(DO, bs="ts", k=5) +\n\n s(ave_sav, by = fDiet_presence) +\n fDiet_presence +\n \n s(fSite, bs="re"),\n \n data = shiny_toad,\n method = "REML", \n family = nb(link = "log"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n> simulationOutput <- simulateResiduals(fittedModel = full_model)\n> testDispersion(simulationOutput)\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs.\n simulated\n\ndata: simulationOutput\ndispersion = 1.151, p-value = 0.44\nalternative hypothesis: two.sided\n\n\n", "question_id": 677079, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "Are long tails in a fitted vs. simulated residuals plot from DHARMa a sign of over-fitting (or any other issues)? Do they make the test for dispersion overly optimistic (p-value > 0.05)? I'm not sure if this is a problem simply because it's not significant, but are there ways to model theta in mgcv? Is it necessary here? No zero-inflation: ratioObsSim = 0.9977, p-value = 0.864, and only 1 outlier more than expected: outliers at both margin(s) = 1, observations = 1145, p-value = 0.36.\n\n\n\n\nData here (https://github.com/NateLaS/Toadfish/blob/main/share_version%20-%20toadfish.csv)\n\n\n\n\nshiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_presence, ref = \"no food\")\n\nlibrary(mgcv)\nlibrary(DHARMa)\n\nsystem.time(\n full_model <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(sal, bs=\"ts\", k=5) +\n s(DO, bs=\"ts\", k=5) +\n\n s(ave_sav, by = fDiet_presence) +\n fDiet_presence +\n \n s(fSite, bs=\"re\"),\n \n data = shiny_toad,\n method = \"REML\", \n family = nb(link = \"log\"),\n select = FALSE, \n \n drop.unused.levels = FALSE, \n control = list(trace = TRUE))\n)\n\n> simulationOutput <- simulateResiduals(fittedModel = full_model)\n> testDispersion(simulationOutput)\n\n DHARMa nonparametric dispersion test via sd of residuals fitted vs.\n simulated\n\ndata: simulationOutput\ndispersion = 1.151, p-value = 0.44\nalternative hypothesis: two.sided\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/JpiINT52.png] (https://i.sstatic.net/JpiINT52.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-09-05T17:50:46+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "62485478-1E70-4507-A25A-EFD7CF98BE71", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/62485478-1E70-4507-A25A-EFD7CF98BE71/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-09-05T18:00:15+00:00", "raw_file": "raw/codex_api_v1/64ee278f47b21ead17c9e9fc156835d607f15cff0518af0117a527463a68df8a_1790825256327661600_0.json", "raw_sha256": "18d894000304f6d836d0b21a9f2f35d37c183b3d25e32a897338c6dff012df04", "revision_guid": "20C1E059-9409-4237-A047-3AC90CDF12F1", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/20C1E059-9409-4237-A047-3AC90CDF12F1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-09-06T11:10:30+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "218741D1-87E1-45D3-9356-2175B506F115", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/218741D1-87E1-45D3-9356-2175B506F115/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nate", "profile_url": "https://stats.stackexchange.com/users/337106/nate", "user_type": "registered"}, "created_at": "2026-09-06T16:02:30+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "68679B7E-46AA-465C-8DEB-E7300F26A45C", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/68679B7E-46AA-465C-8DEB-E7300F26A45C/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-06T16:44:53+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "FCE33A0B-2FF0-443A-AAE5-C039C64F1D4A", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/FCE33A0B-2FF0-443A-AAE5-C039C64F1D4A/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677079/dharma-are-long-tails-in-dispersion-plot-a-problem", "split": "train", "split_group": "04a77f3456ebfb67020241072d2e6012e18b8e493f7d3df8ca4d468735284bb3", "tags": ["overfitting", "mgcv", "overdispersion", "dharma"], "thread_id": "stats:677079", "title": "DHARMa: Are long tails in dispersion plot a problem?"}}
{"accepted_answer": {"answer_html": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.
\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.
fit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\nFull code:
\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf("[%2d/%2d] n = %3d, k = %d ... ", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf("done (%.1fs elapsed)\\n",\n as.numeric(difftime(Sys.time(), t0, units = "secs"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c("moments", "mle"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c("true_mean", "true_variance", "n", "k", "true_var_of_mean", \n "mean_estimate", "bias", "mc_se", "sd_estimate", \n "variance_estimate", "length_of_interval", "coverage")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == "moments")\ndf_mle <- subset(res_df, method == "mle")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = "n", y = y_label, color = "k") +\n theme_bw() +\n theme(legend.position = "bottom",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = "dashed", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, "bias", "Moments: bias of the estimated mean", \n "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np2 <- make_panel(df_mle, "bias", "MLE: bias of the estimated mean", \n "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np3 <- make_panel(df_mom, "sd_estimate", "Moments: SD of the estimated mean", \n "Spread of the estimate across studies.", "SD")\np4 <- make_panel(df_mle, "sd_estimate", "MLE: SD of the estimated mean", \n "Spread of the estimate across studies.", "SD")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = "dashed") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = "Coverage of the nominal 95% interval",\n subtitle = "Share of 1000 intervals containing the true mean. Dashed line at 0.95.",\n x = "n",\n y = "coverage",\n color = "method") +\n theme_bw() +\n theme(legend.position = "bottom",\n strip.background = element_rect(fill = "grey90"))\n\nprint(p_cov)\n\n", "answer_id": 677117, "answer_text": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.\n\n\n\n\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.\n\n\n\n\nfit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/yrEHvkk0.png] (https://i.sstatic.net/yrEHvkk0.png)\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/9nEiiFBK.png] (https://i.sstatic.net/9nEiiFBK.png)\n\n\n\n\nFull code:\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)", "answer_url": "https://stats.stackexchange.com/a/677117", "author": "jblood94", "author_url": "https://stats.stackexchange.com/users/214015/jblood94", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-09T13:02:57+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": 677094, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jblood94", "profile_url": "https://stats.stackexchange.com/users/214015/jblood94", "user_type": "registered"}, "created_at": "2026-09-09T13:02:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "09E52470-6B69-4568-A8B3-D52476EA341B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "20C3E36B-1564-462F-9257-5BBE5B9B70EF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}], "score": 3, "updated_at": "2026-09-09T13:02:57+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = \"BFGS\",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, \"try-error\")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677094, "sha256": "748b8957c64ad9c882e5131628ded56e236fa132e526ea16319627b14f44d2e8", "source_url": "https://stats.stackexchange.com/questions/677094/can-coverage-probability-decrease-as-sample-size-increases"}, {"block_index": 0, "code_text": "fit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677117, "sha256": "51cc539111e4e5bb9577cca7f1743154014577b6d727c2354ce8054c03f21b29", "source_url": "https://stats.stackexchange.com/a/677117"}, {"block_index": 1, "code_text": "library(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677117, "sha256": "b749e1889b6f66b0bc1acd992da72507b9cf5e17536a32c9b5d036efb773fd2a", "source_url": "https://stats.stackexchange.com/a/677117"}], "other_answers": [], "product": "code_qa", "question": "Here is a beta-binomial model (treated like repeated measures - $i$ is an index for each individual, $n$ total individuals, and exactly $k$ measurements per individual):\n\n\n\n\n$$\\theta_i \\stackrel{\\text{iid}}{\\sim} \\mathrm{Beta}(a,b), \\qquad x_i \\mid \\theta_i \\sim \\mathrm{Binomial}(k,\\theta_i), \\qquad \\hat p_i = \\frac{x_i}{k}, \\qquad i = 1,\\dots,n$$\n\n\n\n\n$$\\mu = E[\\theta_i] = \\frac{a}{a+b}$$\n\n\n\n\n$$\\sigma^2 = \\operatorname{Var}(\\theta_i) = \\frac{ab}{(a+b)^2(a+b+1)}$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i(1-\\theta_i)] = \\mu(1-\\mu) - \\sigma^2$$\n\n\n\n\nFor a single unit,\n\n\n\n\n$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\nand\n\n\n\n\n$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$\n\n\n\n\nThere are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).\n\n\n\n\nThe first way is with moments (I can show the manipulations if needed):\n\n\n\n\n$$\\hat\\mu = \\frac{1}{n}\\sum_{i=1}^{n}\\hat p_i \\qquad \\text{estimates } \\mu$$\n\n\n\n\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^{n}(\\hat p_i - \\hat\\mu)^2 \\qquad \\text{estimates } \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\n$$\\widehat{\\operatorname{Var}}(\\hat\\mu) = \\frac{S^2}{n} \\qquad \\text{estimates } \\operatorname{Var}(\\hat\\mu)$$\n\n\n\n\nAnd the second way is using MLE (delta method for variances and log/exp constraint for optimization).\n\n\n\n\nHere is an R script that simulates data, and compares estimates, precision and coverage for both methods. I made it so that mean and variance can be specified in the simulation (instead of a and b from the Beta distribution) at different values of $n,k$ for some fixed true mean and variance. I discard MLE fits with invalid Hessians/variance and I specifically chose the case where there is a large true variance):\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = \"BFGS\",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, \"try-error\")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\n\n\n\n\nHere are the results:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/kEDelnub.png] (https://i.sstatic.net/kEDelnub.png)\n[image: enter image description here; source: https://i.sstatic.net/H3ywscwO.png] (https://i.sstatic.net/H3ywscwO.png)\n\n\n\n\nPrior to running this script, I would have thought that larger $n,k$ combinations would produce less bias, tighter variances and better coverage rates. But for the MLE, it looks like this is not true. And for both Moments and MLE, it seems that sometimes coverage can sometimes decrease as $n$ increases (jagged pattern).\n\n\n\n\nWhy is this happening?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677094", "selected_answer": {"answer_html": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.
\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.
fit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\nFull code:
\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf("[%2d/%2d] n = %3d, k = %d ... ", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf("done (%.1fs elapsed)\\n",\n as.numeric(difftime(Sys.time(), t0, units = "secs"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c("moments", "mle"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c("true_mean", "true_variance", "n", "k", "true_var_of_mean", \n "mean_estimate", "bias", "mc_se", "sd_estimate", \n "variance_estimate", "length_of_interval", "coverage")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == "moments")\ndf_mle <- subset(res_df, method == "mle")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = "n", y = y_label, color = "k") +\n theme_bw() +\n theme(legend.position = "bottom",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = "dashed", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, "bias", "Moments: bias of the estimated mean", \n "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np2 <- make_panel(df_mle, "bias", "MLE: bias of the estimated mean", \n "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np3 <- make_panel(df_mom, "sd_estimate", "Moments: SD of the estimated mean", \n "Spread of the estimate across studies.", "SD")\np4 <- make_panel(df_mle, "sd_estimate", "MLE: SD of the estimated mean", \n "Spread of the estimate across studies.", "SD")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = "dashed") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = "Coverage of the nominal 95% interval",\n subtitle = "Share of 1000 intervals containing the true mean. Dashed line at 0.95.",\n x = "n",\n y = "coverage",\n color = "method") +\n theme_bw() +\n theme(legend.position = "bottom",\n strip.background = element_rect(fill = "grey90"))\n\nprint(p_cov)\n\n", "answer_id": 677117, "answer_text": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.\n\n\n\n\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.\n\n\n\n\nfit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/yrEHvkk0.png] (https://i.sstatic.net/yrEHvkk0.png)\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/9nEiiFBK.png] (https://i.sstatic.net/9nEiiFBK.png)\n\n\n\n\nFull code:\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)", "answer_url": "https://stats.stackexchange.com/a/677117", "author": "jblood94", "author_url": "https://stats.stackexchange.com/users/214015/jblood94", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-09T13:02:57+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": 677094, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jblood94", "profile_url": "https://stats.stackexchange.com/users/214015/jblood94", "user_type": "registered"}, "created_at": "2026-09-09T13:02:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "09E52470-6B69-4568-A8B3-D52476EA341B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "20C3E36B-1564-462F-9257-5BBE5B9B70EF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}], "score": 3, "updated_at": "2026-09-09T13:02:57+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": 677117, "answers": [{"answer_html": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.
\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.
fit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\nFull code:
\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf("[%2d/%2d] n = %3d, k = %d ... ", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf("done (%.1fs elapsed)\\n",\n as.numeric(difftime(Sys.time(), t0, units = "secs"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c("moments", "mle"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c("true_mean", "true_variance", "n", "k", "true_var_of_mean", \n "mean_estimate", "bias", "mc_se", "sd_estimate", \n "variance_estimate", "length_of_interval", "coverage")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == "moments")\ndf_mle <- subset(res_df, method == "mle")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = "n", y = y_label, color = "k") +\n theme_bw() +\n theme(legend.position = "bottom",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = "dashed", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, "bias", "Moments: bias of the estimated mean", \n "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np2 <- make_panel(df_mle, "bias", "MLE: bias of the estimated mean", \n "Average estimate minus the truth. Dashed line at 0.", "bias", 0)\np3 <- make_panel(df_mom, "sd_estimate", "Moments: SD of the estimated mean", \n "Spread of the estimate across studies.", "SD")\np4 <- make_panel(df_mle, "sd_estimate", "MLE: SD of the estimated mean", \n "Spread of the estimate across studies.", "SD")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = "dashed") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = "Coverage of the nominal 95% interval",\n subtitle = "Share of 1000 intervals containing the true mean. Dashed line at 0.95.",\n x = "n",\n y = "coverage",\n color = "method") +\n theme_bw() +\n theme(legend.position = "bottom",\n strip.background = element_rect(fill = "grey90"))\n\nprint(p_cov)\n\n", "answer_id": 677117, "answer_text": "The suspicion expressed in the comments is well-founded: your MLE function tends to not arrive at the true MLE. Since it is performing a search, I would expect a good MLE function to use the moment estimators as the starting point. Using the function below, the behavior you observed disappears, as shown by the equivalent plots.\n\n\n\n\nMy fit_mle function is inspired by Rfast::betabinom.mle, adapted to handle edge cases.\n\n\n\n\nfit_mle <- function(x, k) {\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/yrEHvkk0.png] (https://i.sstatic.net/yrEHvkk0.png)\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/9nEiiFBK.png] (https://i.sstatic.net/9nEiiFBK.png)\n\n\n\n\nFull code:\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nfit_mle <- function(x, k) {\n xx <<- x\n kk <<- k\n m1 <- mean(x)\n \n if (k == 1 || all(x == 0) || all(x == k)) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n V <- NA\n } else {\n n <- length(x)\n z1 <- sort(unique(x))\n n1 <- tabulate(match(x, z1))\n z2 <- sort(unique(k - x))\n n2 <- tabulate(match(k - x, z2))\n m2 <- mean(x^2)\n d <- 1/(k*(m2/m1 - m1) - k + m1)\n a <- (k*m1 - m2)*d\n b <- (k - m1)*(k - m2/m1)*d\n \n if (!is.finite(a) || d < 0) {\n a <- max(m1*100/k, 1e-5)\n b <- max(100 - a, 1e-5)\n } else if (a <= 0 || b <= 0) {\n a <- max(m1*0.1/k, 1e-5)\n b <- max(0.1 - a, 1e-5)\n }\n \n for (i in 1:100) {\n ab <- a + b\n t1 <- digamma(ab) - digamma(k + ab)\n S1 <- a*(sum(digamma(z1 + a)*n1) + n*(t1 - digamma(a)))\n S2 <- b*(sum(digamma(z2 + b)*n2) + n*(t1 - digamma(b)))\n t2 <- trigamma(ab) - trigamma(k + ab)\n J11 <- a^2*(sum(trigamma(z1 + a)*n1) + n*(t2 - trigamma(a))) + S1\n J22 <- b^2*(sum(trigamma(z2 + b)*n2) + n*(t2 - trigamma(b))) + S2\n J12 <- a*b*t2*n\n if (abs(detJ <- J11*J22 - J12^2) < 1e-12) break\n step1 <- (J22*S1 - J12*S2)/detJ\n step2 <- (J11*S2 - J12*S1)/detJ\n if (abs(step1) + abs(step2) < 1e-8) break\n step_norm <- 2/sqrt(step1^2 + step2^2)\n \n if (step_norm < 1) {\n step1 <- step1*step_norm\n step2 <- step2*step_norm\n }\n \n a <- a*exp(-step1)\n b <- b*exp(-step2)\n }\n \n g <- a*b/(a + b)^2\n V <- -(J11 + J22 + 2*J12)*g^2/detJ\n }\n \n c(a/(a + b), if (is.finite(V) && V > 0 && V < 1 / (4 * n)) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\nt0 <- Sys.time()\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nlibrary(ggplot2)\nlibrary(patchwork)\n\nres_df <- as.data.frame(res, stringsAsFactors = FALSE)\nnum_cols <- c(\"true_mean\", \"true_variance\", \"n\", \"k\", \"true_var_of_mean\", \n \"mean_estimate\", \"bias\", \"mc_se\", \"sd_estimate\", \n \"variance_estimate\", \"length_of_interval\", \"coverage\")\nres_df[num_cols] <- lapply(res_df[num_cols], as.numeric)\nres_df$k_factor <- as.factor(res_df$k)\n\ndf_mom <- subset(res_df, method == \"moments\")\ndf_mle <- subset(res_df, method == \"mle\")\n\n# Helper function to generate the panels\nmake_panel <- function(data, metric_col, title, subtitle, y_label, hline = NULL) {\n p <- ggplot(data, aes(x = n, y = .data[[metric_col]], color = k_factor)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n labs(title = title, subtitle = subtitle, x = \"n\", y = y_label, color = \"k\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n plot.title = element_text(hjust = 0),\n plot.subtitle = element_text(hjust = 0))\n \n if (!is.null(hline)) {\n p <- p + geom_hline(yintercept = hline, linetype = \"dashed\", linewidth = 0.5)\n }\n return(p)\n}\n\np1 <- make_panel(df_mom, \"bias\", \"Moments: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np2 <- make_panel(df_mle, \"bias\", \"MLE: bias of the estimated mean\", \n \"Average estimate minus the truth. Dashed line at 0.\", \"bias\", 0)\np3 <- make_panel(df_mom, \"sd_estimate\", \"Moments: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\np4 <- make_panel(df_mle, \"sd_estimate\", \"MLE: SD of the estimated mean\", \n \"Spread of the estimate across studies.\", \"SD\")\n\n# Combine using patchwork\ncombined_grid <- (p1 + p2) / (p3 + p4)\nprint(combined_grid)\n\np_cov <- ggplot(res_df, aes(x = n, y = coverage, color = method)) +\n geom_line(linewidth = 0.5) +\n geom_point(size = 1.5) +\n geom_hline(yintercept = 0.95, linetype = \"dashed\") +\n facet_grid(~ k, labeller = label_both) +\n labs(title = \"Coverage of the nominal 95% interval\",\n subtitle = \"Share of 1000 intervals containing the true mean. Dashed line at 0.95.\",\n x = \"n\",\n y = \"coverage\",\n color = \"method\") +\n theme_bw() +\n theme(legend.position = \"bottom\",\n strip.background = element_rect(fill = \"grey90\"))\n\nprint(p_cov)", "answer_url": "https://stats.stackexchange.com/a/677117", "author": "jblood94", "author_url": "https://stats.stackexchange.com/users/214015/jblood94", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-09T13:02:57+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": 677094, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jblood94", "profile_url": "https://stats.stackexchange.com/users/214015/jblood94", "user_type": "registered"}, "created_at": "2026-09-09T13:02:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "09E52470-6B69-4568-A8B3-D52476EA341B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/09E52470-6B69-4568-A8B3-D52476EA341B/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "20C3E36B-1564-462F-9257-5BBE5B9B70EF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/20C3E36B-1564-462F-9257-5BBE5B9B70EF/view-source"}], "score": 3, "updated_at": "2026-09-09T13:02:57+00:00"}], "domain": "statistics", "external_links": ["https://i.sstatic.net/9nEiiFBK.png", "https://i.sstatic.net/H3ywscwO.png", "https://i.sstatic.net/kEDelnub.png", "https://i.sstatic.net/yrEHvkk0.png"], "medical_sensitive": false, "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": "adamkostanov", "question_author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "question_author_user_type": "registered", "question_created_at": "2026-09-07T06:07:31+00:00", "question_html": "Here is a beta-binomial model (treated like repeated measures - $i$ is an index for each individual, $n$ total individuals, and exactly $k$ measurements per individual):
\n$$\\theta_i \\stackrel{\\text{iid}}{\\sim} \\mathrm{Beta}(a,b), \\qquad x_i \\mid \\theta_i \\sim \\mathrm{Binomial}(k,\\theta_i), \\qquad \\hat p_i = \\frac{x_i}{k}, \\qquad i = 1,\\dots,n$$
\n$$\\mu = E[\\theta_i] = \\frac{a}{a+b}$$
\n$$\\sigma^2 = \\operatorname{Var}(\\theta_i) = \\frac{ab}{(a+b)^2(a+b+1)}$$
\n$$\\tau^2 = E[\\theta_i(1-\\theta_i)] = \\mu(1-\\mu) - \\sigma^2$$
\nFor a single unit,
\n$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$
\nand
\n$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$
\nThere are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).
\nThe first way is with moments (I can show the manipulations if needed):
\n$$\\hat\\mu = \\frac{1}{n}\\sum_{i=1}^{n}\\hat p_i \\qquad \\text{estimates } \\mu$$
\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^{n}(\\hat p_i - \\hat\\mu)^2 \\qquad \\text{estimates } \\sigma^2 + \\frac{\\tau^2}{k}$$
\n$$\\widehat{\\operatorname{Var}}(\\hat\\mu) = \\frac{S^2}{n} \\qquad \\text{estimates } \\operatorname{Var}(\\hat\\mu)$$
\nAnd the second way is using MLE (delta method for variances and log/exp constraint for optimization).
\nHere is an R script that simulates data, and compares estimates, precision and coverage for both methods. I made it so that mean and variance can be specified in the simulation (instead of a and b from the Beta distribution) at different values of $n,k$ for some fixed true mean and variance. I discard MLE fits with invalid Hessians/variance and I specifically chose the case where there is a large true variance):
\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = "BFGS",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, "try-error")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf("[%2d/%2d] n = %3d, k = %d ... ", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf("done (%.1fs elapsed)\\n",\n as.numeric(difftime(Sys.time(), t0, units = "secs"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c("moments", "mle"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\nHere are the results:
\n\nPrior to running this script, I would have thought that larger $n,k$ combinations would produce less bias, tighter variances and better coverage rates. But for the MLE, it looks like this is not true. And for both Moments and MLE, it seems that sometimes coverage can sometimes decrease as $n$ increases (jagged pattern).
\nWhy is this happening?
\n", "question_id": 677094, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "Here is a beta-binomial model (treated like repeated measures - $i$ is an index for each individual, $n$ total individuals, and exactly $k$ measurements per individual):\n\n\n\n\n$$\\theta_i \\stackrel{\\text{iid}}{\\sim} \\mathrm{Beta}(a,b), \\qquad x_i \\mid \\theta_i \\sim \\mathrm{Binomial}(k,\\theta_i), \\qquad \\hat p_i = \\frac{x_i}{k}, \\qquad i = 1,\\dots,n$$\n\n\n\n\n$$\\mu = E[\\theta_i] = \\frac{a}{a+b}$$\n\n\n\n\n$$\\sigma^2 = \\operatorname{Var}(\\theta_i) = \\frac{ab}{(a+b)^2(a+b+1)}$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i(1-\\theta_i)] = \\mu(1-\\mu) - \\sigma^2$$\n\n\n\n\nFor a single unit,\n\n\n\n\n$$E[\\hat p_i] = \\mu, \\qquad \\operatorname{Var}(\\hat p_i) = \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\nand\n\n\n\n\n$$\\operatorname{Var}(\\hat\\mu) = \\frac{1}{n}\\left(\\sigma^2 + \\frac{\\tau^2}{k}\\right)$$\n\n\n\n\nThere are two ways to estimate parameters I am interested in (I am interested in mean estimate and the variance of the mean estimate).\n\n\n\n\nThe first way is with moments (I can show the manipulations if needed):\n\n\n\n\n$$\\hat\\mu = \\frac{1}{n}\\sum_{i=1}^{n}\\hat p_i \\qquad \\text{estimates } \\mu$$\n\n\n\n\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^{n}(\\hat p_i - \\hat\\mu)^2 \\qquad \\text{estimates } \\sigma^2 + \\frac{\\tau^2}{k}$$\n\n\n\n\n$$\\widehat{\\operatorname{Var}}(\\hat\\mu) = \\frac{S^2}{n} \\qquad \\text{estimates } \\operatorname{Var}(\\hat\\mu)$$\n\n\n\n\nAnd the second way is using MLE (delta method for variances and log/exp constraint for optimization).\n\n\n\n\nHere is an R script that simulates data, and compares estimates, precision and coverage for both methods. I made it so that mean and variance can be specified in the simulation (instead of a and b from the Beta distribution) at different values of $n,k$ for some fixed true mean and variance. I discard MLE fits with invalid Hessians/variance and I specifically chose the case where there is a large true variance):\n\n\n\n\nlibrary(MASS)\n\nz <- qnorm(0.975)\n\n## Simulate \nmu_true <- 0.5\nv_true <- 0.249\nn_vals <- c(5, 10, 15, 20, 25, 50, 100, 200, 500,1000)\nk_vals <- c(1, 2, 3, 4, 5, 6,7,8,9)\nR <- 1000\n\n\nsim_data <- function(n, k, mu, v) {\n nu <- mu * (1 - mu) / v - 1\n rbinom(n, k, rbeta(n, mu * nu, (1 - mu) * nu))\n}\n\n## MLE \nbb_nll <- function(q, x, k)\n length(x) * lbeta(exp(q[1]), exp(q[2])) -\n sum(lbeta(exp(q[1]) + x, exp(q[2]) + k - x))\n\nfit_mle <- function(x, k) {\n n <- length(x)\n o <- try(optim(c(0, 0), bb_nll, x = x, k = k, method = \"BFGS\",\n hessian = TRUE), silent = TRUE)\n if (inherits(o, \"try-error\")) return(c(NA, NA))\n a <- exp(o$par[1]); b <- exp(o$par[2])\n g <- a * b / (a + b)^2 * c(1, -1)\n V <- try(drop(crossprod(g, ginv(o$hessian) %*% g)), silent = TRUE)\n ok <- !inherits(V, \"try-error\") && is.finite(V) && V > 0 &&\n V < 1 / (4 * n) && rcond(o$hessian) > 1e-10\n c(a / (a + b), if (ok) V else NA)\n}\n\n## Moments\nfit_mom <- function(x, k) {\n p <- x / k\n c(mean(p), var(p) / length(p))\n}\n\nscore <- function(m, V, mu) {\n s <- sqrt(V); ok <- is.finite(m)\n data.frame(mean_estimate = mean(m[ok]),\n bias = mean(m[ok]) - mu,\n mc_se = sd(m[ok]) / sqrt(sum(ok)),\n sd_estimate = sd(m[ok]),\n variance_estimate = mean(V, na.rm = TRUE),\n length_of_interval = mean(2 * z * s, na.rm = TRUE),\n coverage = mean(abs(m - mu) <= z * s, na.rm = TRUE))\n}\n\nrun_cell <- function(mu, v, n, k, R, i, tot, t0) {\n cat(sprintf(\"[%2d/%2d] n = %3d, k = %d ... \", i, tot, n, k))\n e <- replicate(R, { x <- sim_data(n, k, mu, v)\n rbind(fit_mom(x, k), fit_mle(x, k)) })\n cat(sprintf(\"done (%.1fs elapsed)\\n\",\n as.numeric(difftime(Sys.time(), t0, units = \"secs\"))))\n cbind(true_mean = mu, true_variance = v, n = n, k = k,\n true_var_of_mean = (v + (mu * (1 - mu) - v) / k) / n,\n method = c(\"moments\", \"mle\"),\n rbind(score(e[1, 1, ], e[1, 2, ], mu),\n score(e[2, 1, ], e[2, 2, ], mu)))\n}\n\n#Estimation\nset.seed(1)\ng <- expand.grid(n = n_vals, k = k_vals)\nres <- do.call(rbind, Map(run_cell, mu_true, v_true, g$n, g$k,\n MoreArgs = list(R = R), i = seq_len(nrow(g)),\n tot = nrow(g), t0 = t0))\n\n\n\n\n\nHere are the results:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/kEDelnub.png] (https://i.sstatic.net/kEDelnub.png)\n[image: enter image description here; source: https://i.sstatic.net/H3ywscwO.png] (https://i.sstatic.net/H3ywscwO.png)\n\n\n\n\nPrior to running this script, I would have thought that larger $n,k$ combinations would produce less bias, tighter variances and better coverage rates. But for the MLE, it looks like this is not true. And for both Moments and MLE, it seems that sometimes coverage can sometimes decrease as $n$ increases (jagged pattern).\n\n\n\n\nWhy is this happening?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:07:31+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "BE06C153-8C52-4CC0-883B-294D30B035A1", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/BE06C153-8C52-4CC0-883B-294D30B035A1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:17:50+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "E476317C-DD27-4C9B-AE2F-6BCDF9875E56", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/E476317C-DD27-4C9B-AE2F-6BCDF9875E56/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:25:11+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "30B3CCCA-ABFC-44BA-A8AA-62F762C98FC8", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/30B3CCCA-ABFC-44BA-A8AA-62F762C98FC8/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:33:19+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "2E412836-177B-410E-B0A8-2FD925F88199", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2E412836-177B-410E-B0A8-2FD925F88199/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T06:41:52+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "246BB9D4-0913-4A5D-BA26-19A883E71D2E", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/246BB9D4-0913-4A5D-BA26-19A883E71D2E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-07T08:45:32+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "06091D8C-4AF4-44C7-A257-DDB59EE43D39", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/06091D8C-4AF4-44C7-A257-DDB59EE43D39/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-09T06:13:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "4B6B337A-AB66-48A4-9852-835642560D4F", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/4B6B337A-AB66-48A4-9852-835642560D4F/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-09T06:13:57+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "FF6141BB-F0C5-4F25-80CC-121B75A68FE8", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/FF6141BB-F0C5-4F25-80CC-121B75A68FE8/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "398480DB-D18F-4C34-B57A-2901985CD8FF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/398480DB-D18F-4C34-B57A-2901985CD8FF/view-source"}, {"content_license": null, "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-16T13:07:32+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "E442CC1D-1B8D-4B82-A247-1B52D8C54699", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/E442CC1D-1B8D-4B82-A247-1B52D8C54699/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677094/can-coverage-probability-decrease-as-sample-size-increases", "split": "test", "split_group": "9708b014da60835c67095344e417c92716420d5056f8162fcbb5adcca7853c04", "tags": ["r", "maximum-likelihood"], "thread_id": "stats:677094", "title": "Can coverage probability decrease as sample size increases?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "modules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677095, "sha256": "1d618fa130fbed5952b989d4c334bd6f29b52043ec44b220abbe1a7348e72701", "source_url": "https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult"}], "other_answers": [], "product": "code_qa", "question": "I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.\n\n\n\n\nI have individual student data, but some aggregated dummy data would be:\n\n\n\n\nmodules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n\n\n\n\n\nAnd the questions I would like to ask are\n\n\n\n\n\nIs the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?\n\n\n\n\nIs the proportion of students who get an F grade in FR202 the same as the proportion of students who get an F grade in other xx200 level courses?\n\n\n\n\n\nI did some reading and from Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science (https://moderndive.com/8-confidence-intervals.html) started out by calculating bootstrap confidence intervals around the proportion of A/F grades awarded in each course, and seeing if these overlapped with the proportion of A/F grades awarded for other courses (e.g. all other MA courses, all other xx200 courses).\n\n\n\n\nHowever, having dug a bit further (e.g. Bootstrapping a Proportion - Probably Overthinking It, (https://www.allendowney.com/blog/2024/10/15/bootstrapping-a-proportion/) Bootstrap intervals for the single proportion – corp.ling.stats (https://corplingstats.wordpress.com/2024/12/12/bootstrap-intervals/)) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.\n\n\n\n\nBefore I go down the wrong path again, I’d love a sense check from some more experienced hands.\n\n\n\n\n\nAre Wilson intervals the right approach for these sorts of questions?\n\n\n\n\nGiven that I sometimes have small numbers (<30 students on a course) and rare outcomes (F grades are not common!) I think I should use a continuity correction (Correcting for continuity – corp.ling.stats (https://corplingstats.wordpress.com/2019/04/27/correcting-for-continuity/)), is that right?\n\n\n\n\nAny pointers on how to adjust for multiple comparisons, given that I’ll be calculating two CIs each (prop A and prop F) for multiple courses (e.g. each of 7 MA courses against the other 6 MA courses)?\n\n\n\n\n\nI have some formal stats training, but not done much that isn't regression for a while. I understand I could run a regression of prop A/prop F with module dummy variables, but I'd like to try branching out to some other skills, where appropriate.\n\n\n\n\nThank you.", "record_id": "Scientific-Code-and-Analysis-QA:stats:677095", "selected_answer": {"answer_html": "Welcome to CV!
\nSo you want to compare 2 proportions; e.g. “Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?”.
\nWell, the “canonical” way to compare 2 proportions is via a 2x2 contingency table (aka crosstab). And the “canonical” tests are either a chi-square test, or a Fisher-exact test (aka Fisher-0Irwin test).
\nNow, using binomial CI’s will not really answer your 2 questions, unless the answer is obvious” if the 2 CI’s do not overlap, you have a significant difference. And if they overlap to a large extent, you do not have a significant difference. But in between, you can not simply eyeball the CI’s.
\nNow, given that you are dealing with (very?) low proportions or counts (how many F’s in a given class? Maybe 2-3?), the chi-square test is not recommended (it is based on a normal approximation, which is not warranted for such low proportions/counts). Nor for that matter are CI’s based on normal approximations, a group the Wilson CI belongs to. And forget about continuity corrections, they do not work properly with very small proportions.
\nSo you are left with the Fisher-exact test, or some newer versions of it (which are less “conservative, while remaining “exact”, that is based on exactly the binomial distribution), such as the Blaker test.
But there is a subtlety in what you are trying to compare. On one hand, you have the proportion of A’s in one class: easy. On the other hand you have the proportion of A’s in all other MA courses (the scenario is the same for the other question, so I will only address the first). How do you express that 2nd proportion?
\nOne option is to simply take the count of all A grades in all other MA courses, and the count of all students enrolled in all other MA classes. And then you can/should indeed use a Fisher-exact (or a Blaker-exact) test. But this will weight each student equally, but not each class (the classes with a large enrollment are more heavily weighted than the classes with a low enrollment). That may be what you want (as it reflects the experience of all students enrolled in all other MA classes), but it may not.\nAn alternative would be to look at all the proportions in all other MA classes, and take the average of these proportions. This weights all classes equally (but not all students). In that case, your test can be done with a single CI. You compute an binomial CI (again using an exact method given your possibly low proportions/counts), and simply see if the average proportion in included in that CI. If it is not, you have established a significant difference (at what ever significance level you chose for the CI).
Last, you ask about multiple comparisons. The fact that you compute multiple CI’s is not relevant; multiple comparisons only occur when you are making a comparison to a significance level (or checking if a CI contains 0, or 1).. And since you seem to only have 2 questions, then you are only making 2 comparisons.
\nThe cautious thing to do would be to use a multiple comparison correction (MCC). Given only 2 comparisons, just use Bonferroni, and halve your significance level.
\nBut bolder statisticians could argue that your 2 hypotheses are different, and independent. And therefore, a MCC is not warranted... (should a researcher correct for all the various hypotheses he/she will test in their career?). So depending on your ultimate goal (why only these 2 questions? what are you really trying to show), you may be able to dispense with a MCC.
Welcome to CV!
\nSo you want to compare 2 proportions; e.g. “Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?”.
\nWell, the “canonical” way to compare 2 proportions is via a 2x2 contingency table (aka crosstab). And the “canonical” tests are either a chi-square test, or a Fisher-exact test (aka Fisher-0Irwin test).
\nNow, using binomial CI’s will not really answer your 2 questions, unless the answer is obvious” if the 2 CI’s do not overlap, you have a significant difference. And if they overlap to a large extent, you do not have a significant difference. But in between, you can not simply eyeball the CI’s.
\nNow, given that you are dealing with (very?) low proportions or counts (how many F’s in a given class? Maybe 2-3?), the chi-square test is not recommended (it is based on a normal approximation, which is not warranted for such low proportions/counts). Nor for that matter are CI’s based on normal approximations, a group the Wilson CI belongs to. And forget about continuity corrections, they do not work properly with very small proportions.
\nSo you are left with the Fisher-exact test, or some newer versions of it (which are less “conservative, while remaining “exact”, that is based on exactly the binomial distribution), such as the Blaker test.
But there is a subtlety in what you are trying to compare. On one hand, you have the proportion of A’s in one class: easy. On the other hand you have the proportion of A’s in all other MA courses (the scenario is the same for the other question, so I will only address the first). How do you express that 2nd proportion?
\nOne option is to simply take the count of all A grades in all other MA courses, and the count of all students enrolled in all other MA classes. And then you can/should indeed use a Fisher-exact (or a Blaker-exact) test. But this will weight each student equally, but not each class (the classes with a large enrollment are more heavily weighted than the classes with a low enrollment). That may be what you want (as it reflects the experience of all students enrolled in all other MA classes), but it may not.\nAn alternative would be to look at all the proportions in all other MA classes, and take the average of these proportions. This weights all classes equally (but not all students). In that case, your test can be done with a single CI. You compute an binomial CI (again using an exact method given your possibly low proportions/counts), and simply see if the average proportion in included in that CI. If it is not, you have established a significant difference (at what ever significance level you chose for the CI).
Last, you ask about multiple comparisons. The fact that you compute multiple CI’s is not relevant; multiple comparisons only occur when you are making a comparison to a significance level (or checking if a CI contains 0, or 1).. And since you seem to only have 2 questions, then you are only making 2 comparisons.
\nThe cautious thing to do would be to use a multiple comparison correction (MCC). Given only 2 comparisons, just use Bonferroni, and halve your significance level.
\nBut bolder statisticians could argue that your 2 hypotheses are different, and independent. And therefore, a MCC is not warranted... (should a researcher correct for all the various hypotheses he/she will test in their career?). So depending on your ultimate goal (why only these 2 questions? what are you really trying to show), you may be able to dispense with a MCC.
I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.
\nI have individual student data, but some aggregated dummy data would be:
\nmodules <- c(\n "MA101","MA102","MA103","MA201","MA202","MA301","MA302",\n "FR101","FR102","FR104","FR201","FR202","FR203","FR301",\n "EN101","EN102","EN201","EN202","EN203","EN301","EN302"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n\nAnd the questions I would like to ask are
\nI did some reading and from Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science started out by calculating bootstrap confidence intervals around the proportion of A/F grades awarded in each course, and seeing if these overlapped with the proportion of A/F grades awarded for other courses (e.g. all other MA courses, all other xx200 courses).
\nHowever, having dug a bit further (e.g. Bootstrapping a Proportion - Probably Overthinking It, Bootstrap intervals for the single proportion – corp.ling.stats) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.
\nBefore I go down the wrong path again, I’d love a sense check from some more experienced hands.
\nI have some formal stats training, but not done much that isn't regression for a while. I understand I could run a regression of prop A/prop F with module dummy variables, but I'd like to try branching out to some other skills, where appropriate.
\nThank you.
\n", "question_id": 677095, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.\n\n\n\n\nI have individual student data, but some aggregated dummy data would be:\n\n\n\n\nmodules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(modules), replace = TRUE)\ngrade_counts <- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) <- LETTERS[1:5]\n\ndummy_data <- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n\n\n\n\n\nAnd the questions I would like to ask are\n\n\n\n\n\nIs the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?\n\n\n\n\nIs the proportion of students who get an F grade in FR202 the same as the proportion of students who get an F grade in other xx200 level courses?\n\n\n\n\n\nI did some reading and from Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science (https://moderndive.com/8-confidence-intervals.html) started out by calculating bootstrap confidence intervals around the proportion of A/F grades awarded in each course, and seeing if these overlapped with the proportion of A/F grades awarded for other courses (e.g. all other MA courses, all other xx200 courses).\n\n\n\n\nHowever, having dug a bit further (e.g. Bootstrapping a Proportion - Probably Overthinking It, (https://www.allendowney.com/blog/2024/10/15/bootstrapping-a-proportion/) Bootstrap intervals for the single proportion – corp.ling.stats (https://corplingstats.wordpress.com/2024/12/12/bootstrap-intervals/)) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.\n\n\n\n\nBefore I go down the wrong path again, I’d love a sense check from some more experienced hands.\n\n\n\n\n\nAre Wilson intervals the right approach for these sorts of questions?\n\n\n\n\nGiven that I sometimes have small numbers (<30 students on a course) and rare outcomes (F grades are not common!) I think I should use a continuity correction (Correcting for continuity – corp.ling.stats (https://corplingstats.wordpress.com/2019/04/27/correcting-for-continuity/)), is that right?\n\n\n\n\nAny pointers on how to adjust for multiple comparisons, given that I’ll be calculating two CIs each (prop A and prop F) for multiple courses (e.g. each of 7 MA courses against the other 6 MA courses)?\n\n\n\n\n\nI have some formal stats training, but not done much that isn't regression for a while. I understand I could run a regression of prop A/prop F with module dummy variables, but I'd like to try branching out to some other skills, where appropriate.\n\n\n\n\nThank you.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "LST", "profile_url": "https://stats.stackexchange.com/users/516373/lst", "user_type": "registered"}, "created_at": "2026-09-07T16:47:08+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "77370A41-A452-40D5-9FE9-E2D1C2A53F6B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/77370A41-A452-40D5-9FE9-E2D1C2A53F6B/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult", "split": "train", "split_group": "539d92a20e4941595f8fd87a1112f78fb0bb6db32af014f84a6cccc0e55d9727", "tags": ["confidence-interval", "proportion"], "thread_id": "stats:677095", "title": "Testing differences in proportions - Wilson CIs, continuity corrections and multiple comparisons"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "library(lme4)\n\nmodel <- lmer(log(sd_depth) ~ Grazing * Country + (1|PlotID), data = sd_data)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677129, "sha256": "2709c370d4eb7a49f17b14941e5fe040beff65d0a68e6bd750cb444b39496f9e", "source_url": "https://stats.stackexchange.com/questions/677129/what-mixed-model-do-i-need-to-use-for-my-analysis"}], "other_answers": [], "product": "code_qa", "question": "I have been working on analysing ecological data for different countries (within each country there are two groups (grazed/ungrazed) and plots (5 per group) which contain subplots (pseudoreplicates)\n\n\n\n\nMy sample size: 9 countries with each 2 groups of 5 plots with 4 subplots, so 20 measurepoints per group, 40 measure points per country\n\n\n\n\nI want to know what the effect of grazers are for each measurement at each study site (country). And have decided to go for a mixed model, since I have pseudoreplicates to account for.\n\n\n\n\nI started with a Linear Mixed Model, but the residuals were not normally distributed. I have now log transformed my data.\n\n\n\n\nlibrary(lme4)\n\nmodel <- lmer(log(sd_depth) ~ Grazing * Country + (1|PlotID), data = sd_data)\n\n\n\n\n\nI made a qqnorm plot for the residuals and it looked a lot better, but the shapiro.test gave a p-value of 0.01.\n\n\n\n\nsd_depth = standard deviation values (I calculated soil depth for 50 steps, each step a separate measurement, and calculated the standard deviation per subplot of these measurements).\n\n\n\n\nMy question is:\n\n\n\n\n\nIs that p-value enough to fit the Linear mixed model anyway?\n\n\n\n\nDo I need to use another model, for example GLMM? Which distribution do I need to choose then? And do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)\n\n\n\n\nWhat are the considerations for choosing families for distribution models (because I have other data that I need to analyse in a similar way), tips for websites/articles that explain this in a clear way are welcome too!", "record_id": "Scientific-Code-and-Analysis-QA:stats:677129", "selected_answer": {"answer_html": "Putting together the comments:
\n\n\nIs that p-value enough to fit the Linear mixed model anyway?
\n
Don't rely on such p-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get "statistically significant" deviations from the hypothesized distribution that don't matter in practice. With small data sets, you typically don't have the power to find substantial deviations that pass the "statistical significance" criterion. See this page.
\nFurthermore, there's a strong argument that the whole process of checking distributions of errors from a model and then changing the model is inappropriate if you want to do inference based on the results. The p-values you get from a model rely on the assumption that you didn't use the outcomes to choose the model. That two-step process necessarily uses the outcomes.
\n\n\nDo I need to use another model, for example GLMM? ...
\n
Standard linear regression assumes a single normal distribution of errors around model predictions. If the nature of your outcome variable suggests that isn't a reasonable assumption, a generalized linear model is more appropriate.
\nIf your outcome is a standard deviation (your choice of the outcome of variability measure) or variance (as @Roland suggests), the values are necessarily non-negative. If you are sampling from normal distributions, variance estimates have chi-square distributions, while the standard deviation estimates have chi distributions. Chi-square distributions may approach normal distributions, but your number of samples per (sub)plot might not be adequate for a normal approximation to the distribution of variance estimates. Furthermore, your measurements of soil depth might not have normally distributed errors.
\n\n\nWhich distribution do I need to choose then? ... What are the considerations for choosing families for distribution models...?
\n
The type of outcome variable helps determine the choice. What's critical is the nature of the random variability around the mean values the model predicts from the covariates. This answer succinctly summarizes major possibilities.
\nAs a variance or standard deviation is continuous and non-negative, the gamma family would be one standard choice. The choice of family has to be accompanied by a choice of link function; a log link* is often used with a gamma model. The gamma family is directly relevant in your case, as the chi-square distribution is a special case of the gamma family.
\n\n\nAnd do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)
\n
Checking model fit for generalized linear mixed models isn't as simple as for standard linear regression. As @RickHass noted, the R DHARMa package provides useful tools for that, based on simulations from the model and the observed data.
*There's an important difference between using a log link in a GL(M)M and the log transformation of outcomes that you used. That GLM models the log of the mean outcome value as a function of covariates. A log transformation followed by linear regression models the mean of the log of the outcome values. If you know that your variance values come from samples of normal distributions, you could use a Gamma family with the identity link.
\n", "answer_id": 677144, "answer_text": "Putting together the comments:\n\n\n\n\n\n\n\nIs that p-value enough to fit the Linear mixed model anyway?\n\n\n\n\n\n\n\nDon't rely on such p-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get \"statistically significant\" deviations from the hypothesized distribution that don't matter in practice. With small data sets, you typically don't have the power to find substantial deviations that pass the \"statistical significance\" criterion. See this page (https://stats.stackexchange.com/q/2492/28500).\n\n\n\n\nFurthermore, there's a strong argument that the whole process of checking distributions of errors from a model and then changing the model is inappropriate if you want to do inference based on the results. The p-values you get from a model rely on the assumption that you didn't use the outcomes to choose the model. That two-step process necessarily uses the outcomes.\n\n\n\n\n\n\n\nDo I need to use another model, for example GLMM? ...\n\n\n\n\n\n\n\nStandard linear regression assumes a single normal distribution of errors around model predictions. If the nature of your outcome variable suggests that isn't a reasonable assumption, a generalized linear model is more appropriate.\n\n\n\n\nIf your outcome is a standard deviation (your choice of the outcome of variability measure) or variance (as @Roland suggests), the values are necessarily non-negative. If you are sampling from normal distributions, variance estimates have chi-square distributions (https://en.wikipedia.org/wiki/Chi-squared_distribution#Occurrence_and_applications), while the standard deviation estimates have chi distributions (https://en.wikipedia.org/wiki/Chi_distribution#). Chi-square distributions may approach normal distributions, but your number of samples per (sub)plot might not be adequate for a normal approximation (https://en.wikipedia.org/wiki/Chi-squared_distribution#Asymptotic_properties) to the distribution of variance estimates. Furthermore, your measurements of soil depth might not have normally distributed errors.\n\n\n\n\n\n\n\nWhich distribution do I need to choose then? ... What are the considerations for choosing families for distribution models...?\n\n\n\n\n\n\n\nThe type of outcome variable helps determine the choice. What's critical is the nature of the random variability around the mean values the model predicts from the covariates. This answer (https://stats.stackexchange.com/a/303592/28500) succinctly summarizes major possibilities.\n\n\n\n\nAs a variance or standard deviation is continuous and non-negative, the gamma family would be one standard choice. The choice of family has to be accompanied by a choice of link function; a log link* is often used with a gamma model. The gamma family is directly relevant in your case, as the chi-square distribution is a special case of the gamma family (https://en.wikipedia.org/wiki/Gamma_distribution#General).\n\n\n\n\n\n\n\nAnd do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)\n\n\n\n\n\n\n\nChecking model fit for generalized linear mixed models isn't as simple as for standard linear regression. As @RickHass noted, the R DHARMa package (https://cran.r-project.org/package=DHARMa) provides useful tools for that, based on simulations from the model and the observed data.\n\n\n\n\n\n\n\n*There's an important difference between using a log link in a GL(M)M and the log transformation of outcomes that you used. That GLM models the log of the mean outcome value as a function of covariates. A log transformation followed by linear regression models the mean of the log of the outcome values. If you know that your variance values come from samples of normal distributions, you could use a Gamma family with the identity link.", "answer_url": "https://stats.stackexchange.com/a/677144", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T15:41:29+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": 677129, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T15:41:29+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "75DAD87A-C4FD-4864-A9E0-3DDADD861A78", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/75DAD87A-C4FD-4864-A9E0-3DDADD861A78/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T16:40:36+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "9AD56685-4998-4F06-A9D3-E7CA7A2C653C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9AD56685-4998-4F06-A9D3-E7CA7A2C653C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T17:27:30+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "1778ADB3-A83B-49CF-BDE1-AD32AC57C294", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1778ADB3-A83B-49CF-BDE1-AD32AC57C294/view-source"}], "score": 2, "updated_at": "2026-09-11T17:27:30+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Putting together the comments:
\n\n\nIs that p-value enough to fit the Linear mixed model anyway?
\n
Don't rely on such p-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get "statistically significant" deviations from the hypothesized distribution that don't matter in practice. With small data sets, you typically don't have the power to find substantial deviations that pass the "statistical significance" criterion. See this page.
\nFurthermore, there's a strong argument that the whole process of checking distributions of errors from a model and then changing the model is inappropriate if you want to do inference based on the results. The p-values you get from a model rely on the assumption that you didn't use the outcomes to choose the model. That two-step process necessarily uses the outcomes.
\n\n\nDo I need to use another model, for example GLMM? ...
\n
Standard linear regression assumes a single normal distribution of errors around model predictions. If the nature of your outcome variable suggests that isn't a reasonable assumption, a generalized linear model is more appropriate.
\nIf your outcome is a standard deviation (your choice of the outcome of variability measure) or variance (as @Roland suggests), the values are necessarily non-negative. If you are sampling from normal distributions, variance estimates have chi-square distributions, while the standard deviation estimates have chi distributions. Chi-square distributions may approach normal distributions, but your number of samples per (sub)plot might not be adequate for a normal approximation to the distribution of variance estimates. Furthermore, your measurements of soil depth might not have normally distributed errors.
\n\n\nWhich distribution do I need to choose then? ... What are the considerations for choosing families for distribution models...?
\n
The type of outcome variable helps determine the choice. What's critical is the nature of the random variability around the mean values the model predicts from the covariates. This answer succinctly summarizes major possibilities.
\nAs a variance or standard deviation is continuous and non-negative, the gamma family would be one standard choice. The choice of family has to be accompanied by a choice of link function; a log link* is often used with a gamma model. The gamma family is directly relevant in your case, as the chi-square distribution is a special case of the gamma family.
\n\n\nAnd do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)
\n
Checking model fit for generalized linear mixed models isn't as simple as for standard linear regression. As @RickHass noted, the R DHARMa package provides useful tools for that, based on simulations from the model and the observed data.
*There's an important difference between using a log link in a GL(M)M and the log transformation of outcomes that you used. That GLM models the log of the mean outcome value as a function of covariates. A log transformation followed by linear regression models the mean of the log of the outcome values. If you know that your variance values come from samples of normal distributions, you could use a Gamma family with the identity link.
\n", "answer_id": 677144, "answer_text": "Putting together the comments:\n\n\n\n\n\n\n\nIs that p-value enough to fit the Linear mixed model anyway?\n\n\n\n\n\n\n\nDon't rely on such p-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get \"statistically significant\" deviations from the hypothesized distribution that don't matter in practice. With small data sets, you typically don't have the power to find substantial deviations that pass the \"statistical significance\" criterion. See this page (https://stats.stackexchange.com/q/2492/28500).\n\n\n\n\nFurthermore, there's a strong argument that the whole process of checking distributions of errors from a model and then changing the model is inappropriate if you want to do inference based on the results. The p-values you get from a model rely on the assumption that you didn't use the outcomes to choose the model. That two-step process necessarily uses the outcomes.\n\n\n\n\n\n\n\nDo I need to use another model, for example GLMM? ...\n\n\n\n\n\n\n\nStandard linear regression assumes a single normal distribution of errors around model predictions. If the nature of your outcome variable suggests that isn't a reasonable assumption, a generalized linear model is more appropriate.\n\n\n\n\nIf your outcome is a standard deviation (your choice of the outcome of variability measure) or variance (as @Roland suggests), the values are necessarily non-negative. If you are sampling from normal distributions, variance estimates have chi-square distributions (https://en.wikipedia.org/wiki/Chi-squared_distribution#Occurrence_and_applications), while the standard deviation estimates have chi distributions (https://en.wikipedia.org/wiki/Chi_distribution#). Chi-square distributions may approach normal distributions, but your number of samples per (sub)plot might not be adequate for a normal approximation (https://en.wikipedia.org/wiki/Chi-squared_distribution#Asymptotic_properties) to the distribution of variance estimates. Furthermore, your measurements of soil depth might not have normally distributed errors.\n\n\n\n\n\n\n\nWhich distribution do I need to choose then? ... What are the considerations for choosing families for distribution models...?\n\n\n\n\n\n\n\nThe type of outcome variable helps determine the choice. What's critical is the nature of the random variability around the mean values the model predicts from the covariates. This answer (https://stats.stackexchange.com/a/303592/28500) succinctly summarizes major possibilities.\n\n\n\n\nAs a variance or standard deviation is continuous and non-negative, the gamma family would be one standard choice. The choice of family has to be accompanied by a choice of link function; a log link* is often used with a gamma model. The gamma family is directly relevant in your case, as the chi-square distribution is a special case of the gamma family (https://en.wikipedia.org/wiki/Gamma_distribution#General).\n\n\n\n\n\n\n\nAnd do I need to check for any other assumptions if I go for GLMM (or any other mixed effect model?)\n\n\n\n\n\n\n\nChecking model fit for generalized linear mixed models isn't as simple as for standard linear regression. As @RickHass noted, the R DHARMa package (https://cran.r-project.org/package=DHARMa) provides useful tools for that, based on simulations from the model and the observed data.\n\n\n\n\n\n\n\n*There's an important difference between using a log link in a GL(M)M and the log transformation of outcomes that you used. That GLM models the log of the mean outcome value as a function of covariates. A log transformation followed by linear regression models the mean of the log of the outcome values. If you know that your variance values come from samples of normal distributions, you could use a Gamma family with the identity link.", "answer_url": "https://stats.stackexchange.com/a/677144", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T15:41:29+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": 677129, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T15:41:29+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "75DAD87A-C4FD-4864-A9E0-3DDADD861A78", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/75DAD87A-C4FD-4864-A9E0-3DDADD861A78/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T16:40:36+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "9AD56685-4998-4F06-A9D3-E7CA7A2C653C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/9AD56685-4998-4F06-A9D3-E7CA7A2C653C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-11T17:27:30+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "1778ADB3-A83B-49CF-BDE1-AD32AC57C294", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1778ADB3-A83B-49CF-BDE1-AD32AC57C294/view-source"}], "score": 2, "updated_at": "2026-09-11T17:27:30+00:00"}], "domain": "statistics", "external_links": ["https://cran.r-project.org/package=DHARMa", "https://en.wikipedia.org/wiki/Chi-squared_distribution#Asymptotic_properties", "https://en.wikipedia.org/wiki/Chi-squared_distribution#Occurrence_and_applications", "https://en.wikipedia.org/wiki/Chi_distribution#", "https://en.wikipedia.org/wiki/Gamma_distribution#General"], "medical_sensitive": false, "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": "S.E123", "question_author_url": "https://stats.stackexchange.com/users/516500/s-e123", "question_author_user_type": "unregistered", "question_created_at": "2026-09-10T14:34:54+00:00", "question_html": "I have been working on analysing ecological data for different countries (within each country there are two groups (grazed/ungrazed) and plots (5 per group) which contain subplots (pseudoreplicates)
\nMy sample size: 9 countries with each 2 groups of 5 plots with 4 subplots, so 20 measurepoints per group, 40 measure points per country
\nI want to know what the effect of grazers are for each measurement at each study site (country). And have decided to go for a mixed model, since I have pseudoreplicates to account for.
\nI started with a Linear Mixed Model, but the residuals were not normally distributed. I have now log transformed my data.
\nlibrary(lme4)\n\nmodel <- lmer(log(sd_depth) ~ Grazing * Country + (1|PlotID), data = sd_data)\n\nI made a qqnorm plot for the residuals and it looked a lot better, but the shapiro.test gave a p-value of 0.01.
\nsd_depth = standard deviation values (I calculated soil depth for 50 steps, each step a separate measurement, and calculated the standard deviation per subplot of these measurements).
\nMy question is:
\nYou are using R version 4.6.1. Well, since R 4.6.0, from R News:
\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.
\n
Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:
\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.
\n
[...]
\n\n\n", "answer_id": 677139, "answer_text": "You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).", "answer_url": "https://stats.stackexchange.com/a/677139", "author": "J-J-J", "author_url": "https://stats.stackexchange.com/users/164936/j-j-j", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T07:32:22+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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T07:32:22+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "23216BD3-49D3-422F-8020-02B7D9CD2B5A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T08:09:51+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "CB4779A0-4EA1-4BB0-99F8-7FFB266F646D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}], "score": 16, "updated_at": "2026-09-11T08:09:51+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677135, "sha256": "d5c814c461b4b9343809a17c4edd3fbbe1bc940093edcb02ae766c0fbd63e802", "source_url": "https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test"}, {"block_index": 1, "code_text": "\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677135, "sha256": "62c4ef27f6977021d1af60c7700550f89ea035d044d29b3bff4641ab21fc10e6", "source_url": "https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test"}, {"block_index": 0, "code_text": "df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677136, "sha256": "496b05ec45239bb68abbf4de00ba9a79c421d6cd74f3703e914e45742d127983", "source_url": "https://stats.stackexchange.com/a/677136"}, {"block_index": 1, "code_text": "(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677136, "sha256": "3b004d026d68a8f11c9c562e695ca7fb83bb343024bf0b626d348d5f77c4bb42", "source_url": "https://stats.stackexchange.com/a/677136"}], "other_answers": [{"answer_html": "Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.
\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.
\n
Can you provide a {reprex}? I'm getting a warning when I run your code
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\nCreated on 2026-09-10 with reprex v2.1.1
\nEDIT: I was using an old version of R. Here is the reprex from using 4.6
\n(R.version.string)\n#> [1] "R version 4.6.0 (2026-04-24)"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nCreated on 2026-09-11 with reprex v2.1.1
\nNote, no warning. See J-J-J's comment for an explanation.
\n", "answer_id": 677136, "answer_text": "Can you provide a {reprex} (https://reprex.tidyverse.org/)? I'm getting a warning when I run your code\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\n\n\n\n\nCreated on 2026-09-10 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nEDIT: I was using an old version of R. Here is the reprex from using 4.6\n\n\n\n\n(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\n\n\n\n\nCreated on 2026-09-11 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nNote, no warning. See J-J-J's comment for an explanation.", "answer_url": "https://stats.stackexchange.com/a/677136", "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-11T01:34:59+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": 677135, "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-11T01:34:59+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "3461E410-C604-4E94-BBD3-042259374DDF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3461E410-C604-4E94-BBD3-042259374DDF/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-11T17:41:38+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "C692081B-A074-4F0B-985E-9AECEBE88DE5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C692081B-A074-4F0B-985E-9AECEBE88DE5/view-source"}], "score": 5, "updated_at": "2026-09-11T17:41:38+00:00"}, {"answer_html": "This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.
\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.
\n\nHere we range from evident to speculative:
\nInteger scores, so ties are more likely than otherwise.
\nIs there an upper limit of 32?
\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.
\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?
\n", "answer_id": 677141, "answer_text": "This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.\n\n\n\n\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/7o9W87he.png] (https://i.sstatic.net/7o9W87he.png)\n\n\n\n\nHere we range from evident to speculative:\n\n\n\n\n\n\n\nInteger scores, so ties are more likely than otherwise.\n\n\n\n\n\n\n\n\n\nIs there an upper limit of 32?\n\n\n\n\n\n\n\n\n\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.\n\n\n\n\n\n\n\n\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?", "answer_url": "https://stats.stackexchange.com/a/677141", "author": "Nick Cox", "author_url": "https://stats.stackexchange.com/users/22047/nick-cox", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T08:47:46+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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-11T08:47:46+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "F5E781A6-F63A-4F3B-897E-03303213674F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F5E781A6-F63A-4F3B-897E-03303213674F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-11T09:20:25+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "2F24FDA3-AB03-426F-84C2-A097A0D37730", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2F24FDA3-AB03-426F-84C2-A097A0D37730/view-source"}], "score": 7, "updated_at": "2026-09-11T09:20:25+00:00"}], "product": "code_qa", "question": "I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n\n\n\n\n\nAs there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?\n\n\n\n\nHere is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.\n\n\n\n\n\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```", "record_id": "Scientific-Code-and-Analysis-QA:stats:677135", "selected_answer": {"answer_html": "You are using R version 4.6.1. Well, since R 4.6.0, from R News:
\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.
\n
Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:
\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.
\n
[...]
\n\n\n", "answer_id": 677139, "answer_text": "You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).", "answer_url": "https://stats.stackexchange.com/a/677139", "author": "J-J-J", "author_url": "https://stats.stackexchange.com/users/164936/j-j-j", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T07:32:22+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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T07:32:22+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "23216BD3-49D3-422F-8020-02B7D9CD2B5A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T08:09:51+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "CB4779A0-4EA1-4BB0-99F8-7FFB266F646D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}], "score": 16, "updated_at": "2026-09-11T08:09:51+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677139, "answers": [{"answer_html": "Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.
\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.
\n
Can you provide a {reprex}? I'm getting a warning when I run your code
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\nCreated on 2026-09-10 with reprex v2.1.1
\nEDIT: I was using an old version of R. Here is the reprex from using 4.6
\n(R.version.string)\n#> [1] "R version 4.6.0 (2026-04-24)"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n "tbl", "data.frame"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nCreated on 2026-09-11 with reprex v2.1.1
\nNote, no warning. See J-J-J's comment for an explanation.
\n", "answer_id": 677136, "answer_text": "Can you provide a {reprex} (https://reprex.tidyverse.org/)? I'm getting a warning when I run your code\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with ties\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact p-value with zeroes\n#> Warning in wilcox.test.default(df$PostScore, df$PreScore, conf.int = TRUE, :\n#> cannot compute exact confidence interval with zeroes\n#> \n#> Wilcoxon signed rank test with continuity correction\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 77, p-value = 0.00324\n#> alternative hypothesis: true location shift is not equal to 0\n#> 95 percent confidence interval:\n#> 4.500064 9.499992\n#> sample estimates:\n#> (pseudo)median \n#> 7.000049\n\n\n\n\n\nCreated on 2026-09-10 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nEDIT: I was using an old version of R. Here is the reprex from using 4.6\n\n\n\n\n(R.version.string)\n#> [1] \"R version 4.6.0 (2026-04-24)\"\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n 26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n 30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n \"tbl\", \"data.frame\"))\n\nwilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: df$PostScore and df$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\n\n\n\n\nCreated on 2026-09-11 with reprex v2.1.1 (https://reprex.tidyverse.org)\n\n\n\n\nNote, no warning. See J-J-J's comment for an explanation.", "answer_url": "https://stats.stackexchange.com/a/677136", "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-11T01:34:59+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": 677135, "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-11T01:34:59+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "3461E410-C604-4E94-BBD3-042259374DDF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3461E410-C604-4E94-BBD3-042259374DDF/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-11T17:41:38+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "C692081B-A074-4F0B-985E-9AECEBE88DE5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C692081B-A074-4F0B-985E-9AECEBE88DE5/view-source"}], "score": 5, "updated_at": "2026-09-11T17:41:38+00:00"}, {"answer_html": "You are using R version 4.6.1. Well, since R 4.6.0, from R News:
\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.
\n
Therefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:
\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.
\n
[...]
\n\n\n", "answer_id": 677139, "answer_text": "You are using R version 4.6.1. Well, since R 4.6.0, from R News (https://cran.r-project.org/doc/manuals/r-release/NEWS.html):\n\n\n\n\n\n\n\nwilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hothorn.\n\n\n\n\n\n\n\nTherefore, it seems there's no longer a reason to throw a warning. The wilcox.test() documentation says:\n\n\n\n\n\n\n\nIf there are ties, exact inference is performed using the\nconditional/permutation distribution given the observed ranks, using\nan implementation of the Streitberg–Röhmel shift algorithm (Streitberg\nand Röhmel 1986; Streitberg and Röhmel 1987) contributed by Torsten\nHothorn.\n\n\n\n\n\n\n\n[...]\n\n\n\n\n\n\n\nStreitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.\n\n\n\n\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/ (https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/).", "answer_url": "https://stats.stackexchange.com/a/677139", "author": "J-J-J", "author_url": "https://stats.stackexchange.com/users/164936/j-j-j", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T07:32:22+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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T07:32:22+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "23216BD3-49D3-422F-8020-02B7D9CD2B5A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/23216BD3-49D3-422F-8020-02B7D9CD2B5A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "J-J-J", "profile_url": "https://stats.stackexchange.com/users/164936/j-j-j", "user_type": "registered"}, "created_at": "2026-09-11T08:09:51+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "CB4779A0-4EA1-4BB0-99F8-7FFB266F646D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CB4779A0-4EA1-4BB0-99F8-7FFB266F646D/view-source"}], "score": 16, "updated_at": "2026-09-11T08:09:51+00:00"}, {"answer_html": "Streitberg B, Röhmel J (1986). “Exact Distributions for Permutation\nand Rank Tests: An Introduction to Some Recently Published\nAlgorithms.” Statistical Software Newsletter, 12(1), 10–17. ISSN\n0173-5896.
\nStreitberg B, Röhmel J (1987). “Exakte Verteilungen für Rang- und\nRandomisierungstests im allgemeinen c-Stichprobenfall.” EDV in Medizin\nund Biologie, 18(1), 12–19. ISSN 0300-8282.\nhttps://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/.
\n
This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.
\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.
\n\nHere we range from evident to speculative:
\nInteger scores, so ties are more likely than otherwise.
\nIs there an upper limit of 32?
\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.
\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?
\n", "answer_id": 677141, "answer_text": "This arguably should at most be a comment as it doesn't attempt to answer the question at all. But I have a graph, and my comment also pertains to many applications of such tests that are likely not very helpful in data analysis. I am presuming that the data are serious from somewhere. If that isn't so, then this reply loses some of its force.\n\n\n\n\nHere is a scatter plot of Post versus Pre. Ties on Pre or Post are naturally shown by vertical or horizontal alignment; ties on both are shown by text 2 rather than text 1 on the graph.\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/7o9W87he.png] (https://i.sstatic.net/7o9W87he.png)\n\n\n\n\nHere we range from evident to speculative:\n\n\n\n\n\n\n\nInteger scores, so ties are more likely than otherwise.\n\n\n\n\n\n\n\n\n\nIs there an upper limit of 32?\n\n\n\n\n\n\n\n\n\nThe observations seem to fall into two groups, those whose Post score is quite good, and those whose Post score is about the same as their Pre.\n\n\n\n\n\n\n\n\nA Wilcoxon test can't pay direct attention to such details emerging from a very simple graphical analysis. Sure, 11/13 had higher Post, 1 the same, 1 lower. But does the test really help?", "answer_url": "https://stats.stackexchange.com/a/677141", "author": "Nick Cox", "author_url": "https://stats.stackexchange.com/users/22047/nick-cox", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-11T08:47:46+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": 677135, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-11T08:47:46+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "F5E781A6-F63A-4F3B-897E-03303213674F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F5E781A6-F63A-4F3B-897E-03303213674F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-11T09:20:25+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "2F24FDA3-AB03-426F-84C2-A097A0D37730", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2F24FDA3-AB03-426F-84C2-A097A0D37730/view-source"}], "score": 7, "updated_at": "2026-09-11T09:20:25+00:00"}], "domain": "statistics", "external_links": ["https://cran.r-project.org/doc/manuals/r-release/NEWS.html", "https://i.sstatic.net/7o9W87he.png", "https://reprex.tidyverse.org", "https://reprex.tidyverse.org/", "https://ul.qucosa.de/api/qucosa%3A12624/attachment/ATT-0/"], "medical_sensitive": false, "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": "DAVID PAUL CAPELLE", "question_author_url": "https://stats.stackexchange.com/users/386267/david-paul-capelle", "question_author_user_type": "registered", "question_created_at": "2026-09-11T01:14:02+00:00", "question_html": "I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df", \n"tbl", "data.frame"))\n\nAs there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?
Here is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.
\n\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c("tbl_df", "tbl", "data.frame")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```\n\n", "question_id": 677135, "question_license": "CC BY-SA 4.0", "question_score": 10, "question_text": "I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:\n\n\n\n\ndf <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n\n\n\n\n\nAs there are ties in the data I would have expected wilcox.test() to produce a warning. Why is there no warning in this case?\n\n\n\n\nHere is the reprex. I have tested it in an online IDE and obtained the same result as in my environment. I still do not see why ties are not reported.\n\n\n\n\n\nprepost <- structure(\n list(\n PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, 26, 25, 23, 18),\n PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, 30, 32, 30, 31, 17)\n ),\n row.names = c(NA, -13L),\n class = c(\"tbl_df\", \"tbl\", \"data.frame\")\n)\n\nwilcox.test(\n prepost$PostScore,\n prepost$PreScore,\n conf.int = TRUE,\n paired = TRUE,\n exact = TRUE\n)\n#> \n#> Wilcoxon signed rank exact test\n#> \n#> data: prepost$PostScore and prepost$PreScore\n#> V = 88, p-value = 0.0009766\n#> alternative hypothesis: true location shift is not equal to 0\n#> 96.7 percent confidence interval:\n#> 4 9\n#> sample estimates:\n#> (pseudo)median \n#> 6.5\n\nsessionInfo()\n#> R version 4.6.1 (2026-06-24)\n#> Platform: x86_64-pc-linux-gnu\n#> Running under: Garuda Linux\n#> \n#> Matrix products: default\n#> BLAS: /usr/lib/libblas.so.3.12.0 \n#> LAPACK: /usr/lib/liblapack.so.3.12.0 LAPACK version 3.12.0\n#> \n#> locale:\n#> [1] LC_CTYPE=en_SG.UTF-8 LC_NUMERIC=C \n#> [3] LC_TIME=en_SG.UTF-8 LC_COLLATE=en_SG.UTF-8 \n#> [5] LC_MONETARY=en_SG.UTF-8 LC_MESSAGES=en_SG.UTF-8 \n#> [7] LC_PAPER=en_SG.UTF-8 LC_NAME=C \n#> [9] LC_ADDRESS=C LC_TELEPHONE=C \n#> [11] LC_MEASUREMENT=en_SG.UTF-8 LC_IDENTIFICATION=C \n#> \n#> time zone: Asia/Kuala_Lumpur\n#> tzcode source: system (glibc)\n#> \n#> attached base packages:\n#> [1] stats graphics grDevices utils datasets methods base \n#> \n#> loaded via a namespace (and not attached):\n#> [1] digest_0.6.39 fastmap_1.2.0 xfun_0.60 glue_1.8.1 \n#> [5] knitr_1.51 htmltools_0.5.9 rmarkdown_2.32 lifecycle_1.0.5 \n#> [9] cli_3.6.6 reprex_2.1.1 withr_3.0.2 compiler_4.6.1 \n#> [13] rstudioapi_0.19.0 tools_4.6.1 evaluate_1.0.5 yaml_2.3.12 \n#> [17] otel_0.2.0 rlang_1.2.0 fs_2.1.0\n```", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DAVID PAUL CAPELLE", "profile_url": "https://stats.stackexchange.com/users/386267/david-paul-capelle", "user_type": "registered"}, "created_at": "2026-09-11T01:14:02+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "93652C25-9FE3-4C77-B0E9-CF7DD58DC50A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/93652C25-9FE3-4C77-B0E9-CF7DD58DC50A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DAVID PAUL CAPELLE", "profile_url": "https://stats.stackexchange.com/users/386267/david-paul-capelle", "user_type": "registered"}, "created_at": "2026-09-11T06:13:00+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "C7E16D39-DC10-460F-B943-B7547B90F63D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C7E16D39-DC10-460F-B943-B7547B90F63D/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-11T09:18:50+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "BC7129B7-4E28-49C0-8308-97D09DE31CA9", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/BC7129B7-4E28-49C0-8308-97D09DE31CA9/view-source"}, {"content_license": null, "contributor": {"display_name": "M--", "profile_url": "https://stats.stackexchange.com/users/154449/m", "user_type": "registered"}, "created_at": "2026-09-13T11:06:51+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "052E2710-AD21-4AFE-992F-D9FB54C17A14", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/052E2710-AD21-4AFE-992F-D9FB54C17A14/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677135/why-does-r-not-warn-about-ties-in-wilcox-test", "split": "train", "split_group": "fb4920dde6ede8f339350f0d34d985d9c1dcf8eb8ac2beea3857cb378c76b04b", "tags": ["r", "ties"], "thread_id": "stats:677135", "title": "Why does R not warn about ties in wilcox.test()"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "library(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)\nbasis_matrix\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677137, "sha256": "625d3a6019c48761839d6530ecc3c3e86fbd3239c15c955f72192c54f6da8e62", "source_url": "https://stats.stackexchange.com/questions/677137/why-does-a-cubic-b-spline-basis-matrix-contain-so-many-zero-columns"}, {"block_index": 0, "code_text": "library(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = \"l\") ## cosmetic\nmatplot(x_all, basis_matrix, type = \"l\", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677164, "sha256": "889db05ba0b28d8f0e24540e9c3d031ee80a767e206ebb68a5f169c03c9841db", "source_url": "https://stats.stackexchange.com/a/677164"}], "other_answers": [{"answer_html": "Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for $-3 \\lt x \\lt 6$), with the ones that are non-zero at $x=1.5$ highlighted:
\n\nlibrary(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = "l") ## cosmetic\nmatplot(x_all, basis_matrix, type = "l", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)\n\n", "answer_id": 677164, "answer_text": "Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for $-3 \\lt x \\lt 6$), with the ones that are non-zero at $x=1.5$ highlighted:\n\n\n\n\n[image: plot of the basis elements of a spline, with the elements that are non-zero at x=1.5 highlighted (solid, thick lines); source: https://i.sstatic.net/7o5ja3We.png] (https://i.sstatic.net/7o5ja3We.png)\n\n\n\n\nlibrary(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = \"l\") ## cosmetic\nmatplot(x_all, basis_matrix, type = \"l\", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)", "answer_url": "https://stats.stackexchange.com/a/677164", "author": "Ben Bolker", "author_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-13T20:32:49+00:00", "is_accepted": false, "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": 677137, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ben Bolker", "profile_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "user_type": "registered"}, "created_at": "2026-09-13T20:32:49+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "EBF57CF7-0E40-482E-A05C-136F42F17A79", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EBF57CF7-0E40-482E-A05C-136F42F17A79/view-source"}], "score": 6, "updated_at": "2026-09-13T20:32:49+00:00"}], "product": "code_qa", "question": "I've been studying how splines::bs() builds its basis matrix, and I'm trying to fully understand why the returned matrix has so many zero entries.\n\n\n\n\nThe worked example in Ken Koon Wong's blog post \"Understanding Basis Spline (B-spline) By Working Through Cox-deBoor Algorithm\", reproduced below:\n\n\n\n\nlibrary(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)\nbasis_matrix\n\n\n\n\n\nResult:\n\n\n\n\n## 1 2 3 4 5 6 7 8 9 10 11\n## [1,] 0 0 0 0.02083333 0.4791667 0.4791667 0.02083333 0 0 0 0\n## attr(,\"degree\")\n## [1] 3\n## attr(,\"knots\")\n## [1] -2 -1 0 1 2 3 4 5\n## attr(,\"Boundary.knots\")\n## [1] -3 6\n## attr(,\"intercept\")\n## [1] FALSE\n## attr(,\"class\")\n## [1] \"bs\" \"basis\" \"matrix\"\n\n\n\n\n\nWong explained:\n\n\n\n\n\n\n\nAwesome!!! We have very similar numbers !!! But why are there so many columns? And they’re filled with zeros, reminds me almost like padding. Apparently this is mainly to ensure no issues when x is very close to boundary knots is my understanding. And the way they add these padding depends on degrees + 1 if you use degree = 3, add 1 to it and that would be how many repeats of the numbers of your boundary knots.\n\n\n\n\n\n\n\nBut why are the number of leading and trailing zeros different?\n\n\n\n\nFrom wiki of De Boor's algorithm,\n\n\n\n\n\n\n\nIt follows from i≥0 that k≥p. Similarly, we see in the recursion that the highest queried knot location is at index k+1+p. This means that any knot interval [tk,tk+1) which is actually used must have at least p additional knots before and after. In a computer program, this is typically achieved by repeating the first and last used knot location p times. For example, for p=3 and real knot locations (0,1,2), one would pad the knot vector to (0,0,0,0,1,2,2,2,2).\n\n\n\n\n\n\n\n{which is actually used must have at least p additional knots before and after}<- Then the number of leading and trailing zeros should be the same? i.e. 3+1 = 4\n\n\n\n\n\n\n\nUpdate:\nAccording to the calculation by Ken Koon Wong,\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/v4LeyMo7.png] (https://i.sstatic.net/v4LeyMo7.png)\n\n\n\n\nThe position of knots should be c(-3,-3,-3,-3,-2, -1, 0, 1, 2,2,2,2)?\nAm I correct?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677137", "selected_answer": {"answer_html": "B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).
\nConsequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostly-zero.
\n* This locality is mathematically and graphically explicit in the wikipedia article, which is worth reading.
\n", "answer_id": 677156, "answer_text": "B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).\n\n\n\n\nConsequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostly-zero.\n\n\n\n\n\n\n\n* This locality is mathematically and graphically explicit in the wikipedia article, which is worth reading.", "answer_url": "https://stats.stackexchange.com/a/677156", "author": "Glen_b", "author_url": "https://stats.stackexchange.com/users/805/glen-b", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-13T02:41:43+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": 677137, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-13T02:41:43+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "F103E6FE-AD3D-4F47-A179-708950A92E6A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F103E6FE-AD3D-4F47-A179-708950A92E6A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-13T03:16:34+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "323EB6A5-54C4-485A-910C-C896C850F031", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/323EB6A5-54C4-485A-910C-C896C850F031/view-source"}], "score": 10, "updated_at": "2026-09-13T03:16:34+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).
\nConsequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostly-zero.
\n* This locality is mathematically and graphically explicit in the wikipedia article, which is worth reading.
\n", "answer_id": 677156, "answer_text": "B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).\n\n\n\n\nConsequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostly-zero.\n\n\n\n\n\n\n\n* This locality is mathematically and graphically explicit in the wikipedia article, which is worth reading.", "answer_url": "https://stats.stackexchange.com/a/677156", "author": "Glen_b", "author_url": "https://stats.stackexchange.com/users/805/glen-b", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-13T02:41:43+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": 677137, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-13T02:41:43+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "F103E6FE-AD3D-4F47-A179-708950A92E6A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F103E6FE-AD3D-4F47-A179-708950A92E6A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Glen_b", "profile_url": "https://stats.stackexchange.com/users/805/glen-b", "user_type": "registered"}, "created_at": "2026-09-13T03:16:34+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "323EB6A5-54C4-485A-910C-C896C850F031", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/323EB6A5-54C4-485A-910C-C896C850F031/view-source"}], "score": 10, "updated_at": "2026-09-13T03:16:34+00:00"}, {"answer_html": "Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for $-3 \\lt x \\lt 6$), with the ones that are non-zero at $x=1.5$ highlighted:
\n\nlibrary(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = "l") ## cosmetic\nmatplot(x_all, basis_matrix, type = "l", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)\n\n", "answer_id": 677164, "answer_text": "Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for $-3 \\lt x \\lt 6$), with the ones that are non-zero at $x=1.5$ highlighted:\n\n\n\n\n[image: plot of the basis elements of a spline, with the elements that are non-zero at x=1.5 highlighted (solid, thick lines); source: https://i.sstatic.net/7o5ja3We.png] (https://i.sstatic.net/7o5ja3We.png)\n\n\n\n\nlibrary(splines)\nx_i <- 1.5\nx_all <- seq(-3, 6, length.out = 150)\nbasis_matrix <- splines::bs(x_all,\n knots = -2:5, \n Boundary.knots = c(-3, 6),\n degree = 3)\npos_el <- rep(c(1,2,1), c(3,4,3))\npar(las=1, bty = \"l\") ## cosmetic\nmatplot(x_all, basis_matrix, type = \"l\", lty = 3-pos_el, lwd = pos_el)\nabline(v=1.5, lty = 2)", "answer_url": "https://stats.stackexchange.com/a/677164", "author": "Ben Bolker", "author_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-13T20:32:49+00:00", "is_accepted": false, "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": 677137, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ben Bolker", "profile_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "user_type": "registered"}, "created_at": "2026-09-13T20:32:49+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "EBF57CF7-0E40-482E-A05C-136F42F17A79", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/EBF57CF7-0E40-482E-A05C-136F42F17A79/view-source"}], "score": 6, "updated_at": "2026-09-13T20:32:49+00:00"}], "domain": "statistics", "external_links": ["https://i.sstatic.net/7o5ja3We.png", "https://i.sstatic.net/v4LeyMo7.png"], "medical_sensitive": false, "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": "doraemon", "question_author_url": "https://stats.stackexchange.com/users/368723/doraemon", "question_author_user_type": "registered", "question_created_at": "2026-09-11T07:17:25+00:00", "question_html": "I've been studying how splines::bs() builds its basis matrix, and I'm trying to fully understand why the returned matrix has so many zero entries.
\nThe worked example in Ken Koon Wong's blog post "Understanding Basis Spline (B-spline) By Working Through Cox-deBoor Algorithm", reproduced below:
\nlibrary(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)\nbasis_matrix\n\nResult:
\n## 1 2 3 4 5 6 7 8 9 10 11\n## [1,] 0 0 0 0.02083333 0.4791667 0.4791667 0.02083333 0 0 0 0\n## attr(,"degree")\n## [1] 3\n## attr(,"knots")\n## [1] -2 -1 0 1 2 3 4 5\n## attr(,"Boundary.knots")\n## [1] -3 6\n## attr(,"intercept")\n## [1] FALSE\n## attr(,"class")\n## [1] "bs" "basis" "matrix"\n\nWong explained:
\n\n\nAwesome!!! We have very similar numbers !!! But why are there so many columns? And they’re filled with zeros, reminds me almost like padding. Apparently this is mainly to ensure no issues when x is very close to boundary knots is my understanding. And the way they add these padding depends on degrees + 1 if you use degree = 3, add 1 to it and that would be how many repeats of the numbers of your boundary knots.
\n
But why are the number of leading and trailing zeros different?
\nFrom wiki of De Boor's algorithm,
\n\n\nIt follows from i≥0 that k≥p. Similarly, we see in the recursion that the highest queried knot location is at index k+1+p. This means that any knot interval [tk,tk+1) which is actually used must have at least p additional knots before and after. In a computer program, this is typically achieved by repeating the first and last used knot location p times. For example, for p=3 and real knot locations (0,1,2), one would pad the knot vector to (0,0,0,0,1,2,2,2,2).
\n
{which is actually used must have at least p additional knots before and after}<- Then the number of leading and trailing zeros should be the same? i.e. 3+1 = 4
\nUpdate:\nAccording to the calculation by Ken Koon Wong,
\n\nThe position of knots should be c(-3,-3,-3,-3,-2, -1, 0, 1, 2,2,2,2)?\nAm I correct?
\n", "question_id": 677137, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I've been studying how splines::bs() builds its basis matrix, and I'm trying to fully understand why the returned matrix has so many zero entries.\n\n\n\n\nThe worked example in Ken Koon Wong's blog post \"Understanding Basis Spline (B-spline) By Working Through Cox-deBoor Algorithm\", reproduced below:\n\n\n\n\nlibrary(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)\nbasis_matrix\n\n\n\n\n\nResult:\n\n\n\n\n## 1 2 3 4 5 6 7 8 9 10 11\n## [1,] 0 0 0 0.02083333 0.4791667 0.4791667 0.02083333 0 0 0 0\n## attr(,\"degree\")\n## [1] 3\n## attr(,\"knots\")\n## [1] -2 -1 0 1 2 3 4 5\n## attr(,\"Boundary.knots\")\n## [1] -3 6\n## attr(,\"intercept\")\n## [1] FALSE\n## attr(,\"class\")\n## [1] \"bs\" \"basis\" \"matrix\"\n\n\n\n\n\nWong explained:\n\n\n\n\n\n\n\nAwesome!!! We have very similar numbers !!! But why are there so many columns? And they’re filled with zeros, reminds me almost like padding. Apparently this is mainly to ensure no issues when x is very close to boundary knots is my understanding. And the way they add these padding depends on degrees + 1 if you use degree = 3, add 1 to it and that would be how many repeats of the numbers of your boundary knots.\n\n\n\n\n\n\n\nBut why are the number of leading and trailing zeros different?\n\n\n\n\nFrom wiki of De Boor's algorithm,\n\n\n\n\n\n\n\nIt follows from i≥0 that k≥p. Similarly, we see in the recursion that the highest queried knot location is at index k+1+p. This means that any knot interval [tk,tk+1) which is actually used must have at least p additional knots before and after. In a computer program, this is typically achieved by repeating the first and last used knot location p times. For example, for p=3 and real knot locations (0,1,2), one would pad the knot vector to (0,0,0,0,1,2,2,2,2).\n\n\n\n\n\n\n\n{which is actually used must have at least p additional knots before and after}<- Then the number of leading and trailing zeros should be the same? i.e. 3+1 = 4\n\n\n\n\n\n\n\nUpdate:\nAccording to the calculation by Ken Koon Wong,\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/v4LeyMo7.png] (https://i.sstatic.net/v4LeyMo7.png)\n\n\n\n\nThe position of knots should be c(-3,-3,-3,-3,-2, -1, 0, 1, 2,2,2,2)?\nAm I correct?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "doraemon", "profile_url": "https://stats.stackexchange.com/users/368723/doraemon", "user_type": "registered"}, "created_at": "2026-09-11T07:17:25+00:00", "raw_file": "raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json", "raw_sha256": "ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc", "revision_guid": "44C9B612-E48F-45D8-A87E-134A15427F2A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/44C9B612-E48F-45D8-A87E-134A15427F2A/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-13T06:50:29+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "7FDC6F64-699C-45D6-AD65-42C2EB6E9601", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/7FDC6F64-699C-45D6-AD65-42C2EB6E9601/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-09-15T03:24:20+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "26A7DFFA-3772-4615-A75D-4773FFF3DA34", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/26A7DFFA-3772-4615-A75D-4773FFF3DA34/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "doraemon", "profile_url": "https://stats.stackexchange.com/users/368723/doraemon", "user_type": "registered"}, "created_at": "2026-09-18T09:00:22+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "DF8093CD-0CC4-47CA-A76A-429E20D88E33", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/DF8093CD-0CC4-47CA-A76A-429E20D88E33/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677137/why-does-a-cubic-b-spline-basis-matrix-contain-so-many-zero-columns", "split": "train", "split_group": "a3b9bc15521973baeed3260891b4d75567f430c5afd7368e49e8db8c587dd1a5", "tags": ["r", "splines", "mgcv", "gamlss"], "thread_id": "stats:677137", "title": "Why does a cubic B-spline basis matrix contain so many zero columns?"}} {"accepted_answer": {"answer_html": "Fix treatment arm $d$ and, to keep the notation light, let all sums and expectations below be taken within that arm. Write
\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$$
\nA first-order Taylor expansion of $f(y,m)=y/m$ gives
\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$$
\nThe last equality uses $E[Y]=\\tau E[M]$. Therefore, the influence function is
\n$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$
\nReplacing the unknown quantities with their sample estimates gives
\n$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$
\nThus, apart from the constant scaling factor $1/\\overline{M}$, the linearized outcome is
\n$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\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
\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\nCreated on 2026-09-15 with reprex v2.1.1
\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": "Fix treatment arm $d$ and, to keep the notation light, let all sums and expectations below be taken within that arm. Write
\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$$
\nA first-order Taylor expansion of $f(y,m)=y/m$ gives
\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$$
\nThe last equality uses $E[Y]=\\tau E[M]$. Therefore, the influence function is
\n$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$
\nReplacing the unknown quantities with their sample estimates gives
\n$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$
\nThus, apart from the constant scaling factor $1/\\overline{M}$, the linearized outcome is
\n$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\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
\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\nCreated on 2026-09-15 with reprex v2.1.1
\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": "Fix treatment arm $d$ and, to keep the notation light, let all sums and expectations below be taken within that arm. Write
\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$$
\nA first-order Taylor expansion of $f(y,m)=y/m$ gives
\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$$
\nThe last equality uses $E[Y]=\\tau E[M]$. Therefore, the influence function is
\n$$\n\\operatorname{IF}_i\n=\n\\frac{Y_i-\\tau M_i}{E[M]}.\n$$
\nReplacing the unknown quantities with their sample estimates gives
\n$$\n\\widehat{\\operatorname{IF}}_i\n=\n\\frac{Y_i-\\widehat{\\tau}M_i}{\\overline{M}}.\n$$
\nThus, apart from the constant scaling factor $1/\\overline{M}$, the linearized outcome is
\n$$\nZ_i=Y_i-\\widehat{\\tau}M_i.\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
\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\nCreated on 2026-09-15 with reprex v2.1.1
\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": "In my workplace, I came across an idea that OLS can be retooled to solve ratio metric inference problems.
\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)$$
\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.
\nNaively, we have two options for OLS.
\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$$ \\frac{k_i}{m_i} = \\alpha + \\lambda d_i + \\beta X +\\epsilon $$
\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$$ \\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 $$
\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$$ z_i = k_i - (\\frac{\\sum_{j=1} K_j}{\\sum_{j=1} M_j}) m_i $$
\n$$ z_i = \\alpha + \\lambda d_i + \\beta X_i +\\epsilon $$
\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.
\nQuestion: How does the TSE prove $z_i$ to be the correct solution accounting for the nonlinearity in the ratio function?
\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": "modelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = \"logit\")\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677183, "sha256": "d2e0b087137c58a9d017d1f4cb6ac63b0c3aa386a664b23e5b642e53fe18932f", "source_url": "https://stats.stackexchange.com/questions/677183/ordinal-mixed-effect-model-with-3-factors-and-interactions-beginner-help"}], "other_answers": [], "product": "code_qa", "question": "I am a beginner in Ordinal Models looking for some help. I am doing a 3-factor model, primarily interested in the effect of the 3 way interaction on the results. I have to say that I come from making Linear mixed effect models and initially assumed it would largerly transfer. However, I do not know how to report the results I got, nor how to visualize it in a easy, straighforward manner.\nHere is the model I'm using in R:\n\n\n\n\nmodelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = \"logit\")\n\n\n\n\n\nRating_Resp is 5 levels; WordCat, Session and Group are all categorical with 2 levels, with Session being within group factor. Participant and word/item are random intercepts.\nI then used summary(modelOrdinalWordCat) to look at the model in a more \"ANOVA\" like manner, and got this print out.\n\n\n\n\n Estimate Std. Error z value Pr(>|z|) \nWordCat[S.NonWord] -0.38012 0.04136 -9.190 < 2e-16 ***\nGroupL2 Exposure -0.17397 0.08151 -2.134 0.03282 *\nSession2 -0.05367 0.03627 -1.480 0.13896 \nWordCat[S.NonWord]:GroupL2 Exposure 0.04777 0.03412 1.400 0.16141 \nWordCat[S.NonWord]:Session2 0.05404 0.03623 1.492 0.13579 \nGroupL2 Exposure:Session2 0.13310 0.04820 2.761 0.00576 ** \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 -0.10393 0.04815 -2.159 0.03089 * \n\n\n\n\n\nUsing just the default print out, I get this:\n\n\n\n\nWordCat[S.NonWord] GroupL2 Exposure \n-0.38012 -0.17397 \nSession2 WordCat[S.NonWord]:GroupL2 Exposure \n-0.05367 0.04777 \nWordCat[S.NonWord]:Session2 GroupL2 Exposure:Session2 \n0.05404 0.13310 \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 \n-0.10393 \n\n\n\n\n\nI can't make heads of tails of this table.\nHow do I report the results of this? Is it just : Word Type x Session x Group: estimate = -0.10, SE = 0.048, z value = -2.16, p = .031\nThanks in advance!\n(If I am completely wrong, let me have it!)", "record_id": "Scientific-Code-and-Analysis-QA:stats:677183", "selected_answer": {"answer_html": "Ordinal models pose (at least) two difficulties in interpretation beyond standard linear models.
\nFirst, the coefficients are in log-odds scales, which can be hard to think about even in logistic regression. A log-odds coefficient in ordinal regression is for the change of one outcome level per change in a predictor or interaction.
\nYou should show the model summary, but visualization of model predictions and their confidence intervals or standard errors is more useful for your audience (and probably for yourself). As you used the standard R treatment coding of the factors, each coefficient thus represents the difference in log-odds associated with a predictor or interaction term, beyond what would be predicted from lower-level intercepts or single-predictor coefficients or interactions.
\nSecond, instead of having a single intercept as in logistic regression, there is a separate intercept for each transition between outcome levels. To get model predictions, it's simplest to use post-modeling tools like those in the emmeans package recommended by @Sointu in a comment.
Your 3-way interaction is thus the difference in log-odds for changing one outcome level between the situation with none of the 3 factors at reference levels and the situation with only 1 of them at the reference level. The coefficient of -0.10393 in log-odds scale represents odds of about 0.9. Whether its statistical significance is important in practice depends on your understanding of the subject matter.
This site has several entries that provide more detail and links, including Interpretation of ordinal logistic regression and How to understand output from R's polr function (ordered logistic regression)?. UCLA Advanced Research Computing has pages on Ordinal Logistic Regression | R Data Analysis Examples and How Do I Interpret the Coefficients in an Ordinal Logistic Regression in R?. Frank Harrell provides extensive Resources for Ordinal Regression Models, recommending their widespread use even with data that would often be considered continuous.
\nOne additional warning: there are two different ways to set up the ordinal regression. Read the documentation to know which is being used. One models the probability of having an outcome less than or equal to a specified outcome level. That seems to be used in most R implementations. The other, used in Frank Harrell's rms package, models the probability of having an outcome greater than or equal to a specified outcome level. You'll find differences in signs of intercepts depending on which is used. The emmeans package can work with either to get model predictions.
Ordinal models pose (at least) two difficulties in interpretation beyond standard linear models.
\nFirst, the coefficients are in log-odds scales, which can be hard to think about even in logistic regression. A log-odds coefficient in ordinal regression is for the change of one outcome level per change in a predictor or interaction.
\nYou should show the model summary, but visualization of model predictions and their confidence intervals or standard errors is more useful for your audience (and probably for yourself). As you used the standard R treatment coding of the factors, each coefficient thus represents the difference in log-odds associated with a predictor or interaction term, beyond what would be predicted from lower-level intercepts or single-predictor coefficients or interactions.
\nSecond, instead of having a single intercept as in logistic regression, there is a separate intercept for each transition between outcome levels. To get model predictions, it's simplest to use post-modeling tools like those in the emmeans package recommended by @Sointu in a comment.
Your 3-way interaction is thus the difference in log-odds for changing one outcome level between the situation with none of the 3 factors at reference levels and the situation with only 1 of them at the reference level. The coefficient of -0.10393 in log-odds scale represents odds of about 0.9. Whether its statistical significance is important in practice depends on your understanding of the subject matter.
This site has several entries that provide more detail and links, including Interpretation of ordinal logistic regression and How to understand output from R's polr function (ordered logistic regression)?. UCLA Advanced Research Computing has pages on Ordinal Logistic Regression | R Data Analysis Examples and How Do I Interpret the Coefficients in an Ordinal Logistic Regression in R?. Frank Harrell provides extensive Resources for Ordinal Regression Models, recommending their widespread use even with data that would often be considered continuous.
\nOne additional warning: there are two different ways to set up the ordinal regression. Read the documentation to know which is being used. One models the probability of having an outcome less than or equal to a specified outcome level. That seems to be used in most R implementations. The other, used in Frank Harrell's rms package, models the probability of having an outcome greater than or equal to a specified outcome level. You'll find differences in signs of intercepts depending on which is used. The emmeans package can work with either to get model predictions.
I am a beginner in Ordinal Models looking for some help. I am doing a 3-factor model, primarily interested in the effect of the 3 way interaction on the results. I have to say that I come from making Linear mixed effect models and initially assumed it would largerly transfer. However, I do not know how to report the results I got, nor how to visualize it in a easy, straighforward manner.\nHere is the model I'm using in R:
\nmodelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = "logit")\n\nRating_Resp is 5 levels; WordCat, Session and Group are all categorical with 2 levels, with Session being within group factor. Participant and word/item are random intercepts.\nI then used summary(modelOrdinalWordCat) to look at the model in a more "ANOVA" like manner, and got this print out.
\n Estimate Std. Error z value Pr(>|z|) \nWordCat[S.NonWord] -0.38012 0.04136 -9.190 < 2e-16 ***\nGroupL2 Exposure -0.17397 0.08151 -2.134 0.03282 *\nSession2 -0.05367 0.03627 -1.480 0.13896 \nWordCat[S.NonWord]:GroupL2 Exposure 0.04777 0.03412 1.400 0.16141 \nWordCat[S.NonWord]:Session2 0.05404 0.03623 1.492 0.13579 \nGroupL2 Exposure:Session2 0.13310 0.04820 2.761 0.00576 ** \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 -0.10393 0.04815 -2.159 0.03089 * \n\nUsing just the default print out, I get this:
\nWordCat[S.NonWord] GroupL2 Exposure \n-0.38012 -0.17397 \nSession2 WordCat[S.NonWord]:GroupL2 Exposure \n-0.05367 0.04777 \nWordCat[S.NonWord]:Session2 GroupL2 Exposure:Session2 \n0.05404 0.13310 \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 \n-0.10393 \n\nI can't make heads of tails of this table.\nHow do I report the results of this? Is it just : Word Type x Session x Group: estimate = -0.10, SE = 0.048, z value = -2.16, p = .031\nThanks in advance!\n(If I am completely wrong, let me have it!)
\n", "question_id": 677183, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am a beginner in Ordinal Models looking for some help. I am doing a 3-factor model, primarily interested in the effect of the 3 way interaction on the results. I have to say that I come from making Linear mixed effect models and initially assumed it would largerly transfer. However, I do not know how to report the results I got, nor how to visualize it in a easy, straighforward manner.\nHere is the model I'm using in R:\n\n\n\n\nmodelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = \"logit\")\n\n\n\n\n\nRating_Resp is 5 levels; WordCat, Session and Group are all categorical with 2 levels, with Session being within group factor. Participant and word/item are random intercepts.\nI then used summary(modelOrdinalWordCat) to look at the model in a more \"ANOVA\" like manner, and got this print out.\n\n\n\n\n Estimate Std. Error z value Pr(>|z|) \nWordCat[S.NonWord] -0.38012 0.04136 -9.190 < 2e-16 ***\nGroupL2 Exposure -0.17397 0.08151 -2.134 0.03282 *\nSession2 -0.05367 0.03627 -1.480 0.13896 \nWordCat[S.NonWord]:GroupL2 Exposure 0.04777 0.03412 1.400 0.16141 \nWordCat[S.NonWord]:Session2 0.05404 0.03623 1.492 0.13579 \nGroupL2 Exposure:Session2 0.13310 0.04820 2.761 0.00576 ** \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 -0.10393 0.04815 -2.159 0.03089 * \n\n\n\n\n\nUsing just the default print out, I get this:\n\n\n\n\nWordCat[S.NonWord] GroupL2 Exposure \n-0.38012 -0.17397 \nSession2 WordCat[S.NonWord]:GroupL2 Exposure \n-0.05367 0.04777 \nWordCat[S.NonWord]:Session2 GroupL2 Exposure:Session2 \n0.05404 0.13310 \nWordCat[S.NonWord]:GroupL2 Exposure:Session2 \n-0.10393 \n\n\n\n\n\nI can't make heads of tails of this table.\nHow do I report the results of this? Is it just : Word Type x Session x Group: estimate = -0.10, SE = 0.048, z value = -2.16, p = .031\nThanks in advance!\n(If I am completely wrong, let me have it!)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rae", "profile_url": "https://stats.stackexchange.com/users/516706/rae", "user_type": "registered"}, "created_at": "2026-09-15T18:48:16+00:00", "raw_file": "raw/codex_api_v1/59f98009db0ac38325a869c60e3993040b07f5fbd07014051415831400b70d25_1790825251781774200_0.json", "raw_sha256": "2876465103b1eeb5d593dd46b1ec52a862c1da72f8e4767e5f8ee70ff0564119", "revision_guid": "54C1911F-DE57-4D25-88F0-822250BA5283", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/54C1911F-DE57-4D25-88F0-822250BA5283/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677183/ordinal-mixed-effect-model-with-3-factors-and-interactions-beginner-help", "split": "train", "split_group": "4e9596eab227a4c8203ea12055e6a18f2307cdda74a5c355bfd04e5dbaa03ae6", "tags": ["ordinal-data", "ordered-logit", "ordinal-logistic-regression"], "thread_id": "stats:677183", "title": "Ordinal Mixed Effect Model with 3 factors and Interactions - Beginner Help"}} {"accepted_answer": {"answer_html": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.
\nHere's a plot in R:
\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\n\n\n", "answer_id": 677231, "answer_text": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution (https://en.wikipedia.org/wiki/Beta-binomial_distribution)). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.\n\n\n\n\nHere's a plot in R:\n\n\n\n\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\n\n\n\n\n\n[image: plot k = 10 from R-Code, one extrem being just 0.4 at 0 and 0.6 at 10, the other fits the binomial; source: https://i.sstatic.net/cWGh2esg.png] (https://i.sstatic.net/cWGh2esg.png)\n[image: plot k = 1 from R-Code, just the same line from 0.4 to 0.6; source: https://i.sstatic.net/BHmL9Quz.png] (https://i.sstatic.net/BHmL9Quz.png)", "answer_url": "https://stats.stackexchange.com/a/677231", "author": "Lukas Lohse", "author_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-21T21:48:52+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": 677226, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lukas Lohse", "profile_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "user_type": "registered"}, "created_at": "2026-09-21T21:48:52+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "315A6811-DCF0-437C-A1D7-8721F8646961", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/315A6811-DCF0-437C-A1D7-8721F8646961/view-source"}], "score": 2, "updated_at": "2026-09-21T21:48:52+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "set.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste(\"Subject\", 1:n), levels = paste(\"Subject\", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n) {\n theta[i] <- rbeta(1, alpha, beta)\n}\n\n# Case 1 \ncase1 <- numeric(n)\nfor (i in 1:n) {\n case1[i] <- rbinom(1, 1, theta[i]) \n}\n\n# Case 2 \ncase2 <- matrix(NA, nrow = k, ncol = n) \nfor (i in 1:n) {\n for (j in 1:k) {\n case2[j, i] <- rbinom(1, 1, theta[i])\n }\n}\n\nd1 <- data.frame(subject = subjects, true = theta, meas = case1)\nd2 <- data.frame(subject = rep(subjects, each = k),\n true = rep(theta, each = k),\n meas = as.vector(case2))\nred2 <- data.frame(subject = subjects, true = theta)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677226, "sha256": "f6cd15195d5d74c89d7431b12ba7c0aac4d3e4e33b3ff40949960b1f791bcb23", "source_url": "https://stats.stackexchange.com/questions/677226/is-variance-still-estimable-when-you-observe-a-single-observation-per-subject"}, {"block_index": 0, "code_text": "library(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677231, "sha256": "f4d4b00c54ed85f483126ced360cf9820be997c762fbd027eda1b32c6af6f67e", "source_url": "https://stats.stackexchange.com/a/677231"}], "other_answers": [{"answer_html": "After thinking about this, I think I know how to do this. When $k=1$, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.
\nHowever, it is possible to estimate the variance of the mean estimator at $k=1$.
\nLet each unit have $\\theta_i \\overset{iid}{\\sim} \\text{Beta}(\\alpha,\\beta)$ with density $f(\\theta)$. Each unit is observed once ($k=1$), so $y_i \\mid \\theta_i \\sim \\text{Bernoulli}(\\theta_i)$:
\nFor a single unit, the Bernoulli distribution:\n$$P(y\\mid\\theta) = \\theta^{y}(1-\\theta)^{1-y}.$$
\nTo marginalize the distribution:
\n$$P(y_i=1) = \\int_0^1 \\theta\\, f(\\theta)\\,d\\theta = E[\\theta_i] = \\mu$$\n$$\\qquad P(y_i=0) = \\int_0^1 (1-\\theta)\\, f(\\theta)\\,d\\theta = 1-\\mu.$$
\n$$y_i \\sim \\text{Bernoulli}(\\mu) = P(y_i = y) = \\mu^{y}(1-\\mu)^{1-y}$$
\nThe iid assumption makes it easy to extend this to $n$ machines:
\n$$P(y_1,\\dots,y_n \\mid \\theta_1,\\dots,\\theta_n) = \\prod_{i=1}^n \\theta_i^{y_i}(1-\\theta_i)^{1-y_i}.$$
\n$$P(y_1,\\dots,y_n) = \\int\\!\\!\\cdots\\!\\!\\int \\prod_{i=1}^n \\Big[\\theta_i^{y_i}(1-\\theta_i)^{1-y_i} f(\\theta_i)\\Big]\\, d\\theta_1\\cdots d\\theta_n.$$
\n$$P(y_1,\\dots,y_n) = \\int_0^1 \\theta_1^{y_1}(1-\\theta_1)^{1-y_1}f(\\theta_1)\\,d\\theta_1 \\times \\cdots \\times \\int_0^1 \\theta_n^{y_n}(1-\\theta_n)^{1-y_n}f(\\theta_n)\\,d\\theta_n.$$
\n$$P(y_1,\\dots,y_n) = \\prod_{i=1}^n \\mu^{y_i}(1-\\mu)^{1-y_i} \\quad\\Longrightarrow\\quad y_1,\\dots,y_n \\overset{iid}{\\sim} \\text{Bernoulli}(\\mu).$$
\nNext, we can see $\\bar y$ is unbiased:
\n$$E[y_i\\mid\\theta_i] = 1\\cdot\\theta_i + 0\\cdot(1-\\theta_i) = \\theta_i$$\n$$E[y_i] = E\\big[\\,E[y_i\\mid\\theta_i]\\,\\big] = E[\\theta_i] = \\mu.$$\n$$E[\\bar y] = \\frac1n\\sum_{i=1}^n E[y_i] = \\frac1n\\cdot n\\mu = \\mu$$
\nNow for the variance:
\n$$\\sigma_y^2 = \\text{Var}(y_i) = \\underbrace{E[\\text{Var}(y_i\\mid\\theta_i)]}_{\\text{within}} + \\underbrace{\\text{Var}(E[y_i\\mid\\theta_i])}_{\\text{between}} = E[\\theta_i(1-\\theta_i)] + \\tau^2.$$
\n$$\\tau^2 = E[\\theta_i^2] - \\mu^2$$\n$$\\sigma_y^2 = \\big(\\mu - E[\\theta_i^2]\\big) + \\big(E[\\theta_i^2] - \\mu^2\\big) = \\mu(1-\\mu).$$
\nFor variance of the mean (0 covariance):
\n$$\\text{Var}(\\bar y) = \\frac{1}{n^2}\\sum_{i=1}^n \\text{Var}(y_i) = \\frac{1}{n^2}\\cdot n\\sigma_y^2 = \\frac{\\sigma_y^2}{n} = \\frac{\\mu(1-\\mu)}{n}.$$
\nFinally, we can see that $S^2$ is unbiased for $\\sigma_y^2$.
\nThe sample variance is:\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^n (y_i-\\bar y)^2.$$
\n$$\\sum_{i=1}^n (y_i-\\mu) = \\sum_i y_i - n\\mu = n\\bar y - n\\mu = n(\\bar y-\\mu).$$
\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 - n(\\bar y-\\mu)^2.$$
\nTherefore\n$$E\\Big[\\sum_i (y_i-\\bar y)^2\\Big] = n\\sigma_y^2 - n\\cdot\\frac{\\sigma_y^2}{n} = (n-1)\\sigma_y^2 \\quad\\Longrightarrow\\quad E[S^2] = \\sigma_y^2$$
\nFor 0/1 data, $y_i^2 = y_i$, and $S^2$ simplifies to $\\dfrac{n}{n-1}\\,\\bar y(1-\\bar y)$.
\nSo it seems that at $k=1$, we can estimate the population mean and variance of the mean estimator.
\n", "answer_id": 677265, "answer_text": "After thinking about this, I think I know how to do this. When $k=1$, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.\n\n\n\n\nHowever, it is possible to estimate the variance of the mean estimator at $k=1$.\n\n\n\n\nLet each unit have $\\theta_i \\overset{iid}{\\sim} \\text{Beta}(\\alpha,\\beta)$ with density $f(\\theta)$. Each unit is observed once ($k=1$), so $y_i \\mid \\theta_i \\sim \\text{Bernoulli}(\\theta_i)$:\n\n\n\n\n\n$\\mu = E[\\theta_i]$ — population mean (the target) and is $\\mu = \\frac{\\alpha}{\\alpha+\\beta}$\n\n\n\n\n\n\n$\\tau^2 = \\operatorname{Var}(\\theta_i)$ — population variance and is = $\\tau^2 = \\frac{\\mu(1-\\mu)}{\\alpha+\\beta+1}$\n\n\n\n\n\n\n$\\sigma_y^2 = \\operatorname{Var}(y_i)$\n\n\n\n\n\nFor a single unit, the Bernoulli distribution:\n$$P(y\\mid\\theta) = \\theta^{y}(1-\\theta)^{1-y}.$$\n\n\n\n\nTo marginalize the distribution:\n\n\n\n\n$$P(y_i=1) = \\int_0^1 \\theta\\, f(\\theta)\\,d\\theta = E[\\theta_i] = \\mu$$\n$$\\qquad P(y_i=0) = \\int_0^1 (1-\\theta)\\, f(\\theta)\\,d\\theta = 1-\\mu.$$\n\n\n\n\n$$y_i \\sim \\text{Bernoulli}(\\mu) = P(y_i = y) = \\mu^{y}(1-\\mu)^{1-y}$$\n\n\n\n\nThe iid assumption makes it easy to extend this to $n$ machines:\n\n\n\n\n$$P(y_1,\\dots,y_n \\mid \\theta_1,\\dots,\\theta_n) = \\prod_{i=1}^n \\theta_i^{y_i}(1-\\theta_i)^{1-y_i}.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\int\\!\\!\\cdots\\!\\!\\int \\prod_{i=1}^n \\Big[\\theta_i^{y_i}(1-\\theta_i)^{1-y_i} f(\\theta_i)\\Big]\\, d\\theta_1\\cdots d\\theta_n.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\int_0^1 \\theta_1^{y_1}(1-\\theta_1)^{1-y_1}f(\\theta_1)\\,d\\theta_1 \\times \\cdots \\times \\int_0^1 \\theta_n^{y_n}(1-\\theta_n)^{1-y_n}f(\\theta_n)\\,d\\theta_n.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\prod_{i=1}^n \\mu^{y_i}(1-\\mu)^{1-y_i} \\quad\\Longrightarrow\\quad y_1,\\dots,y_n \\overset{iid}{\\sim} \\text{Bernoulli}(\\mu).$$\n\n\n\n\nNext, we can see $\\bar y$ is unbiased:\n\n\n\n\n$$E[y_i\\mid\\theta_i] = 1\\cdot\\theta_i + 0\\cdot(1-\\theta_i) = \\theta_i$$\n$$E[y_i] = E\\big[\\,E[y_i\\mid\\theta_i]\\,\\big] = E[\\theta_i] = \\mu.$$\n$$E[\\bar y] = \\frac1n\\sum_{i=1}^n E[y_i] = \\frac1n\\cdot n\\mu = \\mu$$\n\n\n\n\nNow for the variance:\n\n\n\n\n$$\\sigma_y^2 = \\text{Var}(y_i) = \\underbrace{E[\\text{Var}(y_i\\mid\\theta_i)]}_{\\text{within}} + \\underbrace{\\text{Var}(E[y_i\\mid\\theta_i])}_{\\text{between}} = E[\\theta_i(1-\\theta_i)] + \\tau^2.$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i^2] - \\mu^2$$\n$$\\sigma_y^2 = \\big(\\mu - E[\\theta_i^2]\\big) + \\big(E[\\theta_i^2] - \\mu^2\\big) = \\mu(1-\\mu).$$\n\n\n\n\nFor variance of the mean (0 covariance):\n\n\n\n\n$$\\text{Var}(\\bar y) = \\frac{1}{n^2}\\sum_{i=1}^n \\text{Var}(y_i) = \\frac{1}{n^2}\\cdot n\\sigma_y^2 = \\frac{\\sigma_y^2}{n} = \\frac{\\mu(1-\\mu)}{n}.$$\n\n\n\n\nFinally, we can see that $S^2$ is unbiased for $\\sigma_y^2$.\n\n\n\n\nThe sample variance is:\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^n (y_i-\\bar y)^2.$$\n\n\n\n\n\n$\\bar y = \\frac1n\\sum_i y_i$ means $\\sum_i y_i = n\\bar y$.\n\n\n\n\nA constant $\\mu$ summed $n$ times is $n\\mu$.\n\n\n\n\n\n$$\\sum_{i=1}^n (y_i-\\mu) = \\sum_i y_i - n\\mu = n\\bar y - n\\mu = n(\\bar y-\\mu).$$\n\n\n\n\n\n$y_i - \\bar y = (y_i-\\mu) - (\\bar y-\\mu)$:\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 \\;-\\; 2(\\bar y-\\mu)\\underbrace{\\sum_i (y_i-\\mu)}_{=\\,n(\\bar y-\\mu)} \\;+\\; n(\\bar y-\\mu)^2.$$\n\n\n\n\n\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 - n(\\bar y-\\mu)^2.$$\n\n\n\n\n\n$E[(y_i-\\mu)^2] = \\sigma_y^2$\n\n\n\n\n$E[(\\bar y-\\mu)^2] = \\text{Var}(\\bar y) = \\sigma_y^2/n$\n\n\n\n\n\nTherefore\n$$E\\Big[\\sum_i (y_i-\\bar y)^2\\Big] = n\\sigma_y^2 - n\\cdot\\frac{\\sigma_y^2}{n} = (n-1)\\sigma_y^2 \\quad\\Longrightarrow\\quad E[S^2] = \\sigma_y^2$$\n\n\n\n\nFor 0/1 data, $y_i^2 = y_i$, and $S^2$ simplifies to $\\dfrac{n}{n-1}\\,\\bar y(1-\\bar y)$.\n\n\n\n\nSo it seems that at $k=1$, we can estimate the population mean and variance of the mean estimator.", "answer_url": "https://stats.stackexchange.com/a/677265", "author": "adamkostanov", "author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T17:44:30+00:00", "is_accepted": false, "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": 677226, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-25T17:44:30+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "A2509D36-CE80-4C0F-BA28-5077E22D040B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A2509D36-CE80-4C0F-BA28-5077E22D040B/view-source"}], "score": 0, "updated_at": "2026-09-25T17:44:30+00:00"}], "product": "code_qa", "question": "Here is a hierarchical data generating process:\n\n\n\n\n\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$\n\n\n\n\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$\n\n\n\n\n\n\n\nThere are two cases - Case 1 is where you sample 1 observation per subject and Case 2 where you sample multiple observations per subject:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/wine4qeY.png] (https://i.sstatic.net/wine4qeY.png)\n\n\n\n\nI am only interested in estimating the population level mean and variance. Can this still be done in Case 1?\n\n\n\n\nI am guessing that there will be no problems doing this for Case 2. For Case 1, I am guessing there won't be any problems for estimating the population level mean, but I am not sure if the population level variance can still be estimated since we do not observe variation at the individual level (regardless of whether moments are used or MLE).\n\n\n\n\n\n\n\nset.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste(\"Subject\", 1:n), levels = paste(\"Subject\", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n) {\n theta[i] <- rbeta(1, alpha, beta)\n}\n\n# Case 1 \ncase1 <- numeric(n)\nfor (i in 1:n) {\n case1[i] <- rbinom(1, 1, theta[i]) \n}\n\n# Case 2 \ncase2 <- matrix(NA, nrow = k, ncol = n) \nfor (i in 1:n) {\n for (j in 1:k) {\n case2[j, i] <- rbinom(1, 1, theta[i])\n }\n}\n\nd1 <- data.frame(subject = subjects, true = theta, meas = case1)\nd2 <- data.frame(subject = rep(subjects, each = k),\n true = rep(theta, each = k),\n meas = as.vector(case2))\nred2 <- data.frame(subject = subjects, true = theta)", "record_id": "Scientific-Code-and-Analysis-QA:stats:677226", "selected_answer": {"answer_html": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.
\nHere's a plot in R:
\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\n\n\n", "answer_id": 677231, "answer_text": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution (https://en.wikipedia.org/wiki/Beta-binomial_distribution)). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.\n\n\n\n\nHere's a plot in R:\n\n\n\n\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\n\n\n\n\n\n[image: plot k = 10 from R-Code, one extrem being just 0.4 at 0 and 0.6 at 10, the other fits the binomial; source: https://i.sstatic.net/cWGh2esg.png] (https://i.sstatic.net/cWGh2esg.png)\n[image: plot k = 1 from R-Code, just the same line from 0.4 to 0.6; source: https://i.sstatic.net/BHmL9Quz.png] (https://i.sstatic.net/BHmL9Quz.png)", "answer_url": "https://stats.stackexchange.com/a/677231", "author": "Lukas Lohse", "author_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-21T21:48:52+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": 677226, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lukas Lohse", "profile_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "user_type": "registered"}, "created_at": "2026-09-21T21:48:52+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "315A6811-DCF0-437C-A1D7-8721F8646961", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/315A6811-DCF0-437C-A1D7-8721F8646961/view-source"}], "score": 2, "updated_at": "2026-09-21T21:48:52+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677231, "answers": [{"answer_html": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.
\nHere's a plot in R:
\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = "b", \n col = "red", lwd = 4, ylim = c(0, mu), main = paste0("k = ", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = "b")\n}\n\n\n\n", "answer_id": 677231, "answer_text": "No you can not estimate the $\\theta_i$ variance for $k = 1$. The relevant concept is the beta-binomial distribution(https://en.wikipedia.org/wiki/Beta-binomial_distribution (https://en.wikipedia.org/wiki/Beta-binomial_distribution)). Now we are keeping $\\mu$ fixed and just consider $\\alpha + \\beta$ as a variable then for very large $\\alpha + \\beta$ this basically just the binomial distribution while if it's close to $0$ you end up with basically a Bernoulli-distribution over $\\{0, k\\}$. Of course for $k = 1$ those two are the same thing so there's no way to distinguish any $\\alpha + \\beta$ as long as they have same $\\mu$.\n\n\n\n\nHere's a plot in R:\n\n\n\n\nlibrary(extraDistr)\npars <- exp(seq(-10, 10, length.out = 10))\nmu <- 0.6\nk <- 10\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\nk <- 1\ny <- 0:k\n\nplot(y, dbinom(y, prob = mu, size = k), type = \"b\", \n col = \"red\", lwd = 4, ylim = c(0, mu), main = paste0(\"k = \", k))\nfor(par in pars){\n points(y, dbbinom(y, alpha = mu*par, beta = (1-mu)* par, size = k), type = \"b\")\n}\n\n\n\n\n\n\n[image: plot k = 10 from R-Code, one extrem being just 0.4 at 0 and 0.6 at 10, the other fits the binomial; source: https://i.sstatic.net/cWGh2esg.png] (https://i.sstatic.net/cWGh2esg.png)\n[image: plot k = 1 from R-Code, just the same line from 0.4 to 0.6; source: https://i.sstatic.net/BHmL9Quz.png] (https://i.sstatic.net/BHmL9Quz.png)", "answer_url": "https://stats.stackexchange.com/a/677231", "author": "Lukas Lohse", "author_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-21T21:48:52+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": 677226, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lukas Lohse", "profile_url": "https://stats.stackexchange.com/users/341520/lukas-lohse", "user_type": "registered"}, "created_at": "2026-09-21T21:48:52+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "315A6811-DCF0-437C-A1D7-8721F8646961", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/315A6811-DCF0-437C-A1D7-8721F8646961/view-source"}], "score": 2, "updated_at": "2026-09-21T21:48:52+00:00"}, {"answer_html": "After thinking about this, I think I know how to do this. When $k=1$, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.
\nHowever, it is possible to estimate the variance of the mean estimator at $k=1$.
\nLet each unit have $\\theta_i \\overset{iid}{\\sim} \\text{Beta}(\\alpha,\\beta)$ with density $f(\\theta)$. Each unit is observed once ($k=1$), so $y_i \\mid \\theta_i \\sim \\text{Bernoulli}(\\theta_i)$:
\nFor a single unit, the Bernoulli distribution:\n$$P(y\\mid\\theta) = \\theta^{y}(1-\\theta)^{1-y}.$$
\nTo marginalize the distribution:
\n$$P(y_i=1) = \\int_0^1 \\theta\\, f(\\theta)\\,d\\theta = E[\\theta_i] = \\mu$$\n$$\\qquad P(y_i=0) = \\int_0^1 (1-\\theta)\\, f(\\theta)\\,d\\theta = 1-\\mu.$$
\n$$y_i \\sim \\text{Bernoulli}(\\mu) = P(y_i = y) = \\mu^{y}(1-\\mu)^{1-y}$$
\nThe iid assumption makes it easy to extend this to $n$ machines:
\n$$P(y_1,\\dots,y_n \\mid \\theta_1,\\dots,\\theta_n) = \\prod_{i=1}^n \\theta_i^{y_i}(1-\\theta_i)^{1-y_i}.$$
\n$$P(y_1,\\dots,y_n) = \\int\\!\\!\\cdots\\!\\!\\int \\prod_{i=1}^n \\Big[\\theta_i^{y_i}(1-\\theta_i)^{1-y_i} f(\\theta_i)\\Big]\\, d\\theta_1\\cdots d\\theta_n.$$
\n$$P(y_1,\\dots,y_n) = \\int_0^1 \\theta_1^{y_1}(1-\\theta_1)^{1-y_1}f(\\theta_1)\\,d\\theta_1 \\times \\cdots \\times \\int_0^1 \\theta_n^{y_n}(1-\\theta_n)^{1-y_n}f(\\theta_n)\\,d\\theta_n.$$
\n$$P(y_1,\\dots,y_n) = \\prod_{i=1}^n \\mu^{y_i}(1-\\mu)^{1-y_i} \\quad\\Longrightarrow\\quad y_1,\\dots,y_n \\overset{iid}{\\sim} \\text{Bernoulli}(\\mu).$$
\nNext, we can see $\\bar y$ is unbiased:
\n$$E[y_i\\mid\\theta_i] = 1\\cdot\\theta_i + 0\\cdot(1-\\theta_i) = \\theta_i$$\n$$E[y_i] = E\\big[\\,E[y_i\\mid\\theta_i]\\,\\big] = E[\\theta_i] = \\mu.$$\n$$E[\\bar y] = \\frac1n\\sum_{i=1}^n E[y_i] = \\frac1n\\cdot n\\mu = \\mu$$
\nNow for the variance:
\n$$\\sigma_y^2 = \\text{Var}(y_i) = \\underbrace{E[\\text{Var}(y_i\\mid\\theta_i)]}_{\\text{within}} + \\underbrace{\\text{Var}(E[y_i\\mid\\theta_i])}_{\\text{between}} = E[\\theta_i(1-\\theta_i)] + \\tau^2.$$
\n$$\\tau^2 = E[\\theta_i^2] - \\mu^2$$\n$$\\sigma_y^2 = \\big(\\mu - E[\\theta_i^2]\\big) + \\big(E[\\theta_i^2] - \\mu^2\\big) = \\mu(1-\\mu).$$
\nFor variance of the mean (0 covariance):
\n$$\\text{Var}(\\bar y) = \\frac{1}{n^2}\\sum_{i=1}^n \\text{Var}(y_i) = \\frac{1}{n^2}\\cdot n\\sigma_y^2 = \\frac{\\sigma_y^2}{n} = \\frac{\\mu(1-\\mu)}{n}.$$
\nFinally, we can see that $S^2$ is unbiased for $\\sigma_y^2$.
\nThe sample variance is:\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^n (y_i-\\bar y)^2.$$
\n$$\\sum_{i=1}^n (y_i-\\mu) = \\sum_i y_i - n\\mu = n\\bar y - n\\mu = n(\\bar y-\\mu).$$
\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 - n(\\bar y-\\mu)^2.$$
\nTherefore\n$$E\\Big[\\sum_i (y_i-\\bar y)^2\\Big] = n\\sigma_y^2 - n\\cdot\\frac{\\sigma_y^2}{n} = (n-1)\\sigma_y^2 \\quad\\Longrightarrow\\quad E[S^2] = \\sigma_y^2$$
\nFor 0/1 data, $y_i^2 = y_i$, and $S^2$ simplifies to $\\dfrac{n}{n-1}\\,\\bar y(1-\\bar y)$.
\nSo it seems that at $k=1$, we can estimate the population mean and variance of the mean estimator.
\n", "answer_id": 677265, "answer_text": "After thinking about this, I think I know how to do this. When $k=1$, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.\n\n\n\n\nHowever, it is possible to estimate the variance of the mean estimator at $k=1$.\n\n\n\n\nLet each unit have $\\theta_i \\overset{iid}{\\sim} \\text{Beta}(\\alpha,\\beta)$ with density $f(\\theta)$. Each unit is observed once ($k=1$), so $y_i \\mid \\theta_i \\sim \\text{Bernoulli}(\\theta_i)$:\n\n\n\n\n\n$\\mu = E[\\theta_i]$ — population mean (the target) and is $\\mu = \\frac{\\alpha}{\\alpha+\\beta}$\n\n\n\n\n\n\n$\\tau^2 = \\operatorname{Var}(\\theta_i)$ — population variance and is = $\\tau^2 = \\frac{\\mu(1-\\mu)}{\\alpha+\\beta+1}$\n\n\n\n\n\n\n$\\sigma_y^2 = \\operatorname{Var}(y_i)$\n\n\n\n\n\nFor a single unit, the Bernoulli distribution:\n$$P(y\\mid\\theta) = \\theta^{y}(1-\\theta)^{1-y}.$$\n\n\n\n\nTo marginalize the distribution:\n\n\n\n\n$$P(y_i=1) = \\int_0^1 \\theta\\, f(\\theta)\\,d\\theta = E[\\theta_i] = \\mu$$\n$$\\qquad P(y_i=0) = \\int_0^1 (1-\\theta)\\, f(\\theta)\\,d\\theta = 1-\\mu.$$\n\n\n\n\n$$y_i \\sim \\text{Bernoulli}(\\mu) = P(y_i = y) = \\mu^{y}(1-\\mu)^{1-y}$$\n\n\n\n\nThe iid assumption makes it easy to extend this to $n$ machines:\n\n\n\n\n$$P(y_1,\\dots,y_n \\mid \\theta_1,\\dots,\\theta_n) = \\prod_{i=1}^n \\theta_i^{y_i}(1-\\theta_i)^{1-y_i}.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\int\\!\\!\\cdots\\!\\!\\int \\prod_{i=1}^n \\Big[\\theta_i^{y_i}(1-\\theta_i)^{1-y_i} f(\\theta_i)\\Big]\\, d\\theta_1\\cdots d\\theta_n.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\int_0^1 \\theta_1^{y_1}(1-\\theta_1)^{1-y_1}f(\\theta_1)\\,d\\theta_1 \\times \\cdots \\times \\int_0^1 \\theta_n^{y_n}(1-\\theta_n)^{1-y_n}f(\\theta_n)\\,d\\theta_n.$$\n\n\n\n\n$$P(y_1,\\dots,y_n) = \\prod_{i=1}^n \\mu^{y_i}(1-\\mu)^{1-y_i} \\quad\\Longrightarrow\\quad y_1,\\dots,y_n \\overset{iid}{\\sim} \\text{Bernoulli}(\\mu).$$\n\n\n\n\nNext, we can see $\\bar y$ is unbiased:\n\n\n\n\n$$E[y_i\\mid\\theta_i] = 1\\cdot\\theta_i + 0\\cdot(1-\\theta_i) = \\theta_i$$\n$$E[y_i] = E\\big[\\,E[y_i\\mid\\theta_i]\\,\\big] = E[\\theta_i] = \\mu.$$\n$$E[\\bar y] = \\frac1n\\sum_{i=1}^n E[y_i] = \\frac1n\\cdot n\\mu = \\mu$$\n\n\n\n\nNow for the variance:\n\n\n\n\n$$\\sigma_y^2 = \\text{Var}(y_i) = \\underbrace{E[\\text{Var}(y_i\\mid\\theta_i)]}_{\\text{within}} + \\underbrace{\\text{Var}(E[y_i\\mid\\theta_i])}_{\\text{between}} = E[\\theta_i(1-\\theta_i)] + \\tau^2.$$\n\n\n\n\n$$\\tau^2 = E[\\theta_i^2] - \\mu^2$$\n$$\\sigma_y^2 = \\big(\\mu - E[\\theta_i^2]\\big) + \\big(E[\\theta_i^2] - \\mu^2\\big) = \\mu(1-\\mu).$$\n\n\n\n\nFor variance of the mean (0 covariance):\n\n\n\n\n$$\\text{Var}(\\bar y) = \\frac{1}{n^2}\\sum_{i=1}^n \\text{Var}(y_i) = \\frac{1}{n^2}\\cdot n\\sigma_y^2 = \\frac{\\sigma_y^2}{n} = \\frac{\\mu(1-\\mu)}{n}.$$\n\n\n\n\nFinally, we can see that $S^2$ is unbiased for $\\sigma_y^2$.\n\n\n\n\nThe sample variance is:\n$$S^2 = \\frac{1}{n-1}\\sum_{i=1}^n (y_i-\\bar y)^2.$$\n\n\n\n\n\n$\\bar y = \\frac1n\\sum_i y_i$ means $\\sum_i y_i = n\\bar y$.\n\n\n\n\nA constant $\\mu$ summed $n$ times is $n\\mu$.\n\n\n\n\n\n$$\\sum_{i=1}^n (y_i-\\mu) = \\sum_i y_i - n\\mu = n\\bar y - n\\mu = n(\\bar y-\\mu).$$\n\n\n\n\n\n$y_i - \\bar y = (y_i-\\mu) - (\\bar y-\\mu)$:\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 \\;-\\; 2(\\bar y-\\mu)\\underbrace{\\sum_i (y_i-\\mu)}_{=\\,n(\\bar y-\\mu)} \\;+\\; n(\\bar y-\\mu)^2.$$\n\n\n\n\n\n$$\\sum_i (y_i-\\bar y)^2 = \\sum_i (y_i-\\mu)^2 - n(\\bar y-\\mu)^2.$$\n\n\n\n\n\n$E[(y_i-\\mu)^2] = \\sigma_y^2$\n\n\n\n\n$E[(\\bar y-\\mu)^2] = \\text{Var}(\\bar y) = \\sigma_y^2/n$\n\n\n\n\n\nTherefore\n$$E\\Big[\\sum_i (y_i-\\bar y)^2\\Big] = n\\sigma_y^2 - n\\cdot\\frac{\\sigma_y^2}{n} = (n-1)\\sigma_y^2 \\quad\\Longrightarrow\\quad E[S^2] = \\sigma_y^2$$\n\n\n\n\nFor 0/1 data, $y_i^2 = y_i$, and $S^2$ simplifies to $\\dfrac{n}{n-1}\\,\\bar y(1-\\bar y)$.\n\n\n\n\nSo it seems that at $k=1$, we can estimate the population mean and variance of the mean estimator.", "answer_url": "https://stats.stackexchange.com/a/677265", "author": "adamkostanov", "author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T17:44:30+00:00", "is_accepted": false, "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": 677226, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-25T17:44:30+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "A2509D36-CE80-4C0F-BA28-5077E22D040B", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A2509D36-CE80-4C0F-BA28-5077E22D040B/view-source"}], "score": 0, "updated_at": "2026-09-25T17:44:30+00:00"}], "domain": "statistics", "external_links": ["https://en.wikipedia.org/wiki/Beta-binomial_distribution", "https://i.sstatic.net/BHmL9Quz.png", "https://i.sstatic.net/cWGh2esg.png", "https://i.sstatic.net/wine4qeY.png"], "medical_sensitive": false, "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": "adamkostanov", "question_author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "question_author_user_type": "registered", "question_created_at": "2026-09-21T00:41:19+00:00", "question_html": "Here is a hierarchical data generating process:
\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$
\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$
\n
There are two cases - Case 1 is where you sample 1 observation per subject and Case 2 where you sample multiple observations per subject:
\n\nI am only interested in estimating the population level mean and variance. Can this still be done in Case 1?
\nI am guessing that there will be no problems doing this for Case 2. For Case 1, I am guessing there won't be any problems for estimating the population level mean, but I am not sure if the population level variance can still be estimated since we do not observe variation at the individual level (regardless of whether moments are used or MLE).
\nset.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste("Subject", 1:n), levels = paste("Subject", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n) {\n theta[i] <- rbeta(1, alpha, beta)\n}\n\n# Case 1 \ncase1 <- numeric(n)\nfor (i in 1:n) {\n case1[i] <- rbinom(1, 1, theta[i]) \n}\n\n# Case 2 \ncase2 <- matrix(NA, nrow = k, ncol = n) \nfor (i in 1:n) {\n for (j in 1:k) {\n case2[j, i] <- rbinom(1, 1, theta[i])\n }\n}\n\nd1 <- data.frame(subject = subjects, true = theta, meas = case1)\nd2 <- data.frame(subject = rep(subjects, each = k),\n true = rep(theta, each = k),\n meas = as.vector(case2))\nred2 <- data.frame(subject = subjects, true = theta)\n\n", "question_id": 677226, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "Here is a hierarchical data generating process:\n\n\n\n\n\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$\n\n\n\n\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$\n\n\n\n\n\n\n\nThere are two cases - Case 1 is where you sample 1 observation per subject and Case 2 where you sample multiple observations per subject:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/wine4qeY.png] (https://i.sstatic.net/wine4qeY.png)\n\n\n\n\nI am only interested in estimating the population level mean and variance. Can this still be done in Case 1?\n\n\n\n\nI am guessing that there will be no problems doing this for Case 2. For Case 1, I am guessing there won't be any problems for estimating the population level mean, but I am not sure if the population level variance can still be estimated since we do not observe variation at the individual level (regardless of whether moments are used or MLE).\n\n\n\n\n\n\n\nset.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste(\"Subject\", 1:n), levels = paste(\"Subject\", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n) {\n theta[i] <- rbeta(1, alpha, beta)\n}\n\n# Case 1 \ncase1 <- numeric(n)\nfor (i in 1:n) {\n case1[i] <- rbinom(1, 1, theta[i]) \n}\n\n# Case 2 \ncase2 <- matrix(NA, nrow = k, ncol = n) \nfor (i in 1:n) {\n for (j in 1:k) {\n case2[j, i] <- rbinom(1, 1, theta[i])\n }\n}\n\nd1 <- data.frame(subject = subjects, true = theta, meas = case1)\nd2 <- data.frame(subject = rep(subjects, each = k),\n true = rep(theta, each = k),\n meas = as.vector(case2))\nred2 <- data.frame(subject = subjects, true = theta)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-21T00:41:19+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C1F4E2FF-471E-47A5-928D-F6B0A4681FF3", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C1F4E2FF-471E-47A5-928D-F6B0A4681FF3/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "kjetil b halvorsen", "profile_url": "https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen", "user_type": "moderator"}, "created_at": "2026-09-21T04:23:57+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "19D572A4-437C-42C9-8FEE-FD0F08D0BE8B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/19D572A4-437C-42C9-8FEE-FD0F08D0BE8B/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-21T04:41:49+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "AD8437EA-1725-4DAB-8174-F56009F767F0", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD8437EA-1725-4DAB-8174-F56009F767F0/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-22T01:12:54+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "75227B37-0244-4E58-846B-06B8FB1C54FF", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/75227B37-0244-4E58-846B-06B8FB1C54FF/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677226/is-variance-still-estimable-when-you-observe-a-single-observation-per-subject", "split": "train", "split_group": "9dd25a7f286d352daa4453c364e35088a292dc3acf798487781b158dd5e6996b", "tags": ["probability", "sampling", "estimation", "mean"], "thread_id": "stats:677226", "title": "Is variance still estimable when you observe a single observation per subject?"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "dat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = \"days\")\n)\nThis\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677242, "sha256": "578bb120659315b5f683555f2dd22808cb76a10c82324e2ddfd65df2d0aeea9e", "source_url": "https://stats.stackexchange.com/questions/677242/modeling-within-day-and-across-day-correlations-using-car1-with-repeated-measu"}, {"block_index": 1, "code_text": "model <- gls(\n SBP ~ treatment + day,\n correlation = corCAR1(form = ~ t_elapsed),\n data = dat\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677242, "sha256": "2f3492ec43226c6b22fc018d5bd673083aa32387dc5110cb28418f8f9cd7695f", "source_url": "https://stats.stackexchange.com/questions/677242/modeling-within-day-and-across-day-correlations-using-car1-with-repeated-measu"}], "other_answers": [], "product": "code_qa", "question": "I am running an experiment in which 1 participant is randomized multiple times to different treatments, and we are assessing the effect of treatment on blood pressure (BP).\n\n\n\n\nThe data collection protocol is as follows:\n\n\n\n\n• BP is measured every day at two time points: 12:00 and 20:00, for approximately 3 months.\n\n\n\n\n• At each time point, BP is measured twice, exactly 1 minute apart.\n\n\n\n\nData structure\n\n\n\n\n\n\n\n\n\nday\ntime\nrep\ndatetime\nSBP\n\n\n\n\n\n\n\n\n\t1\n\t12:00\n\t1\n\t2026-01-01 12:00\n\t122\n\n\n\n\n\n\n\t1\n\t12:00\n\t2\n\t2026-01-01 12:01\n\t121\n\n\n\n\n\n\n\t1\n\t20:00\n\t1\n\t2026-01-01 20:00\n\t128\n\n\n\n\n\n\n\t1\n\t20:00\n\t2\n\t2026-01-01 20:01\n\t127\n\n\n\n\n\n\n\t2\n\t12:00\n\t1\n\t2026-01-02 12:00\n\t120\n\n\n\n\n\n\n\t2\n\t12:00\n\t2\n\t2026-01-02 12:01\n\t119\n\n\n\n\n\n\n\t2\n\t20:00\n\t1\n\t2026-01-02 20:00\n\t130\n\n\n\n\n\n\n\t2\n\t20:00\n\t2\n\t2026-01-02 20:01\n\t129\n\n\n\n\n\n\n\n\n\nI then calculate elapsed time from the first observation:\n\n\n\n\ndat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = \"days\")\n)\nThis\n\n\n\n\n\ngives approximately:\n0, 0.00069, 0.3333, 0.3340,\n1, 1.00069, 1.3333, 1.3340, ...\ni.e., the actual elapsed time between observations, expressed in days.\n\n\n\n\nI was considering the following model:\n\n\n\n\nmodel <- gls(\n SBP ~ treatment + day,\n correlation = corCAR1(form = ~ t_elapsed),\n data = dat\n)\n\n\n\n\n\nQuestions\n\n\n\n\n\nIs calculating t_elapsed an appropriate way to specify the time variable for corCAR1()?\n\n\n\n\nMore generally, is CAR(1) an appropriate correlation structure for these data, given that I have both very closely spaced repeated measurements (1 minute apart) and measurements separated by approximately 8 or 16 hours?\n\n\n\n\nWould you recommend an alternative correlation structure or modeling strategy for this design?\n\n\n\n\n\nThank you!", "record_id": "Scientific-Code-and-Analysis-QA:stats:677242", "selected_answer": {"answer_html": "I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the corCAR1 correlation structure.
If day is treated as continuous, your model implicitly assumes it has a linear association with BP. That's unlikely to hold. If it's treated as a factor, you have a lot of coefficients to estimate. Flexible fitting with regression splines or other generalized additive models is a good intermediate choice for modeling time.
The model also assumes that associations of day and treatment with BP are additive. Is that likely, based on your understanding of the subject matter? If not, include an interaction between them.
I don't see an advantage to using day as a time scale in addition to t_elapsed. I'd just use t_elapsed as the predictor for time scale, as that includes information about day.
I suspect that there will be a circadian difference between 1200 and 2000 hours. The model should take that into account.
\nChapter 7 of Frank Harrell's Regression Modeling Strategies covers generalized least squares for this type of study in some detail. Read it before you go any farther in your analysis.
\n", "answer_id": 677249, "answer_text": "I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the corCAR1 correlation structure.\n\n\n\n\nIf day is treated as continuous, your model implicitly assumes it has a linear association with BP. That's unlikely to hold. If it's treated as a factor, you have a lot of coefficients to estimate. Flexible fitting with regression splines or other generalized additive models is a good intermediate choice for modeling time.\n\n\n\n\nThe model also assumes that associations of day and treatment with BP are additive. Is that likely, based on your understanding of the subject matter? If not, include an interaction between them.\n\n\n\n\nI don't see an advantage to using day as a time scale in addition to t_elapsed. I'd just use t_elapsed as the predictor for time scale, as that includes information about day.\n\n\n\n\nI suspect that there will be a circadian difference between 1200 and 2000 hours. The model should take that into account.\n\n\n\n\nChapter 7 of Frank Harrell's Regression Modeling Strategies (https://hbiostat.org/rmsc/long) covers generalized least squares for this type of study in some detail. Read it before you go any farther in your analysis.", "answer_url": "https://stats.stackexchange.com/a/677249", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-23T20:10:25+00:00", "is_accepted": false, "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": 677242, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-23T20:10:25+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "49CEC78F-CB41-47B6-A537-4E122B99B13A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49CEC78F-CB41-47B6-A537-4E122B99B13A/view-source"}], "score": 3, "updated_at": "2026-09-23T20:10:25+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the corCAR1 correlation structure.
If day is treated as continuous, your model implicitly assumes it has a linear association with BP. That's unlikely to hold. If it's treated as a factor, you have a lot of coefficients to estimate. Flexible fitting with regression splines or other generalized additive models is a good intermediate choice for modeling time.
The model also assumes that associations of day and treatment with BP are additive. Is that likely, based on your understanding of the subject matter? If not, include an interaction between them.
I don't see an advantage to using day as a time scale in addition to t_elapsed. I'd just use t_elapsed as the predictor for time scale, as that includes information about day.
I suspect that there will be a circadian difference between 1200 and 2000 hours. The model should take that into account.
\nChapter 7 of Frank Harrell's Regression Modeling Strategies covers generalized least squares for this type of study in some detail. Read it before you go any farther in your analysis.
\n", "answer_id": 677249, "answer_text": "I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the corCAR1 correlation structure.\n\n\n\n\nIf day is treated as continuous, your model implicitly assumes it has a linear association with BP. That's unlikely to hold. If it's treated as a factor, you have a lot of coefficients to estimate. Flexible fitting with regression splines or other generalized additive models is a good intermediate choice for modeling time.\n\n\n\n\nThe model also assumes that associations of day and treatment with BP are additive. Is that likely, based on your understanding of the subject matter? If not, include an interaction between them.\n\n\n\n\nI don't see an advantage to using day as a time scale in addition to t_elapsed. I'd just use t_elapsed as the predictor for time scale, as that includes information about day.\n\n\n\n\nI suspect that there will be a circadian difference between 1200 and 2000 hours. The model should take that into account.\n\n\n\n\nChapter 7 of Frank Harrell's Regression Modeling Strategies (https://hbiostat.org/rmsc/long) covers generalized least squares for this type of study in some detail. Read it before you go any farther in your analysis.", "answer_url": "https://stats.stackexchange.com/a/677249", "author": "EdM", "author_url": "https://stats.stackexchange.com/users/28500/edm", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-23T20:10:25+00:00", "is_accepted": false, "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": 677242, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "EdM", "profile_url": "https://stats.stackexchange.com/users/28500/edm", "user_type": "registered"}, "created_at": "2026-09-23T20:10:25+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "49CEC78F-CB41-47B6-A537-4E122B99B13A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/49CEC78F-CB41-47B6-A537-4E122B99B13A/view-source"}], "score": 3, "updated_at": "2026-09-23T20:10:25+00:00"}], "domain": "statistics", "external_links": ["https://hbiostat.org/rmsc/long"], "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": "jtjtjtjt", "question_author_url": "https://stats.stackexchange.com/users/393112/jtjtjtjt", "question_author_user_type": "registered", "question_created_at": "2026-09-23T09:07:44+00:00", "question_html": "I am running an experiment in which 1 participant is randomized multiple times to different treatments, and we are assessing the effect of treatment on blood pressure (BP).
\nThe data collection protocol is as follows:
\n• BP is measured every day at two time points: 12:00 and 20:00, for approximately 3 months.
\n• At each time point, BP is measured twice, exactly 1 minute apart.
\nData structure
\n| day | \ntime | \nrep | \ndatetime | \nSBP | \n
|---|---|---|---|---|
| 1 | \n12:00 | \n1 | \n2026-01-01 12:00 | \n122 | \n
| 1 | \n12:00 | \n2 | \n2026-01-01 12:01 | \n121 | \n
| 1 | \n20:00 | \n1 | \n2026-01-01 20:00 | \n128 | \n
| 1 | \n20:00 | \n2 | \n2026-01-01 20:01 | \n127 | \n
| 2 | \n12:00 | \n1 | \n2026-01-02 12:00 | \n120 | \n
| 2 | \n12:00 | \n2 | \n2026-01-02 12:01 | \n119 | \n
| 2 | \n20:00 | \n1 | \n2026-01-02 20:00 | \n130 | \n
| 2 | \n20:00 | \n2 | \n2026-01-02 20:01 | \n129 | \n
I then calculate elapsed time from the first observation:
\ndat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = "days")\n)\nThis\n\ngives approximately:\n0, 0.00069, 0.3333, 0.3340,\n1, 1.00069, 1.3333, 1.3340, ...\ni.e., the actual elapsed time between observations, expressed in days.
\nI was considering the following model:
\nmodel <- gls(\n SBP ~ treatment + day,\n correlation = corCAR1(form = ~ t_elapsed),\n data = dat\n)\n\nQuestions
\nThank you!
\n", "question_id": 677242, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am running an experiment in which 1 participant is randomized multiple times to different treatments, and we are assessing the effect of treatment on blood pressure (BP).\n\n\n\n\nThe data collection protocol is as follows:\n\n\n\n\n• BP is measured every day at two time points: 12:00 and 20:00, for approximately 3 months.\n\n\n\n\n• At each time point, BP is measured twice, exactly 1 minute apart.\n\n\n\n\nData structure\n\n\n\n\n\n\n\n\n\nday\ntime\nrep\ndatetime\nSBP\n\n\n\n\n\n\n\n\n\t1\n\t12:00\n\t1\n\t2026-01-01 12:00\n\t122\n\n\n\n\n\n\n\t1\n\t12:00\n\t2\n\t2026-01-01 12:01\n\t121\n\n\n\n\n\n\n\t1\n\t20:00\n\t1\n\t2026-01-01 20:00\n\t128\n\n\n\n\n\n\n\t1\n\t20:00\n\t2\n\t2026-01-01 20:01\n\t127\n\n\n\n\n\n\n\t2\n\t12:00\n\t1\n\t2026-01-02 12:00\n\t120\n\n\n\n\n\n\n\t2\n\t12:00\n\t2\n\t2026-01-02 12:01\n\t119\n\n\n\n\n\n\n\t2\n\t20:00\n\t1\n\t2026-01-02 20:00\n\t130\n\n\n\n\n\n\n\t2\n\t20:00\n\t2\n\t2026-01-02 20:01\n\t129\n\n\n\n\n\n\n\n\n\nI then calculate elapsed time from the first observation:\n\n\n\n\ndat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = \"days\")\n)\nThis\n\n\n\n\n\ngives approximately:\n0, 0.00069, 0.3333, 0.3340,\n1, 1.00069, 1.3333, 1.3340, ...\ni.e., the actual elapsed time between observations, expressed in days.\n\n\n\n\nI was considering the following model:\n\n\n\n\nmodel <- gls(\n SBP ~ treatment + day,\n correlation = corCAR1(form = ~ t_elapsed),\n data = dat\n)\n\n\n\n\n\nQuestions\n\n\n\n\n\nIs calculating t_elapsed an appropriate way to specify the time variable for corCAR1()?\n\n\n\n\nMore generally, is CAR(1) an appropriate correlation structure for these data, given that I have both very closely spaced repeated measurements (1 minute apart) and measurements separated by approximately 8 or 16 hours?\n\n\n\n\nWould you recommend an alternative correlation structure or modeling strategy for this design?\n\n\n\n\n\nThank you!", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "jtjtjtjt", "profile_url": "https://stats.stackexchange.com/users/393112/jtjtjtjt", "user_type": "registered"}, "created_at": "2026-09-23T09:07:44+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "F6683031-BCCB-4D54-BBE3-456E3642AC0F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F6683031-BCCB-4D54-BBE3-456E3642AC0F/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-24T01:29:33+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "4E6C2681-2FA3-4F04-87F3-25F3A9004AFC", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/4E6C2681-2FA3-4F04-87F3-25F3A9004AFC/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677242/modeling-within-day-and-across-day-correlations-using-car1-with-repeated-measu", "split": "train", "split_group": "f33a429b362ffdcdd327a936bb1a7b486e9a3a3e1d3c84d34deb198a0b0393f5", "tags": ["lme4-nlme", "autoregressive", "generalized-least-squares"], "thread_id": "stats:677242", "title": "Modeling within-day and across-day correlations using CAR(1) with repeated measurements"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "ratlong <- read.csv(\"ratlong.csv\") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n weights = varIdent(form = ~ 1 | time),\n na.action = na.exclude,\n method = \"REML\",\n data = ratlong)\n\nsummary(model)\nparameters(model)\ngetVarCov(model)\n\ntmp <- mutate(\n ratlong,\n fit = fitted(model),\n response = residuals(model, type = \"r\"),\n pearson = residuals(model, type = \"p\"),\n norm_res_R = residuals(model, type = \"n\"),\n norm_res_stata = c(\n -.3343025, .5268827, .4992422, .0732094, .8447663,\n -.3185105, -.2071171, 1.274912, .7114518, 1.215278,\n -.5135215, .0203645, -.5228509, -.8512383, 1.808096,\n .4581496, -1.22478, -.9106107, -.7130803, .2519478,\n .3804444, .2287333, .9784756, -.3758776, -.7113822,\n -1.475303, -1.399477, -1.504103, 1.288807, -.5631775,\n .473786, -.4318775, .5628197, -1.065117, -1.452405,\n .9371732, 1.274058, .9912707, .9466597, -.4890752,\n .1423321, .311183, -.8122606, -.5272216, -1.526507,\n .2497523, .9020303, -.556895, .5124069, .6224594,\n .8534008, -1.234297, .7109886, 1.567964, .3556911,\n 1.202434, -.9995003, .4767818, .8310238, -.1630251,\n -.7255811, -.987914, 1.937267, -1.758109, .6521003,\n -1.101692, 2.462107, .2542622, .8310238, -.1630251,\n -1.298645, -.3421695, -1.104759, .5448185, 1.170816,\n -1.124267, .0387734, .6711161, -.8830101, -.385332,\n .2229622, -.5032972, .0853191, 1.314626, -1.200457,\n 2.574736, .5105642, -1.381145, -.8254197, 1.170816,\n -.5026115, -.0627333, -.9601486, -1.083703, -1.27456,\n -.1007365, 1.118466, -.6896819, -.5392144, -.1630251)\n)\n\n# Here we observe that the pearson residual is approximately equal to the \n# normalized at time 1 for R and time 5 for stata\ntmp$pearson[seq(5, nrow(ratlong), 5)] - \n tmp$norm_res_stata[seq(5, nrow(ratlong), 5)]\ntmp$pearson[seq(1, nrow(ratlong), 5)] - \n tmp$norm_res_R[seq(1, nrow(ratlong), 5)]\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "d16b7b9cab3fd8d94d48e1eab2bd8bc38880d968e38079852a04a215d3fdf1f5", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 1, "code_text": "#### from residuals.gls\nval <- object$residuals\nif (type != \"response\") {\n val <- val/attr(val, \"std\")\n lab <- \"Standardized residuals\"\n if (type == \"normalized\") {\nif (!is.null(cSt <- object$modelStruct$corStruct)) {\n ## normalize according to inv-trans factor\n val <- recalc(cSt, list(Xy = as.matrix(val)))$Xy[, 1]\n lab <- \"Normalized residuals\"\n }\n }\n}\n \n#### from recalc.corSymm\nrecalc.corSymm <- function(object, conLin, ...)\n{\n val <-\n .C(symm_recalc,\n Xy = as.double(conLin[[\"Xy\"]]),\n as.integer(unlist(Dim(object))),\n as.integer(ncol(conLin[[\"Xy\"]])),\n as.double(as.vector(object)),\n as.integer(unlist(getCovariate(object))),\n as.integer(attr(object, \"maxCov\")),\n logLik = double(1))[c(\"Xy\", \"logLik\")]\n conLin[[\"Xy\"]][] <- val[[\"Xy\"]]\n conLin[[\"logLik\"]] <- conLin[[\"logLik\"]] + val[[\"logLik\"]]\n conLin\n}\n \n#### from symm_recalc (written in C)\nvoid\nsymm_recalc(double *Xy, int *pdims, int *ZXcol, double *pars,\n int *time, int *maxC, double *logdet)\n{\n int N = pdims[0], M = pdims[1], *len = pdims + 4, *start = len + M, i;\n double *crr = R_Calloc(*maxC * (*maxC - 1) / 2, double);\n /* parameters assumed in unconstrained form */\n symm_fullCorr(pars, maxC, crr); /* get all correlations (not correlation \n matrix) */\n for(i = 0; i < M; i++) {\n double *Factor = R_Calloc((len[i] * len[i]), double);\n symm_fact(crr, time + start[i], &len[i], maxC, Factor, logdet);\n mult_mat(Xy + start[i], N, Factor, len[i], len[i], len[i],\n Xy + start[i], N, *ZXcol);\n R_Free(Factor);\n }\n R_Free(crr);\n}\n \n#### from symm_fact (also written in C)\nstatic void\nsymm_fact(double *crr, int *time, int *n, int *maxC, double *mat,\n double *logdet)\n{\n int job = 11L, info, i, nsq = *n * (*n), np1 = *n + 1;\n double *work = R_Calloc(*n, double), *work1 = R_Calloc(nsq, double);\n symm_mat(crr, time, n, maxC, mat); /* make full symmetric correlation \n matrix for individual i */\n F77_CALL(chol) (mat, n, n, mat, &info); /* Cholesky decomposition */\n for(i = 0; i < *n; i++) {\n work1[i * np1] = 1; /* set diag to 1 in empty matrix (i.e. create \n identity matrix) */\n F77_CALL(dtrsl) (mat, n, n, work1 + i * (*n), &job, &info); /* solves \n linear system given triangular matrix */\n *logdet -= log(fabs(mat[i * np1]));\n }\n Memcpy(mat, work1, nsq); \n R_Free(work); R_Free(work1);\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "1176928f21235d5581ed36d45020fcbdc07f6bf1c471d16d1c4e04a0f4b28e3b", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 2, "code_text": "# regular Cholesky algorithm (same as t(chol) for base R's chol function)\n regChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in 1:n){\n if (j == 1){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[j,1:(j-1)]^2))\n }\n if (j == 1){\n for (i in (j+1):n){\n L[i,j] = A[i,j]/L[j,j]\n }\n } else if (j < n){\n for (i in (j+1):n){\n L[i,j] = (A[i,j]-sum(L[i,1:(j-1)]*L[j,1:(j-1)]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \n # reverse Cholesky algorithm\n revChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \ncorMat <- model$modelStruct$corStruct #correlation structure of type corSymm\n \npdims <- as.integer(unlist(Dim(corMat))) #dimensions of correlation matrices\ncorMatFull <- corMatrix(corMat) #full correlation matrix\n ############################################################################\n#### Compute normalized residuals\n\n# `Using reverse Cholesky decomposition (gives same values as stata)\n\nnormres1 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n L <- revChol(A) # lower triangular / square root\n invSqLambda <- solve(t(L)) # invert L -- if regular Cholesky: use solve(L)\n normres1[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nt(L) %*% L #returns correlation matrix A given reversed Cholesky\n\n#Using regular Cholesky decomposition (gives same values as R)\nnormres2 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) #correlation matrix\n L <- t(chol(A)) \n # lower triangular / square root -- note that regChol(A) = t(chol(A))\n invSqLambda <- solve(L) # invert L -- if regular Cholesky: use solve(L)\n normres2[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nL %*% t(L) #returns correlation matrix given standard Cholesky\n\n# Using EVD\nnormres3 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] # observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) # total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n E <- eigen(A) # EVD eigenvalue decomposition\n sqrtA <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors) \n# matrix square root\n invSqLambda <- solve(sqrtA) # invert sqrtA\n normres3[dim2:(dim2 + dim-1)] <- \ninvSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\n\nround(normres1 - tmp$norm_res_stata, digits = 5) \n# approx 0 when using reverse Cholesky\nround(normres2 - tmp$norm_res_R, digits = 15) \n # approx 0 when using regular Cholesky\n \n##### will add qqplots/histograms with results in a couple of days\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "9a21afd8ff3f46329eca76d130ff8d31f81d0bf73f64afa0c0ad11aaefecf166", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 3, "code_text": "plot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(sample = tmp$norm_res_stata)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals stata\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(sample = tmp$norm_res_R)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals R\")\nplot3 <- ggplot(as.data.frame(normres3), aes(sample = normres3)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(x = tmp$norm_res_stata)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals stata (reverse Cholesky)\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(x = tmp$norm_res_R)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals R (standard Cholesky)\")\nplot3 <- ggplot(as.data.frame(normres3), aes(x = normres3)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "ffcbbb7f5fc811690de3c48395eef18d329c348bdd513fae9603d1b7608a1d66", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 4, "code_text": ". \n. \n. import delim \"ratlong.csv\", clear \n(encoding automatically selected: ISO-8859-1)\n(5 vars, 100 obs)\n\n. \n. mixed weight b1.group##b0.time || rat: , reml baselev nocons res(un, t(time))\n\nPerforming gradient-based optimization: \nIteration 0: Log restricted-likelihood = -346.35796 (not concave)\nIteration 1: Log restricted-likelihood = -284.80839 (not concave)\nIteration 2: Log restricted-likelihood = -281.13028 \nIteration 3: Log restricted-likelihood = -278.4598 \nIteration 4: Log restricted-likelihood = -276.85378 \nIteration 5: Log restricted-likelihood = -276.76319 \nIteration 6: Log restricted-likelihood = -276.76264 \nIteration 7: Log restricted-likelihood = -276.76264 \n\nComputing standard errors ...\n\nMixed-effects REML regression Number of obs = 100\nGroup variable: rat Number of groups = 20\n Obs per group:\n min = 5\n avg = 5.0\n max = 5\n Wald chi2(9) = 1277.34\nLog restricted-likelihood = -276.76264 Prob > chi2 = 0.0000\n\n------------------------------------------------------------------------------\n weight | Coefficient Std. err. z P>|z| [95% conf. interval]\n-------------+----------------------------------------------------------------\n group |\n 1 | 0 (base)\n 3 | .7 2.270827 0.31 0.758 -3.75074 5.15074\n |\n time |\n 0 | 0 (base)\n 1 | 24.5 1.61744 15.15 0.000 21.32988 27.67012\n 2 | 52 2.045184 25.43 0.000 47.99151 56.00849\n 3 | 76.1 3.11002 24.47 0.000 70.00447 82.19553\n 4 | 106.6 4.073561 26.17 0.000 98.61597 114.584\n |\n group#time |\n 3 1 | -2.9 2.287405 -1.27 0.205 -7.383232 1.583232\n 3 2 | -10.9 2.892328 -3.77 0.000 -16.56886 -5.231142\n 3 3 | -22.4 4.398233 -5.09 0.000 -31.02038 -13.77962\n 3 4 | -37.1 5.760885 -6.44 0.000 -48.39113 -25.80887\n |\n _cons | 54 1.605717 33.63 0.000 50.85285 57.14715\n------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------\n Random-effects parameters | Estimate Std. err. [95% conf. interval]\n-----------------------------+------------------------------------------------\nrat: (empty) |\n-----------------------------+------------------------------------------------\nResidual: Unstructured |\n var(e0) | 25.78329 8.592901 13.41698 49.54749\n var(e1) | 77.81102 25.92904 40.49434 149.5161\n var(e2) | 85.31105 28.41546 44.41058 163.8793\n var(e3) | 127.9611 42.64015 66.59387 245.8791\n var(e4) | 182.1112 60.70111 94.75779 349.9921\n cov(e0,e1) | 38.7166 13.95059 11.37394 66.05925\n cov(e0,e2) | 34.63327 13.73195 7.719139 61.5474\n cov(e0,e3) | 28.51106 15.09849 -1.081436 58.10355\n cov(e0,e4) | 20.97774 16.87309 -12.09292 54.04839\n cov(e1,e2) | 71.47769 25.52878 21.44219 121.5132\n cov(e1,e3) | 56.73882 27.02632 3.768207 109.7094\n cov(e1,e4) | 42.8555 29.78855 -15.52898 101.24\n cov(e2,e3) | 89.65551 32.42749 26.09881 153.2122\n cov(e2,e4) | 86.18887 35.69784 16.22239 156.1553\n cov(e3,e4) | 136.2 48.21199 41.70625 230.6938\n------------------------------------------------------------------------------\nLR test vs. linear model: chi2(14) = 139.19 Prob > chi2 = 0.0000\n\nNote: The reported degrees of freedom assumes the null hypothesis is not on the boundary of the parameter space. If this is not true, then the\n reported test is conservative.\n\n. \n. predict res, rstandard\n\n. \n. list rat time res, sepby(rat)\n\n +------------------------+\n | rat time res |\n |------------------------|\n 1. | 1 0 -.3343025 |\n 2. | 1 1 .5268827 |\n 3. | 1 2 .4992422 |\n 4. | 1 3 .0732094 |\n 5. | 1 4 .8447663 |\n |------------------------|\n 6. | 2 0 -.3185105 |\n 7. | 2 1 -.2071171 |\n 8. | 2 2 1.274912 |\n 9. | 2 3 .7114518 |\n 10. | 2 4 1.215278 |\n |------------------------|\n 11. | 3 0 -.5135215 |\n 12. | 3 1 .0203645 |\n 13. | 3 2 -.5228509 |\n 14. | 3 3 -.8512383 |\n 15. | 3 4 1.808096 |\n |------------------------|\n 16. | 4 0 .4581496 |\n 17. | 4 1 -1.22478 |\n 18. | 4 2 -.9106107 |\n 19. | 4 3 -.7130803 |\n 20. | 4 4 .2519478 |\n |------------------------|\n 21. | 5 0 .3804444 |\n 22. | 5 1 .2287333 |\n 23. | 5 2 .9784756 |\n 24. | 5 3 -.3758776 |\n 25. | 5 4 -.7113822 |\n |------------------------|\n 26. | 6 0 -1.475303 |\n 27. | 6 1 -1.399477 |\n 28. | 6 2 -1.504103 |\n 29. | 6 3 1.288807 |\n 30. | 6 4 -.5631775 |\n |------------------------|\n 31. | 7 0 .473786 |\n 32. | 7 1 -.4318775 |\n 33. | 7 2 .5628197 |\n 34. | 7 3 -1.065117 |\n 35. | 7 4 -1.452405 |\n |------------------------|\n 36. | 8 0 .9371732 |\n 37. | 8 1 1.274058 |\n 38. | 8 2 .9912707 |\n 39. | 8 3 .9466597 |\n 40. | 8 4 -.4890752 |\n |------------------------|\n 41. | 9 0 .1423321 |\n 42. | 9 1 .311183 |\n 43. | 9 2 -.8122606 |\n 44. | 9 3 -.5272216 |\n 45. | 9 4 -1.526507 |\n |------------------------|\n 46. | 10 0 .2497523 |\n 47. | 10 1 .9020303 |\n 48. | 10 2 -.556895 |\n 49. | 10 3 .5124069 |\n 50. | 10 4 .6224594 |\n |------------------------|\n 51. | 18 0 .8534008 |\n 52. | 18 1 -1.234297 |\n 53. | 18 2 .7109886 |\n 54. | 18 3 1.567964 |\n 55. | 18 4 .3556911 |\n |------------------------|\n 56. | 19 0 1.202434 |\n 57. | 19 1 -.9995003 |\n 58. | 19 2 .4767818 |\n 59. | 19 3 .8310238 |\n 60. | 19 4 -.1630251 |\n |------------------------|\n 61. | 20 0 -.7255811 |\n 62. | 20 1 -.987914 |\n 63. | 20 2 1.937267 |\n 64. | 20 3 -1.758109 |\n 65. | 20 4 .6521003 |\n |------------------------|\n 66. | 21 0 -1.101692 |\n 67. | 21 1 2.462107 |\n 68. | 21 2 .2542622 |\n 69. | 21 3 .8310238 |\n 70. | 21 4 -.1630251 |\n |------------------------|\n 71. | 22 0 -1.298645 |\n 72. | 22 1 -.3421695 |\n 73. | 22 2 -1.104759 |\n 74. | 22 3 .5448185 |\n 75. | 22 4 1.170816 |\n |------------------------|\n 76. | 23 0 -1.124267 |\n 77. | 23 1 .0387734 |\n 78. | 23 2 .6711161 |\n 79. | 23 3 -.8830101 |\n 80. | 23 4 -.385332 |\n |------------------------|\n 81. | 24 0 .2229622 |\n 82. | 24 1 -.5032972 |\n 83. | 24 2 .0853191 |\n 84. | 24 3 1.314626 |\n 85. | 24 4 -1.200457 |\n |------------------------|\n 86. | 25 0 2.574736 |\n 87. | 25 1 .5105642 |\n 88. | 25 2 -1.381145 |\n 89. | 25 3 -.8254197 |\n 90. | 25 4 1.170816 |\n |------------------------|\n 91. | 26 0 -.5026115 |\n 92. | 26 1 -.0627333 |\n 93. | 26 2 -.9601486 |\n 94. | 26 3 -1.083703 |\n 95. | 26 4 -1.27456 |\n |------------------------|\n 96. | 27 0 -.1007365 |\n 97. | 27 1 1.118466 |\n 98. | 27 2 -.6896819 |\n 99. | 27 3 -.5392144 |\n100. | 27 4 -.1630251 |\n +------------------------+\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "0f6814892fd518ccfd66b2d3fd3de7c87972a02e8f1df59501a03bf1183f280b", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 5, "code_text": "rat <- RatWeight\nnames(rat) <- c(\"Group\", \"Weight0\", \"Weight1\", \"Weight2\", \"Weight3\", \"Weight4\")\nrat$Group <- factor(rat$Group, levels = c(\"Control\", \"Thyroxin\", \"Thiouracil\"))\nrat <- rat[order(rat$Group),]\nrat <- cbind(data.frame(Rat=1:27), rat) |>\n mutate(Rat = factor(Rat))\nrat <- subset(rat, Group != \"Thyroxin\")\nratlong <- rat |> gather(time, Weight, Weight0:Weight4) |>\n separate(time, c(\"W\", \"time\"), sep = 6) |>\n mutate(time = as.factor(as.numeric(time))) |>\n mutate(Group = as.factor(as.numeric(Group))) |>\n mutate(Weight = as.double(Weight))\nratlong <- ratlong[with(ratlong, order(Rat, time, Group)),]\nratlong$Weight[89:90] <- c(116,140)\nwrite.csv(ratlong, \"ratlong.csv\", row.names = FALSE)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "9dddb99f3d3715c6346e0e01f423d9f82af2ef2dd8581704ce4880f0b9c95c48", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 6, "code_text": "library(lme4)\nlibrary(nlme)\nlibrary(haven)\nlibrary(dplyr)\nlibrary(heplots)\nlibrary(parameters)\nlibrary(tidyverse)\nlibrary(gridExtra)\nlibrary(ggplot2)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677243, "sha256": "97a4d9fb1290b82e7755049d7380fb4023cc7c2389da957bef743e9596f48059", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata"}, {"block_index": 0, "code_text": "library(gridExtra)\nlibrary(nlme)\nlibrary(\"mvtnorm\")\nlibrary(\"ggplot2\")\nlibrary(\"dplyr\")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that \"method 1\" is standard Cholesky, \"method 2\" is reverse Cholesky and \"method 3\" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (true Sigma)\")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (true Sigma)\")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (Sigma-hat)\")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (true Sigma)\")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (true Sigma)\")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (Sigma-hat)\")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (Sigma-hat)\")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (true Sigma)\")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (true Sigma)\")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (Sigma-hat)\")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (true Sigma)\")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (true Sigma)\")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (Sigma-hat)\")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (Sigma-hat)\")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677304, "sha256": "ff271d0ac3f1e3f33771e65ded38aff998c5350246f083984483c766cf60b19d", "source_url": "https://stats.stackexchange.com/a/677304"}], "other_answers": [], "product": "code_qa", "question": "I have been tasked with understanding why normalized residuals between R and Stata are different when using mixed models (i.e. the nlme package in R).\n\n\n\n\nWhat I have found is that the residuals are both theoretically computed the same way: norm_residuals = sigma^(-1) * Lambda^(-1/2) * residuals\n\n\n\n\nThis is based on the works of José C. Pinheiro and Douglas M. Bates. The nlme package in R references their book \"Mixed effects models in S and S-PLUS\" (2000), while Stata references their article \"Computational Methods for Multilevel Modelling\" (1998) (see page 575 of \"STATA MULTILEVEL MIXED-EFFECTS REFERENCE MANUAL RELEASE 19 (https://www.stata.com/manuals/me.pdf). The terminology is a bit confusing, as 'normalized' residuals in R are called 'standardized' residuals in stata, which is not to be confused with 'Pearson' residuals, which is what R considers 'standardized').\n\n\n\n\nHowever, the way the matrix square root is computed is different between the two programs. The result can have a rather significant impact on whether or not the normalized residuals actually seem to follow a normal distribution.\n\n\n\n\nThe way R computes the matrix square root is through the Cholesky decomposition A = L*L^T (using the chol function from FORTRAN77). I cannot access the source code for Stata, but it seems like Stata uses Cholesky decomposition as well, however using a Cholesky decomposition algorithm starting at \"the bottom right\" of the matrix instead of \"the top left\" such that A = L^T * L. Using these two methods for Cholesky decomposition, I have been able to recreate the normalised residuals from R and Stata respectively.\n\n\n\n\nWhen using QQ-plots on the normalized residuals calculated with R and those calculated with Stata, the two results plots imply different conclusions about the normality of the residuals.\n\n\n\n\nIn principle, could one not use several different methods for Cholesky decomposition to compute a matrix square root and therefore come to significantly different conclusions? Would it therefore not be preferable to use eigenvalue decomposition to compute a matrix square root as opposed to Cholesky decomposition? One reason I believe EVD would be better is that it does not require transposing one \"square root\", i.e. we have directly that A^(1/2) * A^(1/2) = A.\n\n\n\n\nHere, I have added an example:\n\n\n\n\nratlong <- read.csv(\"ratlong.csv\") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n weights = varIdent(form = ~ 1 | time),\n na.action = na.exclude,\n method = \"REML\",\n data = ratlong)\n\nsummary(model)\nparameters(model)\ngetVarCov(model)\n\ntmp <- mutate(\n ratlong,\n fit = fitted(model),\n response = residuals(model, type = \"r\"),\n pearson = residuals(model, type = \"p\"),\n norm_res_R = residuals(model, type = \"n\"),\n norm_res_stata = c(\n -.3343025, .5268827, .4992422, .0732094, .8447663,\n -.3185105, -.2071171, 1.274912, .7114518, 1.215278,\n -.5135215, .0203645, -.5228509, -.8512383, 1.808096,\n .4581496, -1.22478, -.9106107, -.7130803, .2519478,\n .3804444, .2287333, .9784756, -.3758776, -.7113822,\n -1.475303, -1.399477, -1.504103, 1.288807, -.5631775,\n .473786, -.4318775, .5628197, -1.065117, -1.452405,\n .9371732, 1.274058, .9912707, .9466597, -.4890752,\n .1423321, .311183, -.8122606, -.5272216, -1.526507,\n .2497523, .9020303, -.556895, .5124069, .6224594,\n .8534008, -1.234297, .7109886, 1.567964, .3556911,\n 1.202434, -.9995003, .4767818, .8310238, -.1630251,\n -.7255811, -.987914, 1.937267, -1.758109, .6521003,\n -1.101692, 2.462107, .2542622, .8310238, -.1630251,\n -1.298645, -.3421695, -1.104759, .5448185, 1.170816,\n -1.124267, .0387734, .6711161, -.8830101, -.385332,\n .2229622, -.5032972, .0853191, 1.314626, -1.200457,\n 2.574736, .5105642, -1.381145, -.8254197, 1.170816,\n -.5026115, -.0627333, -.9601486, -1.083703, -1.27456,\n -.1007365, 1.118466, -.6896819, -.5392144, -.1630251)\n)\n\n# Here we observe that the pearson residual is approximately equal to the \n# normalized at time 1 for R and time 5 for stata\ntmp$pearson[seq(5, nrow(ratlong), 5)] - \n tmp$norm_res_stata[seq(5, nrow(ratlong), 5)]\ntmp$pearson[seq(1, nrow(ratlong), 5)] - \n tmp$norm_res_R[seq(1, nrow(ratlong), 5)]\n\n\n\n\n\nAccording to the nmle package (retrieved from github (https://github.com/cran/nlme)), the residuals are computed as such:\n\n\n\n\n#### from residuals.gls\nval <- object$residuals\nif (type != \"response\") {\n val <- val/attr(val, \"std\")\n lab <- \"Standardized residuals\"\n if (type == \"normalized\") {\nif (!is.null(cSt <- object$modelStruct$corStruct)) {\n ## normalize according to inv-trans factor\n val <- recalc(cSt, list(Xy = as.matrix(val)))$Xy[, 1]\n lab <- \"Normalized residuals\"\n }\n }\n}\n \n#### from recalc.corSymm\nrecalc.corSymm <- function(object, conLin, ...)\n{\n val <-\n .C(symm_recalc,\n Xy = as.double(conLin[[\"Xy\"]]),\n as.integer(unlist(Dim(object))),\n as.integer(ncol(conLin[[\"Xy\"]])),\n as.double(as.vector(object)),\n as.integer(unlist(getCovariate(object))),\n as.integer(attr(object, \"maxCov\")),\n logLik = double(1))[c(\"Xy\", \"logLik\")]\n conLin[[\"Xy\"]][] <- val[[\"Xy\"]]\n conLin[[\"logLik\"]] <- conLin[[\"logLik\"]] + val[[\"logLik\"]]\n conLin\n}\n \n#### from symm_recalc (written in C)\nvoid\nsymm_recalc(double *Xy, int *pdims, int *ZXcol, double *pars,\n int *time, int *maxC, double *logdet)\n{\n int N = pdims[0], M = pdims[1], *len = pdims + 4, *start = len + M, i;\n double *crr = R_Calloc(*maxC * (*maxC - 1) / 2, double);\n /* parameters assumed in unconstrained form */\n symm_fullCorr(pars, maxC, crr); /* get all correlations (not correlation \n matrix) */\n for(i = 0; i < M; i++) {\n double *Factor = R_Calloc((len[i] * len[i]), double);\n symm_fact(crr, time + start[i], &len[i], maxC, Factor, logdet);\n mult_mat(Xy + start[i], N, Factor, len[i], len[i], len[i],\n Xy + start[i], N, *ZXcol);\n R_Free(Factor);\n }\n R_Free(crr);\n}\n \n#### from symm_fact (also written in C)\nstatic void\nsymm_fact(double *crr, int *time, int *n, int *maxC, double *mat,\n double *logdet)\n{\n int job = 11L, info, i, nsq = *n * (*n), np1 = *n + 1;\n double *work = R_Calloc(*n, double), *work1 = R_Calloc(nsq, double);\n symm_mat(crr, time, n, maxC, mat); /* make full symmetric correlation \n matrix for individual i */\n F77_CALL(chol) (mat, n, n, mat, &info); /* Cholesky decomposition */\n for(i = 0; i < *n; i++) {\n work1[i * np1] = 1; /* set diag to 1 in empty matrix (i.e. create \n identity matrix) */\n F77_CALL(dtrsl) (mat, n, n, work1 + i * (*n), &job, &info); /* solves \n linear system given triangular matrix */\n *logdet -= log(fabs(mat[i * np1]));\n }\n Memcpy(mat, work1, nsq); \n R_Free(work); R_Free(work1);\n}\n\n\n\n\n\nI then manually computed the normalized residuals in R, through a regular Cholesky decomposition (same as t(chol) in R), through a \"reverse\" Cholesky decomposition and through EVD.\n\n\n\n\n# regular Cholesky algorithm (same as t(chol) for base R's chol function)\n regChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in 1:n){\n if (j == 1){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[j,1:(j-1)]^2))\n }\n if (j == 1){\n for (i in (j+1):n){\n L[i,j] = A[i,j]/L[j,j]\n }\n } else if (j < n){\n for (i in (j+1):n){\n L[i,j] = (A[i,j]-sum(L[i,1:(j-1)]*L[j,1:(j-1)]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \n # reverse Cholesky algorithm\n revChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \ncorMat <- model$modelStruct$corStruct #correlation structure of type corSymm\n \npdims <- as.integer(unlist(Dim(corMat))) #dimensions of correlation matrices\ncorMatFull <- corMatrix(corMat) #full correlation matrix\n ############################################################################\n#### Compute normalized residuals\n\n# `Using reverse Cholesky decomposition (gives same values as stata)\n\nnormres1 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n L <- revChol(A) # lower triangular / square root\n invSqLambda <- solve(t(L)) # invert L -- if regular Cholesky: use solve(L)\n normres1[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nt(L) %*% L #returns correlation matrix A given reversed Cholesky\n\n#Using regular Cholesky decomposition (gives same values as R)\nnormres2 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) #correlation matrix\n L <- t(chol(A)) \n # lower triangular / square root -- note that regChol(A) = t(chol(A))\n invSqLambda <- solve(L) # invert L -- if regular Cholesky: use solve(L)\n normres2[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nL %*% t(L) #returns correlation matrix given standard Cholesky\n\n# Using EVD\nnormres3 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] # observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) # total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n E <- eigen(A) # EVD eigenvalue decomposition\n sqrtA <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors) \n# matrix square root\n invSqLambda <- solve(sqrtA) # invert sqrtA\n normres3[dim2:(dim2 + dim-1)] <- \ninvSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\n\nround(normres1 - tmp$norm_res_stata, digits = 5) \n# approx 0 when using reverse Cholesky\nround(normres2 - tmp$norm_res_R, digits = 15) \n # approx 0 when using regular Cholesky\n \n##### will add qqplots/histograms with results in a couple of days\n\n\n\n\n\nThe results on the rat-example imply a left or a right-skew (Stata and R respecitvely) when compared to the standard normal, i.e. they may lead to different conlclusions about the model fit (I have an example, wherein the difference is more pronounced, but I do not want to break GDPR rules. Maybe someone can find a better example?). Using EVD, there does not seem to be as much of a skew to one side or the other.\n\n\n\n\n[image: QQ-plot of normalized residuals with each method compared to standard normal; source: https://i.sstatic.net/65PG6zuB.png] (https://i.sstatic.net/65PG6zuB.png)\n\n\n\n\n[image: Histogram of normalized residuals with each method compared to standard normal; source: https://i.sstatic.net/XWUljnac.png] (https://i.sstatic.net/XWUljnac.png)\n\n\n\n\nThe figures are created via:\n\n\n\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(sample = tmp$norm_res_stata)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals stata\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(sample = tmp$norm_res_R)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals R\")\nplot3 <- ggplot(as.data.frame(normres3), aes(sample = normres3)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(x = tmp$norm_res_stata)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals stata (reverse Cholesky)\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(x = tmp$norm_res_R)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals R (standard Cholesky)\")\nplot3 <- ggplot(as.data.frame(normres3), aes(x = normres3)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\n\n\n\n\nThe log from the Stata-code is given here:\n\n\n\n\n. \n. \n. import delim \"ratlong.csv\", clear \n(encoding automatically selected: ISO-8859-1)\n(5 vars, 100 obs)\n\n. \n. mixed weight b1.group##b0.time || rat: , reml baselev nocons res(un, t(time))\n\nPerforming gradient-based optimization: \nIteration 0: Log restricted-likelihood = -346.35796 (not concave)\nIteration 1: Log restricted-likelihood = -284.80839 (not concave)\nIteration 2: Log restricted-likelihood = -281.13028 \nIteration 3: Log restricted-likelihood = -278.4598 \nIteration 4: Log restricted-likelihood = -276.85378 \nIteration 5: Log restricted-likelihood = -276.76319 \nIteration 6: Log restricted-likelihood = -276.76264 \nIteration 7: Log restricted-likelihood = -276.76264 \n\nComputing standard errors ...\n\nMixed-effects REML regression Number of obs = 100\nGroup variable: rat Number of groups = 20\n Obs per group:\n min = 5\n avg = 5.0\n max = 5\n Wald chi2(9) = 1277.34\nLog restricted-likelihood = -276.76264 Prob > chi2 = 0.0000\n\n------------------------------------------------------------------------------\n weight | Coefficient Std. err. z P>|z| [95% conf. interval]\n-------------+----------------------------------------------------------------\n group |\n 1 | 0 (base)\n 3 | .7 2.270827 0.31 0.758 -3.75074 5.15074\n |\n time |\n 0 | 0 (base)\n 1 | 24.5 1.61744 15.15 0.000 21.32988 27.67012\n 2 | 52 2.045184 25.43 0.000 47.99151 56.00849\n 3 | 76.1 3.11002 24.47 0.000 70.00447 82.19553\n 4 | 106.6 4.073561 26.17 0.000 98.61597 114.584\n |\n group#time |\n 3 1 | -2.9 2.287405 -1.27 0.205 -7.383232 1.583232\n 3 2 | -10.9 2.892328 -3.77 0.000 -16.56886 -5.231142\n 3 3 | -22.4 4.398233 -5.09 0.000 -31.02038 -13.77962\n 3 4 | -37.1 5.760885 -6.44 0.000 -48.39113 -25.80887\n |\n _cons | 54 1.605717 33.63 0.000 50.85285 57.14715\n------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------\n Random-effects parameters | Estimate Std. err. [95% conf. interval]\n-----------------------------+------------------------------------------------\nrat: (empty) |\n-----------------------------+------------------------------------------------\nResidual: Unstructured |\n var(e0) | 25.78329 8.592901 13.41698 49.54749\n var(e1) | 77.81102 25.92904 40.49434 149.5161\n var(e2) | 85.31105 28.41546 44.41058 163.8793\n var(e3) | 127.9611 42.64015 66.59387 245.8791\n var(e4) | 182.1112 60.70111 94.75779 349.9921\n cov(e0,e1) | 38.7166 13.95059 11.37394 66.05925\n cov(e0,e2) | 34.63327 13.73195 7.719139 61.5474\n cov(e0,e3) | 28.51106 15.09849 -1.081436 58.10355\n cov(e0,e4) | 20.97774 16.87309 -12.09292 54.04839\n cov(e1,e2) | 71.47769 25.52878 21.44219 121.5132\n cov(e1,e3) | 56.73882 27.02632 3.768207 109.7094\n cov(e1,e4) | 42.8555 29.78855 -15.52898 101.24\n cov(e2,e3) | 89.65551 32.42749 26.09881 153.2122\n cov(e2,e4) | 86.18887 35.69784 16.22239 156.1553\n cov(e3,e4) | 136.2 48.21199 41.70625 230.6938\n------------------------------------------------------------------------------\nLR test vs. linear model: chi2(14) = 139.19 Prob > chi2 = 0.0000\n\nNote: The reported degrees of freedom assumes the null hypothesis is not on the boundary of the parameter space. If this is not true, then the\n reported test is conservative.\n\n. \n. predict res, rstandard\n\n. \n. list rat time res, sepby(rat)\n\n +------------------------+\n | rat time res |\n |------------------------|\n 1. | 1 0 -.3343025 |\n 2. | 1 1 .5268827 |\n 3. | 1 2 .4992422 |\n 4. | 1 3 .0732094 |\n 5. | 1 4 .8447663 |\n |------------------------|\n 6. | 2 0 -.3185105 |\n 7. | 2 1 -.2071171 |\n 8. | 2 2 1.274912 |\n 9. | 2 3 .7114518 |\n 10. | 2 4 1.215278 |\n |------------------------|\n 11. | 3 0 -.5135215 |\n 12. | 3 1 .0203645 |\n 13. | 3 2 -.5228509 |\n 14. | 3 3 -.8512383 |\n 15. | 3 4 1.808096 |\n |------------------------|\n 16. | 4 0 .4581496 |\n 17. | 4 1 -1.22478 |\n 18. | 4 2 -.9106107 |\n 19. | 4 3 -.7130803 |\n 20. | 4 4 .2519478 |\n |------------------------|\n 21. | 5 0 .3804444 |\n 22. | 5 1 .2287333 |\n 23. | 5 2 .9784756 |\n 24. | 5 3 -.3758776 |\n 25. | 5 4 -.7113822 |\n |------------------------|\n 26. | 6 0 -1.475303 |\n 27. | 6 1 -1.399477 |\n 28. | 6 2 -1.504103 |\n 29. | 6 3 1.288807 |\n 30. | 6 4 -.5631775 |\n |------------------------|\n 31. | 7 0 .473786 |\n 32. | 7 1 -.4318775 |\n 33. | 7 2 .5628197 |\n 34. | 7 3 -1.065117 |\n 35. | 7 4 -1.452405 |\n |------------------------|\n 36. | 8 0 .9371732 |\n 37. | 8 1 1.274058 |\n 38. | 8 2 .9912707 |\n 39. | 8 3 .9466597 |\n 40. | 8 4 -.4890752 |\n |------------------------|\n 41. | 9 0 .1423321 |\n 42. | 9 1 .311183 |\n 43. | 9 2 -.8122606 |\n 44. | 9 3 -.5272216 |\n 45. | 9 4 -1.526507 |\n |------------------------|\n 46. | 10 0 .2497523 |\n 47. | 10 1 .9020303 |\n 48. | 10 2 -.556895 |\n 49. | 10 3 .5124069 |\n 50. | 10 4 .6224594 |\n |------------------------|\n 51. | 18 0 .8534008 |\n 52. | 18 1 -1.234297 |\n 53. | 18 2 .7109886 |\n 54. | 18 3 1.567964 |\n 55. | 18 4 .3556911 |\n |------------------------|\n 56. | 19 0 1.202434 |\n 57. | 19 1 -.9995003 |\n 58. | 19 2 .4767818 |\n 59. | 19 3 .8310238 |\n 60. | 19 4 -.1630251 |\n |------------------------|\n 61. | 20 0 -.7255811 |\n 62. | 20 1 -.987914 |\n 63. | 20 2 1.937267 |\n 64. | 20 3 -1.758109 |\n 65. | 20 4 .6521003 |\n |------------------------|\n 66. | 21 0 -1.101692 |\n 67. | 21 1 2.462107 |\n 68. | 21 2 .2542622 |\n 69. | 21 3 .8310238 |\n 70. | 21 4 -.1630251 |\n |------------------------|\n 71. | 22 0 -1.298645 |\n 72. | 22 1 -.3421695 |\n 73. | 22 2 -1.104759 |\n 74. | 22 3 .5448185 |\n 75. | 22 4 1.170816 |\n |------------------------|\n 76. | 23 0 -1.124267 |\n 77. | 23 1 .0387734 |\n 78. | 23 2 .6711161 |\n 79. | 23 3 -.8830101 |\n 80. | 23 4 -.385332 |\n |------------------------|\n 81. | 24 0 .2229622 |\n 82. | 24 1 -.5032972 |\n 83. | 24 2 .0853191 |\n 84. | 24 3 1.314626 |\n 85. | 24 4 -1.200457 |\n |------------------------|\n 86. | 25 0 2.574736 |\n 87. | 25 1 .5105642 |\n 88. | 25 2 -1.381145 |\n 89. | 25 3 -.8254197 |\n 90. | 25 4 1.170816 |\n |------------------------|\n 91. | 26 0 -.5026115 |\n 92. | 26 1 -.0627333 |\n 93. | 26 2 -.9601486 |\n 94. | 26 3 -1.083703 |\n 95. | 26 4 -1.27456 |\n |------------------------|\n 96. | 27 0 -.1007365 |\n 97. | 27 1 1.118466 |\n 98. | 27 2 -.6896819 |\n 99. | 27 3 -.5392144 |\n100. | 27 4 -.1630251 |\n +------------------------+\n\n\n\n\n\nI found out the data example I was working with was RatWeight from package heplots, although I was given simply given the \"ratlong.csv\"-file, which is a heavily manipulated and reordered version of RatWeight, so if you want to reproduce it, here is how (I hope you will bear with me):\n\n\n\n\nrat <- RatWeight\nnames(rat) <- c(\"Group\", \"Weight0\", \"Weight1\", \"Weight2\", \"Weight3\", \"Weight4\")\nrat$Group <- factor(rat$Group, levels = c(\"Control\", \"Thyroxin\", \"Thiouracil\"))\nrat <- rat[order(rat$Group),]\nrat <- cbind(data.frame(Rat=1:27), rat) |>\n mutate(Rat = factor(Rat))\nrat <- subset(rat, Group != \"Thyroxin\")\nratlong <- rat |> gather(time, Weight, Weight0:Weight4) |>\n separate(time, c(\"W\", \"time\"), sep = 6) |>\n mutate(time = as.factor(as.numeric(time))) |>\n mutate(Group = as.factor(as.numeric(Group))) |>\n mutate(Weight = as.double(Weight))\nratlong <- ratlong[with(ratlong, order(Rat, time, Group)),]\nratlong$Weight[89:90] <- c(116,140)\nwrite.csv(ratlong, \"ratlong.csv\", row.names = FALSE)\n\n\n\n\n\nPackages used in general:\n\n\n\n\nlibrary(lme4)\nlibrary(nlme)\nlibrary(haven)\nlibrary(dplyr)\nlibrary(heplots)\nlibrary(parameters)\nlibrary(tidyverse)\nlibrary(gridExtra)\nlibrary(ggplot2)", "record_id": "Scientific-Code-and-Analysis-QA:stats:677243", "selected_answer": {"answer_html": "Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. The most likely reason, as to why some datasets and their corresponding models look like they have a better fit using Stata (reverse Cholesky) as opposed to R (standard Cholesky), when examining their normalized residuals, is not due to any deficiency of either program but rather due to the random spread of the residuals, falling in such a way that one method is perceived to be more effective. If given several datasets, where a mixed model is a good fit, I now believe it is equally likely, between R and Stata, which program will give more accurate-looking normalized residuals.
\nOne of the tests I did is the following, wherein I measured the effectiveness of normalization by the closeness to the first 4 moments of the standard normal distribution. I did this for some arbitrary variance-covariance covariance matrix, used to repeatedly simulate N residuals, M number of times.
\nlibrary(gridExtra)\nlibrary(nlme)\nlibrary("mvtnorm")\nlibrary("ggplot2")\nlibrary("dplyr")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that "method 1" is standard Cholesky, "method 2" is reverse Cholesky and "method 3" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v1", x = "method (true Sigma)")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v2", x = "method (true Sigma)")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v1", x = "method (Sigma-hat)")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v2", x = "method (Sigma-hat)")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v1", x = "method (true Sigma)")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v2", x = "method (true Sigma)")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v1", x = "method (Sigma-hat)")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v2", x = "method (Sigma-hat)")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v1", x = "method (true Sigma)")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v2", x = "method (true Sigma)")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v1", x = "method (Sigma-hat)")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v2", x = "method (Sigma-hat)")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v1", x = "method (true Sigma)")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v2", x = "method (true Sigma)")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v1", x = "method (Sigma-hat)")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v2", x = "method (Sigma-hat)")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)\n\n", "answer_id": 677304, "answer_text": "Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. The most likely reason, as to why some datasets and their corresponding models look like they have a better fit using Stata (reverse Cholesky) as opposed to R (standard Cholesky), when examining their normalized residuals, is not due to any deficiency of either program but rather due to the random spread of the residuals, falling in such a way that one method is perceived to be more effective. If given several datasets, where a mixed model is a good fit, I now believe it is equally likely, between R and Stata, which program will give more accurate-looking normalized residuals.\n\n\n\n\nOne of the tests I did is the following, wherein I measured the effectiveness of normalization by the closeness to the first 4 moments of the standard normal distribution. I did this for some arbitrary variance-covariance covariance matrix, used to repeatedly simulate N residuals, M number of times.\n\n\n\n\nlibrary(gridExtra)\nlibrary(nlme)\nlibrary(\"mvtnorm\")\nlibrary(\"ggplot2\")\nlibrary(\"dplyr\")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that \"method 1\" is standard Cholesky, \"method 2\" is reverse Cholesky and \"method 3\" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (true Sigma)\")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (true Sigma)\")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (Sigma-hat)\")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (true Sigma)\")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (true Sigma)\")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (Sigma-hat)\")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (Sigma-hat)\")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (true Sigma)\")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (true Sigma)\")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (Sigma-hat)\")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (true Sigma)\")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (true Sigma)\")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (Sigma-hat)\")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (Sigma-hat)\")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)", "answer_url": "https://stats.stackexchange.com/a/677304", "author": "Michael", "author_url": "https://stats.stackexchange.com/users/517013/michael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-30T10:48:26+00:00", "is_accepted": false, "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": 677243, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-30T10:48:26+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "26D2264C-CE23-455D-B111-D7C569BDFF44", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/26D2264C-CE23-455D-B111-D7C569BDFF44/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-30T10:53:50+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "77058962-D9B4-4D5E-BA55-FC2DD80B5B36", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/77058962-D9B4-4D5E-BA55-FC2DD80B5B36/view-source"}], "score": 2, "updated_at": "2026-09-30T10:53:50+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. The most likely reason, as to why some datasets and their corresponding models look like they have a better fit using Stata (reverse Cholesky) as opposed to R (standard Cholesky), when examining their normalized residuals, is not due to any deficiency of either program but rather due to the random spread of the residuals, falling in such a way that one method is perceived to be more effective. If given several datasets, where a mixed model is a good fit, I now believe it is equally likely, between R and Stata, which program will give more accurate-looking normalized residuals.
\nOne of the tests I did is the following, wherein I measured the effectiveness of normalization by the closeness to the first 4 moments of the standard normal distribution. I did this for some arbitrary variance-covariance covariance matrix, used to repeatedly simulate N residuals, M number of times.
\nlibrary(gridExtra)\nlibrary(nlme)\nlibrary("mvtnorm")\nlibrary("ggplot2")\nlibrary("dplyr")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that "method 1" is standard Cholesky, "method 2" is reverse Cholesky and "method 3" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v1", x = "method (true Sigma)")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v2", x = "method (true Sigma)")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v1", x = "method (Sigma-hat)")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. mean of norm-res-v2", x = "method (Sigma-hat)")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v1", x = "method (true Sigma)")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v2", x = "method (true Sigma)")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v1", x = "method (Sigma-hat)")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "var closest to 1 for norm-res-v2", x = "method (Sigma-hat)")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v1", x = "method (true Sigma)")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v2", x = "method (true Sigma)")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v1", x = "method (Sigma-hat)")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. skew of norm-res-v2", x = "method (Sigma-hat)")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v1", x = "method (true Sigma)")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v2", x = "method (true Sigma)")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v1", x = "method (Sigma-hat)")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat="count",fill = "white", color = "black") +\n labs(y = "smallest abs. kurt. of norm-res-v2", x = "method (Sigma-hat)")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)\n\n", "answer_id": 677304, "answer_text": "Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. The most likely reason, as to why some datasets and their corresponding models look like they have a better fit using Stata (reverse Cholesky) as opposed to R (standard Cholesky), when examining their normalized residuals, is not due to any deficiency of either program but rather due to the random spread of the residuals, falling in such a way that one method is perceived to be more effective. If given several datasets, where a mixed model is a good fit, I now believe it is equally likely, between R and Stata, which program will give more accurate-looking normalized residuals.\n\n\n\n\nOne of the tests I did is the following, wherein I measured the effectiveness of normalization by the closeness to the first 4 moments of the standard normal distribution. I did this for some arbitrary variance-covariance covariance matrix, used to repeatedly simulate N residuals, M number of times.\n\n\n\n\nlibrary(gridExtra)\nlibrary(nlme)\nlibrary(\"mvtnorm\")\nlibrary(\"ggplot2\")\nlibrary(\"dplyr\")\nlibrary(moments)\n\n#on large sample tests, all methods look very similar.\n#on small samples there is a distinction, where EVD tends to lie in between the other 2 methods\n#but this is NOT ALWAYS the case\n\nrevChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n}\n\n################################################################################\n### repeated small sample simulations\n\n\n\nSigma <- matrix(c(5,3, 3,7), byrow = TRUE, nrow = 2)\n\nN = 100\nM = 10000\nmeans <- matrix(0, M, 12)\nvariances <- matrix(0, M, 12)\nskewnesses <- matrix(0, M, 12)\nkurtosises <- matrix(0, M, 12)\nfor (i in 1:M){\n y <- rmvnorm(N, sigma = Sigma)\n \n # compute normalized residuals for true sigma\n L <- chol(Sigma) |> t()\n y_tilde_stdChol <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sigma)\n y_tilde_revChol <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sigma)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n # compute normalized residuals for sigma hat\n Sig_hat <- var(y)\n \n L <- chol(Sig_hat) |> t()\n y_tilde_stdChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(L)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n L_alt <- revChol(Sig_hat)\n y_tilde_revChol2 <- apply(y, MARGIN = 1, FUN = function(y0){\n t(solve(L_alt))%*%y0\n }) |>\n t() |>\n as_tibble()\n \n E <- eigen(Sig_hat)\n sqrtSig <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors)\n y_tilde_EVD2 <- apply(y, MARGIN = 1, FUN = function(y0){\n solve(sqrtSig)%*%y0\n }) |>\n t() |>\n as_tibble()\n \n means[i,1:3] <- c(mean(y_tilde_stdChol$V1), mean(y_tilde_revChol$V1), mean(y_tilde_EVD$V1))\n means[i,4:6] <- c(mean(y_tilde_stdChol$V2), mean(y_tilde_revChol$V2), mean(y_tilde_EVD$V2))\n means[i,7:9] <- c(mean(y_tilde_stdChol2$V1), mean(y_tilde_revChol2$V1), mean(y_tilde_EVD2$V1))\n means[i,10:12] <- c(mean(y_tilde_stdChol2$V2), mean(y_tilde_revChol2$V2), mean(y_tilde_EVD2$V2))\n \n variances[i,1:3] <- c(var(y_tilde_stdChol$V1), var(y_tilde_revChol$V1), var(y_tilde_EVD$V1))\n variances[i,4:6] <- c(var(y_tilde_stdChol$V2), var(y_tilde_revChol$V2), var(y_tilde_EVD$V2))\n variances[i,7:9] <- c(var(y_tilde_stdChol2$V1), var(y_tilde_revChol2$V1), var(y_tilde_EVD2$V1))\n variances[i,10:12] <- c(var(y_tilde_stdChol2$V2), var(y_tilde_revChol2$V2), var(y_tilde_EVD2$V2))\n \n skewnesses[i,1:3] <- c(skewness(y_tilde_stdChol$V1)$Skewness, skewness(y_tilde_revChol$V1)$Skewness, skewness(y_tilde_EVD$V1)$Skewness)\n skewnesses[i,4:6] <- c(skewness(y_tilde_stdChol$V2)$Skewness, skewness(y_tilde_revChol$V2)$Skewness, skewness(y_tilde_EVD$V2)$Skewness)\n skewnesses[i,7:9] <- c(skewness(y_tilde_stdChol2$V1)$Skewness, skewness(y_tilde_revChol2$V1)$Skewness, skewness(y_tilde_EVD2$V1)$Skewness)\n skewnesses[i,10:12] <- c(skewness(y_tilde_stdChol2$V2)$Skewness, skewness(y_tilde_revChol2$V2)$Skewness, skewness(y_tilde_EVD2$V2)$Skewness)\n \n kurtosises[i,1:3] <- c(kurtosis(y_tilde_stdChol$V1)$Kurtosis, kurtosis(y_tilde_revChol$V1)$Kurtosis, kurtosis(y_tilde_EVD$V1)$Kurtosis)\n kurtosises[i,4:6] <- c(kurtosis(y_tilde_stdChol$V2)$Kurtosis, kurtosis(y_tilde_revChol$V2)$Kurtosis, kurtosis(y_tilde_EVD$V2)$Kurtosis)\n kurtosises[i,7:9] <- c(kurtosis(y_tilde_stdChol2$V1)$Kurtosis, kurtosis(y_tilde_revChol2$V1)$Kurtosis, kurtosis(y_tilde_EVD2$V1)$Kurtosis)\n kurtosises[i,10:12] <- c(kurtosis(y_tilde_stdChol2$V2)$Kurtosis, kurtosis(y_tilde_revChol2$V2)$Kurtosis, kurtosis(y_tilde_EVD2$V2)$Kurtosis)\n \n print(i)\n}\n\n#record which methods have the lowest, middle and highest mean for each vector and each simulation\nmeanorder <- cbind(cbind(t(apply(abs(means[,1:3]),1,order)),\n t(apply(abs(means[,4:6]),1,order)),\n t(apply(abs(means[,7:9]),1,order)),\n t(apply(abs(means[,10:12]),1,order))))\n\n#record which methods have the variance closest to 1 for each vector and each simulation\nvarorder <- cbind(cbind(t(apply(abs(1-variances[,1:3]),1,order)),\n t(apply(abs(1-variances[,4:6]),1,order)),\n t(apply(abs(1-variances[,7:9]),1,order)),\n t(apply(abs(1-variances[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest skewness for each vector and each simulation\nskeworder <- cbind(cbind(t(apply(abs(skewnesses[,1:3]),1,order)), \n t(apply(abs(skewnesses[,4:6]),1,order)), \n t(apply(abs(skewnesses[,7:9]),1,order)), \n t(apply(abs(skewnesses[,10:12]),1,order))))\n\n#record which methods have the lowest, middle and highest (excess) kurtosis for each vector and each simulation\nkurtorder <- cbind(cbind(t(apply(abs(kurtosises[,1:3]),1,order)), \n t(apply(abs(kurtosises[,4:6]),1,order)), \n t(apply(abs(kurtosises[,7:9]),1,order)), \n t(apply(abs(kurtosises[,10:12]),1,order))))\n\n#specify that \"method 1\" is standard Cholesky, \"method 2\" is reverse Cholesky and \"method 3\" is EVD\nrename <- function(V){\n V <- data.frame(V) %>% mutate(\n across(\n .cols = everything(),\n .fns = ~ case_when(\n .x == 1 ~ 'stdChol',\n .x == 2 ~ 'revChol',\n .x == 3 ~ 'EVD',\n TRUE ~ as.character(.x)\n )\n )\n )\n}\nmeanorder <- rename(meanorder)\nvarorder <- rename(varorder)\nskeworder <- rename(skeworder)\nkurtorder <- rename(kurtorder)\n\n#plots\npM1 <- meanorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (true Sigma)\")\npM2 <- meanorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (true Sigma)\")\npM3 <- meanorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v1\", x = \"method (Sigma-hat)\")\npM4 <- meanorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. mean of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npV1 <- varorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (true Sigma)\")\npV2 <- varorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (true Sigma)\")\npV3 <- varorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v1\", x = \"method (Sigma-hat)\")\npV4 <- varorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"var closest to 1 for norm-res-v2\", x = \"method (Sigma-hat)\")\n\npS1 <- skeworder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (true Sigma)\")\npS2 <- skeworder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (true Sigma)\")\npS3 <- skeworder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v1\", x = \"method (Sigma-hat)\")\npS4 <- skeworder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. skew of norm-res-v2\", x = \"method (Sigma-hat)\")\n\npK1 <- kurtorder |>\n ggplot(aes(x = X1)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (true Sigma)\")\npK2 <- kurtorder |>\n ggplot(aes(x = X4)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (true Sigma)\")\npK3 <- kurtorder |>\n ggplot(aes(x = X7)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v1\", x = \"method (Sigma-hat)\")\npK4 <- kurtorder |>\n ggplot(aes(x = X10)) +\n geom_histogram(stat=\"count\",fill = \"white\", color = \"black\") +\n labs(y = \"smallest abs. kurt. of norm-res-v2\", x = \"method (Sigma-hat)\")\n\n\ngrid.arrange(pM1, pV1, pS1, pK1,\n pM2, pV2, pS2, pK2,\n pM3, pV3, pS3, pK3,\n pM4, pV4, pS4, pK4, ncol = 4)", "answer_url": "https://stats.stackexchange.com/a/677304", "author": "Michael", "author_url": "https://stats.stackexchange.com/users/517013/michael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-30T10:48:26+00:00", "is_accepted": false, "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": 677243, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-30T10:48:26+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "26D2264C-CE23-455D-B111-D7C569BDFF44", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/26D2264C-CE23-455D-B111-D7C569BDFF44/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-30T10:53:50+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "77058962-D9B4-4D5E-BA55-FC2DD80B5B36", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/77058962-D9B4-4D5E-BA55-FC2DD80B5B36/view-source"}], "score": 2, "updated_at": "2026-09-30T10:53:50+00:00"}], "domain": "statistics", "external_links": ["https://github.com/cran/nlme", "https://i.sstatic.net/65PG6zuB.png", "https://i.sstatic.net/XWUljnac.png", "https://www.stata.com/manuals/me.pdf"], "medical_sensitive": false, "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": "Michael", "question_author_url": "https://stats.stackexchange.com/users/517013/michael", "question_author_user_type": "registered", "question_created_at": "2026-09-23T09:39:51+00:00", "question_html": "I have been tasked with understanding why normalized residuals between R and Stata are different when using mixed models (i.e. the nlme package in R).
What I have found is that the residuals are both theoretically computed the same way: norm_residuals = sigma^(-1) * Lambda^(-1/2) * residuals
\nThis is based on the works of José C. Pinheiro and Douglas M. Bates. The nlme package in R references their book "Mixed effects models in S and S-PLUS" (2000), while Stata references their article "Computational Methods for Multilevel Modelling" (1998) (see page 575 of "STATA MULTILEVEL MIXED-EFFECTS REFERENCE MANUAL RELEASE 19. The terminology is a bit confusing, as 'normalized' residuals in R are called 'standardized' residuals in stata, which is not to be confused with 'Pearson' residuals, which is what R considers 'standardized').
However, the way the matrix square root is computed is different between the two programs. The result can have a rather significant impact on whether or not the normalized residuals actually seem to follow a normal distribution.
\nThe way R computes the matrix square root is through the Cholesky decomposition A = L*L^T (using the chol function from FORTRAN77). I cannot access the source code for Stata, but it seems like Stata uses Cholesky decomposition as well, however using a Cholesky decomposition algorithm starting at "the bottom right" of the matrix instead of "the top left" such that A = L^T * L. Using these two methods for Cholesky decomposition, I have been able to recreate the normalised residuals from R and Stata respectively.
When using QQ-plots on the normalized residuals calculated with R and those calculated with Stata, the two results plots imply different conclusions about the normality of the residuals.
\nIn principle, could one not use several different methods for Cholesky decomposition to compute a matrix square root and therefore come to significantly different conclusions? Would it therefore not be preferable to use eigenvalue decomposition to compute a matrix square root as opposed to Cholesky decomposition? One reason I believe EVD would be better is that it does not require transposing one "square root", i.e. we have directly that A^(1/2) * A^(1/2) = A.
\nHere, I have added an example:
\nratlong <- read.csv("ratlong.csv") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n weights = varIdent(form = ~ 1 | time),\n na.action = na.exclude,\n method = "REML",\n data = ratlong)\n\nsummary(model)\nparameters(model)\ngetVarCov(model)\n\ntmp <- mutate(\n ratlong,\n fit = fitted(model),\n response = residuals(model, type = "r"),\n pearson = residuals(model, type = "p"),\n norm_res_R = residuals(model, type = "n"),\n norm_res_stata = c(\n -.3343025, .5268827, .4992422, .0732094, .8447663,\n -.3185105, -.2071171, 1.274912, .7114518, 1.215278,\n -.5135215, .0203645, -.5228509, -.8512383, 1.808096,\n .4581496, -1.22478, -.9106107, -.7130803, .2519478,\n .3804444, .2287333, .9784756, -.3758776, -.7113822,\n -1.475303, -1.399477, -1.504103, 1.288807, -.5631775,\n .473786, -.4318775, .5628197, -1.065117, -1.452405,\n .9371732, 1.274058, .9912707, .9466597, -.4890752,\n .1423321, .311183, -.8122606, -.5272216, -1.526507,\n .2497523, .9020303, -.556895, .5124069, .6224594,\n .8534008, -1.234297, .7109886, 1.567964, .3556911,\n 1.202434, -.9995003, .4767818, .8310238, -.1630251,\n -.7255811, -.987914, 1.937267, -1.758109, .6521003,\n -1.101692, 2.462107, .2542622, .8310238, -.1630251,\n -1.298645, -.3421695, -1.104759, .5448185, 1.170816,\n -1.124267, .0387734, .6711161, -.8830101, -.385332,\n .2229622, -.5032972, .0853191, 1.314626, -1.200457,\n 2.574736, .5105642, -1.381145, -.8254197, 1.170816,\n -.5026115, -.0627333, -.9601486, -1.083703, -1.27456,\n -.1007365, 1.118466, -.6896819, -.5392144, -.1630251)\n)\n\n# Here we observe that the pearson residual is approximately equal to the \n# normalized at time 1 for R and time 5 for stata\ntmp$pearson[seq(5, nrow(ratlong), 5)] - \n tmp$norm_res_stata[seq(5, nrow(ratlong), 5)]\ntmp$pearson[seq(1, nrow(ratlong), 5)] - \n tmp$norm_res_R[seq(1, nrow(ratlong), 5)]\n\nAccording to the nmle package (retrieved from github), the residuals are computed as such:
#### from residuals.gls\nval <- object$residuals\nif (type != \"response\") {\n val <- val/attr(val, \"std\")\n lab <- \"Standardized residuals\"\n if (type == \"normalized\") {\nif (!is.null(cSt <- object$modelStruct$corStruct)) {\n ## normalize according to inv-trans factor\n val <- recalc(cSt, list(Xy = as.matrix(val)))$Xy[, 1]\n lab <- "Normalized residuals"\n }\n }\n}\n \n#### from recalc.corSymm\nrecalc.corSymm <- function(object, conLin, ...)\n{\n val <-\n .C(symm_recalc,\n Xy = as.double(conLin[["Xy"]]),\n as.integer(unlist(Dim(object))),\n as.integer(ncol(conLin[["Xy"]])),\n as.double(as.vector(object)),\n as.integer(unlist(getCovariate(object))),\n as.integer(attr(object, "maxCov")),\n logLik = double(1))[c("Xy", "logLik")]\n conLin[["Xy"]][] <- val[["Xy"]]\n conLin[["logLik"]] <- conLin[["logLik"]] + val[["logLik"]]\n conLin\n}\n \n#### from symm_recalc (written in C)\nvoid\nsymm_recalc(double *Xy, int *pdims, int *ZXcol, double *pars,\n int *time, int *maxC, double *logdet)\n{\n int N = pdims[0], M = pdims[1], *len = pdims + 4, *start = len + M, i;\n double *crr = R_Calloc(*maxC * (*maxC - 1) / 2, double);\n /* parameters assumed in unconstrained form */\n symm_fullCorr(pars, maxC, crr); /* get all correlations (not correlation \n matrix) */\n for(i = 0; i < M; i++) {\n double *Factor = R_Calloc((len[i] * len[i]), double);\n symm_fact(crr, time + start[i], &len[i], maxC, Factor, logdet);\n mult_mat(Xy + start[i], N, Factor, len[i], len[i], len[i],\n Xy + start[i], N, *ZXcol);\n R_Free(Factor);\n }\n R_Free(crr);\n}\n \n#### from symm_fact (also written in C)\nstatic void\nsymm_fact(double *crr, int *time, int *n, int *maxC, double *mat,\n double *logdet)\n{\n int job = 11L, info, i, nsq = *n * (*n), np1 = *n + 1;\n double *work = R_Calloc(*n, double), *work1 = R_Calloc(nsq, double);\n symm_mat(crr, time, n, maxC, mat); /* make full symmetric correlation \n matrix for individual i */\n F77_CALL(chol) (mat, n, n, mat, &info); /* Cholesky decomposition */\n for(i = 0; i < *n; i++) {\n work1[i * np1] = 1; /* set diag to 1 in empty matrix (i.e. create \n identity matrix) */\n F77_CALL(dtrsl) (mat, n, n, work1 + i * (*n), &job, &info); /* solves \n linear system given triangular matrix */\n *logdet -= log(fabs(mat[i * np1]));\n }\n Memcpy(mat, work1, nsq); \n R_Free(work); R_Free(work1);\n}\n\nI then manually computed the normalized residuals in R, through a regular Cholesky decomposition (same as t(chol) in R), through a "reverse" Cholesky decomposition and through EVD.
# regular Cholesky algorithm (same as t(chol) for base R's chol function)\n regChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in 1:n){\n if (j == 1){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[j,1:(j-1)]^2))\n }\n if (j == 1){\n for (i in (j+1):n){\n L[i,j] = A[i,j]/L[j,j]\n }\n } else if (j < n){\n for (i in (j+1):n){\n L[i,j] = (A[i,j]-sum(L[i,1:(j-1)]*L[j,1:(j-1)]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \n # reverse Cholesky algorithm\n revChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \ncorMat <- model$modelStruct$corStruct #correlation structure of type corSymm\n \npdims <- as.integer(unlist(Dim(corMat))) #dimensions of correlation matrices\ncorMatFull <- corMatrix(corMat) #full correlation matrix\n ############################################################################\n#### Compute normalized residuals\n\n# `Using reverse Cholesky decomposition (gives same values as stata)\n\nnormres1 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n L <- revChol(A) # lower triangular / square root\n invSqLambda <- solve(t(L)) # invert L -- if regular Cholesky: use solve(L)\n normres1[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nt(L) %*% L #returns correlation matrix A given reversed Cholesky\n\n#Using regular Cholesky decomposition (gives same values as R)\nnormres2 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) #correlation matrix\n L <- t(chol(A)) \n # lower triangular / square root -- note that regChol(A) = t(chol(A))\n invSqLambda <- solve(L) # invert L -- if regular Cholesky: use solve(L)\n normres2[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nL %*% t(L) #returns correlation matrix given standard Cholesky\n\n# Using EVD\nnormres3 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] # observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) # total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n E <- eigen(A) # EVD eigenvalue decomposition\n sqrtA <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors) \n# matrix square root\n invSqLambda <- solve(sqrtA) # invert sqrtA\n normres3[dim2:(dim2 + dim-1)] <- \ninvSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\n\nround(normres1 - tmp$norm_res_stata, digits = 5) \n# approx 0 when using reverse Cholesky\nround(normres2 - tmp$norm_res_R, digits = 15) \n # approx 0 when using regular Cholesky\n \n##### will add qqplots/histograms with results in a couple of days\n\nThe results on the rat-example imply a left or a right-skew (Stata and R respecitvely) when compared to the standard normal, i.e. they may lead to different conlclusions about the model fit (I have an example, wherein the difference is more pronounced, but I do not want to break GDPR rules. Maybe someone can find a better example?). Using EVD, there does not seem to be as much of a skew to one side or the other.
\n\n\nThe figures are created via:
\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(sample = tmp$norm_res_stata)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = "normalized residuals stata")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(sample = tmp$norm_res_R)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = "normalized residuals R")\nplot3 <- ggplot(as.data.frame(normres3), aes(sample = normres3)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = "normalized residuals EVD")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(x = tmp$norm_res_stata)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = "black", fill = "white") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = "normalised residuals stata (reverse Cholesky)")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(x = tmp$norm_res_R)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = "black", fill = "white") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = "normalised residuals R (standard Cholesky)")\nplot3 <- ggplot(as.data.frame(normres3), aes(x = normres3)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = "black", fill = "white") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = "normalised residuals EVD")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nThe log from the Stata-code is given here:
\n. \n. \n. import delim "ratlong.csv", clear \n(encoding automatically selected: ISO-8859-1)\n(5 vars, 100 obs)\n\n. \n. mixed weight b1.group##b0.time || rat: , reml baselev nocons res(un, t(time))\n\nPerforming gradient-based optimization: \nIteration 0: Log restricted-likelihood = -346.35796 (not concave)\nIteration 1: Log restricted-likelihood = -284.80839 (not concave)\nIteration 2: Log restricted-likelihood = -281.13028 \nIteration 3: Log restricted-likelihood = -278.4598 \nIteration 4: Log restricted-likelihood = -276.85378 \nIteration 5: Log restricted-likelihood = -276.76319 \nIteration 6: Log restricted-likelihood = -276.76264 \nIteration 7: Log restricted-likelihood = -276.76264 \n\nComputing standard errors ...\n\nMixed-effects REML regression Number of obs = 100\nGroup variable: rat Number of groups = 20\n Obs per group:\n min = 5\n avg = 5.0\n max = 5\n Wald chi2(9) = 1277.34\nLog restricted-likelihood = -276.76264 Prob > chi2 = 0.0000\n\n------------------------------------------------------------------------------\n weight | Coefficient Std. err. z P>|z| [95% conf. interval]\n-------------+----------------------------------------------------------------\n group |\n 1 | 0 (base)\n 3 | .7 2.270827 0.31 0.758 -3.75074 5.15074\n |\n time |\n 0 | 0 (base)\n 1 | 24.5 1.61744 15.15 0.000 21.32988 27.67012\n 2 | 52 2.045184 25.43 0.000 47.99151 56.00849\n 3 | 76.1 3.11002 24.47 0.000 70.00447 82.19553\n 4 | 106.6 4.073561 26.17 0.000 98.61597 114.584\n |\n group#time |\n 3 1 | -2.9 2.287405 -1.27 0.205 -7.383232 1.583232\n 3 2 | -10.9 2.892328 -3.77 0.000 -16.56886 -5.231142\n 3 3 | -22.4 4.398233 -5.09 0.000 -31.02038 -13.77962\n 3 4 | -37.1 5.760885 -6.44 0.000 -48.39113 -25.80887\n |\n _cons | 54 1.605717 33.63 0.000 50.85285 57.14715\n------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------\n Random-effects parameters | Estimate Std. err. [95% conf. interval]\n-----------------------------+------------------------------------------------\nrat: (empty) |\n-----------------------------+------------------------------------------------\nResidual: Unstructured |\n var(e0) | 25.78329 8.592901 13.41698 49.54749\n var(e1) | 77.81102 25.92904 40.49434 149.5161\n var(e2) | 85.31105 28.41546 44.41058 163.8793\n var(e3) | 127.9611 42.64015 66.59387 245.8791\n var(e4) | 182.1112 60.70111 94.75779 349.9921\n cov(e0,e1) | 38.7166 13.95059 11.37394 66.05925\n cov(e0,e2) | 34.63327 13.73195 7.719139 61.5474\n cov(e0,e3) | 28.51106 15.09849 -1.081436 58.10355\n cov(e0,e4) | 20.97774 16.87309 -12.09292 54.04839\n cov(e1,e2) | 71.47769 25.52878 21.44219 121.5132\n cov(e1,e3) | 56.73882 27.02632 3.768207 109.7094\n cov(e1,e4) | 42.8555 29.78855 -15.52898 101.24\n cov(e2,e3) | 89.65551 32.42749 26.09881 153.2122\n cov(e2,e4) | 86.18887 35.69784 16.22239 156.1553\n cov(e3,e4) | 136.2 48.21199 41.70625 230.6938\n------------------------------------------------------------------------------\nLR test vs. linear model: chi2(14) = 139.19 Prob > chi2 = 0.0000\n\nNote: The reported degrees of freedom assumes the null hypothesis is not on the boundary of the parameter space. If this is not true, then the\n reported test is conservative.\n\n. \n. predict res, rstandard\n\n. \n. list rat time res, sepby(rat)\n\n +------------------------+\n | rat time res |\n |------------------------|\n 1. | 1 0 -.3343025 |\n 2. | 1 1 .5268827 |\n 3. | 1 2 .4992422 |\n 4. | 1 3 .0732094 |\n 5. | 1 4 .8447663 |\n |------------------------|\n 6. | 2 0 -.3185105 |\n 7. | 2 1 -.2071171 |\n 8. | 2 2 1.274912 |\n 9. | 2 3 .7114518 |\n 10. | 2 4 1.215278 |\n |------------------------|\n 11. | 3 0 -.5135215 |\n 12. | 3 1 .0203645 |\n 13. | 3 2 -.5228509 |\n 14. | 3 3 -.8512383 |\n 15. | 3 4 1.808096 |\n |------------------------|\n 16. | 4 0 .4581496 |\n 17. | 4 1 -1.22478 |\n 18. | 4 2 -.9106107 |\n 19. | 4 3 -.7130803 |\n 20. | 4 4 .2519478 |\n |------------------------|\n 21. | 5 0 .3804444 |\n 22. | 5 1 .2287333 |\n 23. | 5 2 .9784756 |\n 24. | 5 3 -.3758776 |\n 25. | 5 4 -.7113822 |\n |------------------------|\n 26. | 6 0 -1.475303 |\n 27. | 6 1 -1.399477 |\n 28. | 6 2 -1.504103 |\n 29. | 6 3 1.288807 |\n 30. | 6 4 -.5631775 |\n |------------------------|\n 31. | 7 0 .473786 |\n 32. | 7 1 -.4318775 |\n 33. | 7 2 .5628197 |\n 34. | 7 3 -1.065117 |\n 35. | 7 4 -1.452405 |\n |------------------------|\n 36. | 8 0 .9371732 |\n 37. | 8 1 1.274058 |\n 38. | 8 2 .9912707 |\n 39. | 8 3 .9466597 |\n 40. | 8 4 -.4890752 |\n |------------------------|\n 41. | 9 0 .1423321 |\n 42. | 9 1 .311183 |\n 43. | 9 2 -.8122606 |\n 44. | 9 3 -.5272216 |\n 45. | 9 4 -1.526507 |\n |------------------------|\n 46. | 10 0 .2497523 |\n 47. | 10 1 .9020303 |\n 48. | 10 2 -.556895 |\n 49. | 10 3 .5124069 |\n 50. | 10 4 .6224594 |\n |------------------------|\n 51. | 18 0 .8534008 |\n 52. | 18 1 -1.234297 |\n 53. | 18 2 .7109886 |\n 54. | 18 3 1.567964 |\n 55. | 18 4 .3556911 |\n |------------------------|\n 56. | 19 0 1.202434 |\n 57. | 19 1 -.9995003 |\n 58. | 19 2 .4767818 |\n 59. | 19 3 .8310238 |\n 60. | 19 4 -.1630251 |\n |------------------------|\n 61. | 20 0 -.7255811 |\n 62. | 20 1 -.987914 |\n 63. | 20 2 1.937267 |\n 64. | 20 3 -1.758109 |\n 65. | 20 4 .6521003 |\n |------------------------|\n 66. | 21 0 -1.101692 |\n 67. | 21 1 2.462107 |\n 68. | 21 2 .2542622 |\n 69. | 21 3 .8310238 |\n 70. | 21 4 -.1630251 |\n |------------------------|\n 71. | 22 0 -1.298645 |\n 72. | 22 1 -.3421695 |\n 73. | 22 2 -1.104759 |\n 74. | 22 3 .5448185 |\n 75. | 22 4 1.170816 |\n |------------------------|\n 76. | 23 0 -1.124267 |\n 77. | 23 1 .0387734 |\n 78. | 23 2 .6711161 |\n 79. | 23 3 -.8830101 |\n 80. | 23 4 -.385332 |\n |------------------------|\n 81. | 24 0 .2229622 |\n 82. | 24 1 -.5032972 |\n 83. | 24 2 .0853191 |\n 84. | 24 3 1.314626 |\n 85. | 24 4 -1.200457 |\n |------------------------|\n 86. | 25 0 2.574736 |\n 87. | 25 1 .5105642 |\n 88. | 25 2 -1.381145 |\n 89. | 25 3 -.8254197 |\n 90. | 25 4 1.170816 |\n |------------------------|\n 91. | 26 0 -.5026115 |\n 92. | 26 1 -.0627333 |\n 93. | 26 2 -.9601486 |\n 94. | 26 3 -1.083703 |\n 95. | 26 4 -1.27456 |\n |------------------------|\n 96. | 27 0 -.1007365 |\n 97. | 27 1 1.118466 |\n 98. | 27 2 -.6896819 |\n 99. | 27 3 -.5392144 |\n100. | 27 4 -.1630251 |\n +------------------------+\n\nI found out the data example I was working with was RatWeight from package heplots, although I was given simply given the "ratlong.csv"-file, which is a heavily manipulated and reordered version of RatWeight, so if you want to reproduce it, here is how (I hope you will bear with me):
rat <- RatWeight\nnames(rat) <- c("Group", "Weight0", "Weight1", "Weight2", "Weight3", "Weight4")\nrat$Group <- factor(rat$Group, levels = c("Control", "Thyroxin", "Thiouracil"))\nrat <- rat[order(rat$Group),]\nrat <- cbind(data.frame(Rat=1:27), rat) |>\n mutate(Rat = factor(Rat))\nrat <- subset(rat, Group != "Thyroxin")\nratlong <- rat |> gather(time, Weight, Weight0:Weight4) |>\n separate(time, c("W", "time"), sep = 6) |>\n mutate(time = as.factor(as.numeric(time))) |>\n mutate(Group = as.factor(as.numeric(Group))) |>\n mutate(Weight = as.double(Weight))\nratlong <- ratlong[with(ratlong, order(Rat, time, Group)),]\nratlong$Weight[89:90] <- c(116,140)\nwrite.csv(ratlong, "ratlong.csv", row.names = FALSE)\n\nPackages used in general:
\nlibrary(lme4)\nlibrary(nlme)\nlibrary(haven)\nlibrary(dplyr)\nlibrary(heplots)\nlibrary(parameters)\nlibrary(tidyverse)\nlibrary(gridExtra)\nlibrary(ggplot2)\n\n", "question_id": 677243, "question_license": "CC BY-SA 4.0", "question_score": 5, "question_text": "I have been tasked with understanding why normalized residuals between R and Stata are different when using mixed models (i.e. the nlme package in R).\n\n\n\n\nWhat I have found is that the residuals are both theoretically computed the same way: norm_residuals = sigma^(-1) * Lambda^(-1/2) * residuals\n\n\n\n\nThis is based on the works of José C. Pinheiro and Douglas M. Bates. The nlme package in R references their book \"Mixed effects models in S and S-PLUS\" (2000), while Stata references their article \"Computational Methods for Multilevel Modelling\" (1998) (see page 575 of \"STATA MULTILEVEL MIXED-EFFECTS REFERENCE MANUAL RELEASE 19 (https://www.stata.com/manuals/me.pdf). The terminology is a bit confusing, as 'normalized' residuals in R are called 'standardized' residuals in stata, which is not to be confused with 'Pearson' residuals, which is what R considers 'standardized').\n\n\n\n\nHowever, the way the matrix square root is computed is different between the two programs. The result can have a rather significant impact on whether or not the normalized residuals actually seem to follow a normal distribution.\n\n\n\n\nThe way R computes the matrix square root is through the Cholesky decomposition A = L*L^T (using the chol function from FORTRAN77). I cannot access the source code for Stata, but it seems like Stata uses Cholesky decomposition as well, however using a Cholesky decomposition algorithm starting at \"the bottom right\" of the matrix instead of \"the top left\" such that A = L^T * L. Using these two methods for Cholesky decomposition, I have been able to recreate the normalised residuals from R and Stata respectively.\n\n\n\n\nWhen using QQ-plots on the normalized residuals calculated with R and those calculated with Stata, the two results plots imply different conclusions about the normality of the residuals.\n\n\n\n\nIn principle, could one not use several different methods for Cholesky decomposition to compute a matrix square root and therefore come to significantly different conclusions? Would it therefore not be preferable to use eigenvalue decomposition to compute a matrix square root as opposed to Cholesky decomposition? One reason I believe EVD would be better is that it does not require transposing one \"square root\", i.e. we have directly that A^(1/2) * A^(1/2) = A.\n\n\n\n\nHere, I have added an example:\n\n\n\n\nratlong <- read.csv(\"ratlong.csv\") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n weights = varIdent(form = ~ 1 | time),\n na.action = na.exclude,\n method = \"REML\",\n data = ratlong)\n\nsummary(model)\nparameters(model)\ngetVarCov(model)\n\ntmp <- mutate(\n ratlong,\n fit = fitted(model),\n response = residuals(model, type = \"r\"),\n pearson = residuals(model, type = \"p\"),\n norm_res_R = residuals(model, type = \"n\"),\n norm_res_stata = c(\n -.3343025, .5268827, .4992422, .0732094, .8447663,\n -.3185105, -.2071171, 1.274912, .7114518, 1.215278,\n -.5135215, .0203645, -.5228509, -.8512383, 1.808096,\n .4581496, -1.22478, -.9106107, -.7130803, .2519478,\n .3804444, .2287333, .9784756, -.3758776, -.7113822,\n -1.475303, -1.399477, -1.504103, 1.288807, -.5631775,\n .473786, -.4318775, .5628197, -1.065117, -1.452405,\n .9371732, 1.274058, .9912707, .9466597, -.4890752,\n .1423321, .311183, -.8122606, -.5272216, -1.526507,\n .2497523, .9020303, -.556895, .5124069, .6224594,\n .8534008, -1.234297, .7109886, 1.567964, .3556911,\n 1.202434, -.9995003, .4767818, .8310238, -.1630251,\n -.7255811, -.987914, 1.937267, -1.758109, .6521003,\n -1.101692, 2.462107, .2542622, .8310238, -.1630251,\n -1.298645, -.3421695, -1.104759, .5448185, 1.170816,\n -1.124267, .0387734, .6711161, -.8830101, -.385332,\n .2229622, -.5032972, .0853191, 1.314626, -1.200457,\n 2.574736, .5105642, -1.381145, -.8254197, 1.170816,\n -.5026115, -.0627333, -.9601486, -1.083703, -1.27456,\n -.1007365, 1.118466, -.6896819, -.5392144, -.1630251)\n)\n\n# Here we observe that the pearson residual is approximately equal to the \n# normalized at time 1 for R and time 5 for stata\ntmp$pearson[seq(5, nrow(ratlong), 5)] - \n tmp$norm_res_stata[seq(5, nrow(ratlong), 5)]\ntmp$pearson[seq(1, nrow(ratlong), 5)] - \n tmp$norm_res_R[seq(1, nrow(ratlong), 5)]\n\n\n\n\n\nAccording to the nmle package (retrieved from github (https://github.com/cran/nlme)), the residuals are computed as such:\n\n\n\n\n#### from residuals.gls\nval <- object$residuals\nif (type != \"response\") {\n val <- val/attr(val, \"std\")\n lab <- \"Standardized residuals\"\n if (type == \"normalized\") {\nif (!is.null(cSt <- object$modelStruct$corStruct)) {\n ## normalize according to inv-trans factor\n val <- recalc(cSt, list(Xy = as.matrix(val)))$Xy[, 1]\n lab <- \"Normalized residuals\"\n }\n }\n}\n \n#### from recalc.corSymm\nrecalc.corSymm <- function(object, conLin, ...)\n{\n val <-\n .C(symm_recalc,\n Xy = as.double(conLin[[\"Xy\"]]),\n as.integer(unlist(Dim(object))),\n as.integer(ncol(conLin[[\"Xy\"]])),\n as.double(as.vector(object)),\n as.integer(unlist(getCovariate(object))),\n as.integer(attr(object, \"maxCov\")),\n logLik = double(1))[c(\"Xy\", \"logLik\")]\n conLin[[\"Xy\"]][] <- val[[\"Xy\"]]\n conLin[[\"logLik\"]] <- conLin[[\"logLik\"]] + val[[\"logLik\"]]\n conLin\n}\n \n#### from symm_recalc (written in C)\nvoid\nsymm_recalc(double *Xy, int *pdims, int *ZXcol, double *pars,\n int *time, int *maxC, double *logdet)\n{\n int N = pdims[0], M = pdims[1], *len = pdims + 4, *start = len + M, i;\n double *crr = R_Calloc(*maxC * (*maxC - 1) / 2, double);\n /* parameters assumed in unconstrained form */\n symm_fullCorr(pars, maxC, crr); /* get all correlations (not correlation \n matrix) */\n for(i = 0; i < M; i++) {\n double *Factor = R_Calloc((len[i] * len[i]), double);\n symm_fact(crr, time + start[i], &len[i], maxC, Factor, logdet);\n mult_mat(Xy + start[i], N, Factor, len[i], len[i], len[i],\n Xy + start[i], N, *ZXcol);\n R_Free(Factor);\n }\n R_Free(crr);\n}\n \n#### from symm_fact (also written in C)\nstatic void\nsymm_fact(double *crr, int *time, int *n, int *maxC, double *mat,\n double *logdet)\n{\n int job = 11L, info, i, nsq = *n * (*n), np1 = *n + 1;\n double *work = R_Calloc(*n, double), *work1 = R_Calloc(nsq, double);\n symm_mat(crr, time, n, maxC, mat); /* make full symmetric correlation \n matrix for individual i */\n F77_CALL(chol) (mat, n, n, mat, &info); /* Cholesky decomposition */\n for(i = 0; i < *n; i++) {\n work1[i * np1] = 1; /* set diag to 1 in empty matrix (i.e. create \n identity matrix) */\n F77_CALL(dtrsl) (mat, n, n, work1 + i * (*n), &job, &info); /* solves \n linear system given triangular matrix */\n *logdet -= log(fabs(mat[i * np1]));\n }\n Memcpy(mat, work1, nsq); \n R_Free(work); R_Free(work1);\n}\n\n\n\n\n\nI then manually computed the normalized residuals in R, through a regular Cholesky decomposition (same as t(chol) in R), through a \"reverse\" Cholesky decomposition and through EVD.\n\n\n\n\n# regular Cholesky algorithm (same as t(chol) for base R's chol function)\n regChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in 1:n){\n if (j == 1){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[j,1:(j-1)]^2))\n }\n if (j == 1){\n for (i in (j+1):n){\n L[i,j] = A[i,j]/L[j,j]\n }\n } else if (j < n){\n for (i in (j+1):n){\n L[i,j] = (A[i,j]-sum(L[i,1:(j-1)]*L[j,1:(j-1)]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \n # reverse Cholesky algorithm\n revChol <- function(A){\n n = nrow(A)\n L = matrix(0,n,n)\n for (j in n-0:(n-1)){\n if (j == n){\n L[j,j] = sqrt(A[j,j])\n } else{\n L[j,j] = sqrt(A[j,j] - sum(L[(j+1):n,j]^2))\n }\n if (j == n){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = A[j,i]/L[j,j]\n }\n } else if (j > 1){\n for (i in n-(n-j+1):(n-1)){\n L[j,i] = (A[j,i]-sum(L[(j+1):n,i]*L[(j+1):n,j]))/L[j,j]\n }\n }\n }\n return(L)\n }\n \ncorMat <- model$modelStruct$corStruct #correlation structure of type corSymm\n \npdims <- as.integer(unlist(Dim(corMat))) #dimensions of correlation matrices\ncorMatFull <- corMatrix(corMat) #full correlation matrix\n ############################################################################\n#### Compute normalized residuals\n\n# `Using reverse Cholesky decomposition (gives same values as stata)\n\nnormres1 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n L <- revChol(A) # lower triangular / square root\n invSqLambda <- solve(t(L)) # invert L -- if regular Cholesky: use solve(L)\n normres1[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nt(L) %*% L #returns correlation matrix A given reversed Cholesky\n\n#Using regular Cholesky decomposition (gives same values as R)\nnormres2 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] #observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) #total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) #correlation matrix\n L <- t(chol(A)) \n # lower triangular / square root -- note that regChol(A) = t(chol(A))\n invSqLambda <- solve(L) # invert L -- if regular Cholesky: use solve(L)\n normres2[dim2:(dim2 + dim-1)] <- \n invSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\nL %*% t(L) #returns correlation matrix given standard Cholesky\n\n# Using EVD\nnormres3 = 1:pdims[2]\nfor (i in 1:pdims[2]){\n dim <- pdims[i+4] # observations for individual i\n dim2 <- (pdims[i+4+pdims[2]]+1) # total observations up to individual i\n A <- matrix(unlist(corMatFull[i]), ncol = dim) # correlation matrix\n E <- eigen(A) # EVD eigenvalue decomposition\n sqrtA <- E$vectors %*% sqrt(diag(E$values)) %*% t(E$vectors) \n# matrix square root\n invSqLambda <- solve(sqrtA) # invert sqrtA\n normres3[dim2:(dim2 + dim-1)] <- \ninvSqLambda %*% tmp$pearson[dim2:(dim2 + dim-1)] \n # multiply inverse square root with standardized residuals\n}\n\nround(normres1 - tmp$norm_res_stata, digits = 5) \n# approx 0 when using reverse Cholesky\nround(normres2 - tmp$norm_res_R, digits = 15) \n # approx 0 when using regular Cholesky\n \n##### will add qqplots/histograms with results in a couple of days\n\n\n\n\n\nThe results on the rat-example imply a left or a right-skew (Stata and R respecitvely) when compared to the standard normal, i.e. they may lead to different conlclusions about the model fit (I have an example, wherein the difference is more pronounced, but I do not want to break GDPR rules. Maybe someone can find a better example?). Using EVD, there does not seem to be as much of a skew to one side or the other.\n\n\n\n\n[image: QQ-plot of normalized residuals with each method compared to standard normal; source: https://i.sstatic.net/65PG6zuB.png] (https://i.sstatic.net/65PG6zuB.png)\n\n\n\n\n[image: Histogram of normalized residuals with each method compared to standard normal; source: https://i.sstatic.net/XWUljnac.png] (https://i.sstatic.net/XWUljnac.png)\n\n\n\n\nThe figures are created via:\n\n\n\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(sample = tmp$norm_res_stata)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals stata\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(sample = tmp$norm_res_R)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals R\")\nplot3 <- ggplot(as.data.frame(normres3), aes(sample = normres3)) +\n stat_qq() +\n geom_abline(slope = 1, intercept = 0) + \n labs(y = \"normalized residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\nplot1 <- ggplot(as.data.frame(tmp$norm_res_stata), aes(x = tmp$norm_res_stata)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals stata (reverse Cholesky)\")\nplot2 <- ggplot(as.data.frame(tmp$norm_res_R), aes(x = tmp$norm_res_R)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals R (standard Cholesky)\")\nplot3 <- ggplot(as.data.frame(normres3), aes(x = normres3)) +\n geom_histogram(aes(y =..density..), binwidth = 0.4, color = \"black\", fill = \"white\") + \n stat_function(fun = dnorm, args = list(mean = 0, sd = 1)) +\n labs(x = \"normalised residuals EVD\")\ngrid.arrange(plot1, plot2, plot3, ncol = 3)\n\n\n\n\n\nThe log from the Stata-code is given here:\n\n\n\n\n. \n. \n. import delim \"ratlong.csv\", clear \n(encoding automatically selected: ISO-8859-1)\n(5 vars, 100 obs)\n\n. \n. mixed weight b1.group##b0.time || rat: , reml baselev nocons res(un, t(time))\n\nPerforming gradient-based optimization: \nIteration 0: Log restricted-likelihood = -346.35796 (not concave)\nIteration 1: Log restricted-likelihood = -284.80839 (not concave)\nIteration 2: Log restricted-likelihood = -281.13028 \nIteration 3: Log restricted-likelihood = -278.4598 \nIteration 4: Log restricted-likelihood = -276.85378 \nIteration 5: Log restricted-likelihood = -276.76319 \nIteration 6: Log restricted-likelihood = -276.76264 \nIteration 7: Log restricted-likelihood = -276.76264 \n\nComputing standard errors ...\n\nMixed-effects REML regression Number of obs = 100\nGroup variable: rat Number of groups = 20\n Obs per group:\n min = 5\n avg = 5.0\n max = 5\n Wald chi2(9) = 1277.34\nLog restricted-likelihood = -276.76264 Prob > chi2 = 0.0000\n\n------------------------------------------------------------------------------\n weight | Coefficient Std. err. z P>|z| [95% conf. interval]\n-------------+----------------------------------------------------------------\n group |\n 1 | 0 (base)\n 3 | .7 2.270827 0.31 0.758 -3.75074 5.15074\n |\n time |\n 0 | 0 (base)\n 1 | 24.5 1.61744 15.15 0.000 21.32988 27.67012\n 2 | 52 2.045184 25.43 0.000 47.99151 56.00849\n 3 | 76.1 3.11002 24.47 0.000 70.00447 82.19553\n 4 | 106.6 4.073561 26.17 0.000 98.61597 114.584\n |\n group#time |\n 3 1 | -2.9 2.287405 -1.27 0.205 -7.383232 1.583232\n 3 2 | -10.9 2.892328 -3.77 0.000 -16.56886 -5.231142\n 3 3 | -22.4 4.398233 -5.09 0.000 -31.02038 -13.77962\n 3 4 | -37.1 5.760885 -6.44 0.000 -48.39113 -25.80887\n |\n _cons | 54 1.605717 33.63 0.000 50.85285 57.14715\n------------------------------------------------------------------------------\n\n------------------------------------------------------------------------------\n Random-effects parameters | Estimate Std. err. [95% conf. interval]\n-----------------------------+------------------------------------------------\nrat: (empty) |\n-----------------------------+------------------------------------------------\nResidual: Unstructured |\n var(e0) | 25.78329 8.592901 13.41698 49.54749\n var(e1) | 77.81102 25.92904 40.49434 149.5161\n var(e2) | 85.31105 28.41546 44.41058 163.8793\n var(e3) | 127.9611 42.64015 66.59387 245.8791\n var(e4) | 182.1112 60.70111 94.75779 349.9921\n cov(e0,e1) | 38.7166 13.95059 11.37394 66.05925\n cov(e0,e2) | 34.63327 13.73195 7.719139 61.5474\n cov(e0,e3) | 28.51106 15.09849 -1.081436 58.10355\n cov(e0,e4) | 20.97774 16.87309 -12.09292 54.04839\n cov(e1,e2) | 71.47769 25.52878 21.44219 121.5132\n cov(e1,e3) | 56.73882 27.02632 3.768207 109.7094\n cov(e1,e4) | 42.8555 29.78855 -15.52898 101.24\n cov(e2,e3) | 89.65551 32.42749 26.09881 153.2122\n cov(e2,e4) | 86.18887 35.69784 16.22239 156.1553\n cov(e3,e4) | 136.2 48.21199 41.70625 230.6938\n------------------------------------------------------------------------------\nLR test vs. linear model: chi2(14) = 139.19 Prob > chi2 = 0.0000\n\nNote: The reported degrees of freedom assumes the null hypothesis is not on the boundary of the parameter space. If this is not true, then the\n reported test is conservative.\n\n. \n. predict res, rstandard\n\n. \n. list rat time res, sepby(rat)\n\n +------------------------+\n | rat time res |\n |------------------------|\n 1. | 1 0 -.3343025 |\n 2. | 1 1 .5268827 |\n 3. | 1 2 .4992422 |\n 4. | 1 3 .0732094 |\n 5. | 1 4 .8447663 |\n |------------------------|\n 6. | 2 0 -.3185105 |\n 7. | 2 1 -.2071171 |\n 8. | 2 2 1.274912 |\n 9. | 2 3 .7114518 |\n 10. | 2 4 1.215278 |\n |------------------------|\n 11. | 3 0 -.5135215 |\n 12. | 3 1 .0203645 |\n 13. | 3 2 -.5228509 |\n 14. | 3 3 -.8512383 |\n 15. | 3 4 1.808096 |\n |------------------------|\n 16. | 4 0 .4581496 |\n 17. | 4 1 -1.22478 |\n 18. | 4 2 -.9106107 |\n 19. | 4 3 -.7130803 |\n 20. | 4 4 .2519478 |\n |------------------------|\n 21. | 5 0 .3804444 |\n 22. | 5 1 .2287333 |\n 23. | 5 2 .9784756 |\n 24. | 5 3 -.3758776 |\n 25. | 5 4 -.7113822 |\n |------------------------|\n 26. | 6 0 -1.475303 |\n 27. | 6 1 -1.399477 |\n 28. | 6 2 -1.504103 |\n 29. | 6 3 1.288807 |\n 30. | 6 4 -.5631775 |\n |------------------------|\n 31. | 7 0 .473786 |\n 32. | 7 1 -.4318775 |\n 33. | 7 2 .5628197 |\n 34. | 7 3 -1.065117 |\n 35. | 7 4 -1.452405 |\n |------------------------|\n 36. | 8 0 .9371732 |\n 37. | 8 1 1.274058 |\n 38. | 8 2 .9912707 |\n 39. | 8 3 .9466597 |\n 40. | 8 4 -.4890752 |\n |------------------------|\n 41. | 9 0 .1423321 |\n 42. | 9 1 .311183 |\n 43. | 9 2 -.8122606 |\n 44. | 9 3 -.5272216 |\n 45. | 9 4 -1.526507 |\n |------------------------|\n 46. | 10 0 .2497523 |\n 47. | 10 1 .9020303 |\n 48. | 10 2 -.556895 |\n 49. | 10 3 .5124069 |\n 50. | 10 4 .6224594 |\n |------------------------|\n 51. | 18 0 .8534008 |\n 52. | 18 1 -1.234297 |\n 53. | 18 2 .7109886 |\n 54. | 18 3 1.567964 |\n 55. | 18 4 .3556911 |\n |------------------------|\n 56. | 19 0 1.202434 |\n 57. | 19 1 -.9995003 |\n 58. | 19 2 .4767818 |\n 59. | 19 3 .8310238 |\n 60. | 19 4 -.1630251 |\n |------------------------|\n 61. | 20 0 -.7255811 |\n 62. | 20 1 -.987914 |\n 63. | 20 2 1.937267 |\n 64. | 20 3 -1.758109 |\n 65. | 20 4 .6521003 |\n |------------------------|\n 66. | 21 0 -1.101692 |\n 67. | 21 1 2.462107 |\n 68. | 21 2 .2542622 |\n 69. | 21 3 .8310238 |\n 70. | 21 4 -.1630251 |\n |------------------------|\n 71. | 22 0 -1.298645 |\n 72. | 22 1 -.3421695 |\n 73. | 22 2 -1.104759 |\n 74. | 22 3 .5448185 |\n 75. | 22 4 1.170816 |\n |------------------------|\n 76. | 23 0 -1.124267 |\n 77. | 23 1 .0387734 |\n 78. | 23 2 .6711161 |\n 79. | 23 3 -.8830101 |\n 80. | 23 4 -.385332 |\n |------------------------|\n 81. | 24 0 .2229622 |\n 82. | 24 1 -.5032972 |\n 83. | 24 2 .0853191 |\n 84. | 24 3 1.314626 |\n 85. | 24 4 -1.200457 |\n |------------------------|\n 86. | 25 0 2.574736 |\n 87. | 25 1 .5105642 |\n 88. | 25 2 -1.381145 |\n 89. | 25 3 -.8254197 |\n 90. | 25 4 1.170816 |\n |------------------------|\n 91. | 26 0 -.5026115 |\n 92. | 26 1 -.0627333 |\n 93. | 26 2 -.9601486 |\n 94. | 26 3 -1.083703 |\n 95. | 26 4 -1.27456 |\n |------------------------|\n 96. | 27 0 -.1007365 |\n 97. | 27 1 1.118466 |\n 98. | 27 2 -.6896819 |\n 99. | 27 3 -.5392144 |\n100. | 27 4 -.1630251 |\n +------------------------+\n\n\n\n\n\nI found out the data example I was working with was RatWeight from package heplots, although I was given simply given the \"ratlong.csv\"-file, which is a heavily manipulated and reordered version of RatWeight, so if you want to reproduce it, here is how (I hope you will bear with me):\n\n\n\n\nrat <- RatWeight\nnames(rat) <- c(\"Group\", \"Weight0\", \"Weight1\", \"Weight2\", \"Weight3\", \"Weight4\")\nrat$Group <- factor(rat$Group, levels = c(\"Control\", \"Thyroxin\", \"Thiouracil\"))\nrat <- rat[order(rat$Group),]\nrat <- cbind(data.frame(Rat=1:27), rat) |>\n mutate(Rat = factor(Rat))\nrat <- subset(rat, Group != \"Thyroxin\")\nratlong <- rat |> gather(time, Weight, Weight0:Weight4) |>\n separate(time, c(\"W\", \"time\"), sep = 6) |>\n mutate(time = as.factor(as.numeric(time))) |>\n mutate(Group = as.factor(as.numeric(Group))) |>\n mutate(Weight = as.double(Weight))\nratlong <- ratlong[with(ratlong, order(Rat, time, Group)),]\nratlong$Weight[89:90] <- c(116,140)\nwrite.csv(ratlong, \"ratlong.csv\", row.names = FALSE)\n\n\n\n\n\nPackages used in general:\n\n\n\n\nlibrary(lme4)\nlibrary(nlme)\nlibrary(haven)\nlibrary(dplyr)\nlibrary(heplots)\nlibrary(parameters)\nlibrary(tidyverse)\nlibrary(gridExtra)\nlibrary(ggplot2)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T09:39:51+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "7BC8F667-EB32-47A1-A802-2154A3633C12", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7BC8F667-EB32-47A1-A802-2154A3633C12/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T17:05:33+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "2EFBF184-EFA4-4618-B902-9EB0CF6CDAD1", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2EFBF184-EFA4-4618-B902-9EB0CF6CDAD1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-23T18:51:05+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "CFD9707D-EF4E-4CBF-A2FA-FC17B82ADC40", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CFD9707D-EF4E-4CBF-A2FA-FC17B82ADC40/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T21:15:18+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "DDCD4DF6-217B-4BCA-B9AB-A089EF38A03D", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/DDCD4DF6-217B-4BCA-B9AB-A089EF38A03D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T21:24:18+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "3E87BF4C-CB4D-492F-89AD-9AAEF44DF12F", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/3E87BF4C-CB4D-492F-89AD-9AAEF44DF12F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T21:36:28+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "2160C566-F067-48AE-8E37-5DC1331F1A3F", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/2160C566-F067-48AE-8E37-5DC1331F1A3F/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-23T21:51:58+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "30322FB2-132C-405E-8E54-9D57208C3C4C", "revision_number": 7, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/30322FB2-132C-405E-8E54-9D57208C3C4C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "kjetil b halvorsen", "profile_url": "https://stats.stackexchange.com/users/11887/kjetil-b-halvorsen", "user_type": "moderator"}, "created_at": "2026-09-24T00:39:52+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "A600B7A7-BD08-4855-A958-0D2321246CA5", "revision_number": 8, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/A600B7A7-BD08-4855-A958-0D2321246CA5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-25T07:33:22+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "F655028C-4705-4B3D-BB65-71C57A6831E2", "revision_number": 9, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/F655028C-4705-4B3D-BB65-71C57A6831E2/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael", "profile_url": "https://stats.stackexchange.com/users/517013/michael", "user_type": "registered"}, "created_at": "2026-09-25T10:01:55+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "7549E095-451B-4062-AE3C-66AA61B7671C", "revision_number": 10, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/7549E095-451B-4062-AE3C-66AA61B7671C/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677243/normalized-residuals-in-mixed-models-r-nlme-vs-stata", "split": "train", "split_group": "598fe845d8f6ec9dfd2ba93f72b05bd7499c42da4f6a46494a772e71b8f59550", "tags": ["r", "mixed-model", "residuals", "stata", "normalization"], "thread_id": "stats:677243", "title": "Normalized residuals in mixed models, R (nlme) vs Stata"}}
{"accepted_answer": {"answer_html": "I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.
\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.
\nAs usual, @whuber has provided an excellent answer to this question. Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:
\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.
\n
I wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:
## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.
Now, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.
\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting. My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!
\n", "answer_id": 677263, "answer_text": "UPDATE\n\n\n\n\nI realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.\n\n\n\n\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.\n\n\n\n\n\n\n\nAs usual, @whuber has provided an excellent answer to this question (https://stats.stackexchange.com/a/159203/97844). Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:\n\n\n\n\n\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.\n\n\n\n\n\n\n\nI wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:\n\n\n\n\n## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\n\n\n\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.\n\n\n\n\nNow, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.\n\n\n\n\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting (https://stats.stackexchange.com/a/45764/97844). My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!", "answer_url": "https://stats.stackexchange.com/a/677263", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T13:44:43+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": 677262, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:44:43+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D364CE58-9CC7-407D-B6A6-CA7B48039B16", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D364CE58-9CC7-407D-B6A6-CA7B48039B16/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:54:35+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "311A980C-8FF9-4553-B91E-EB438CA49CF5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/311A980C-8FF9-4553-B91E-EB438CA49CF5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T15:56:42+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "63585334-0D98-4386-B087-8A28FC121807", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/63585334-0D98-4386-B087-8A28FC121807/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T17:46:48+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D32B7BD3-C3DC-4992-8803-1AE622335BD6", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D32B7BD3-C3DC-4992-8803-1AE622335BD6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T19:02:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "FEC7CF2B-92E8-41E2-A10B-658E5657A289", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEC7CF2B-92E8-41E2-A10B-658E5657A289/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-27T15:15:15+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "64ED3E27-F5FD-4A41-AA22-C4265D46E82F", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/64ED3E27-F5FD-4A41-AA22-C4265D46E82F/view-source"}], "score": 7, "updated_at": "2026-09-27T15:15:15+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677263, "sha256": "f3ee2830cd1580e0244d6f7f0f251ec8fa978cc823ab30ab52e174bd98dee53d", "source_url": "https://stats.stackexchange.com/a/677263"}], "other_answers": [], "product": "code_qa", "question": "I'm writing my medical thesis and I want to test our research group's hypothesis that the width of the foramen magnum can predict response or non-response to a certain surgical intervention in a neurological disease. The sample is however quite small (only 23 patients) so any biological signal whould have to be quite strong to cut through the noise.\n\n\n\n\nI asked stats support who wanted me to \"find some exact version of the ROC analysis, some analogue to Fisher's exact test\", but I can't really find anything like that in the literature. Generative AI tends to point me towards Mann-Whitney U-tests, exact logistic regression and/or Firth regression, but cannot point me towards any supporting literature.\n\n\n\n\nIntuitively that's not a bad idea. I might test if the FM width is normally distributed with Shapiro-Wilk, then test for differences with t-test/U-test depending on distribution and only then proceed towards ROC-analyses/logistic regression if an interesting pattern emerges.\n\n\n\n\nBut I will have to motivate the chosen approach formally. Is there an actual recommended approach? Is there any literature discussing the pros and cons of different strategies given this particular dilemma?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677262", "selected_answer": {"answer_html": "I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.
\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.
\nAs usual, @whuber has provided an excellent answer to this question. Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:
\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.
\n
I wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:
## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.
Now, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.
\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting. My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!
\n", "answer_id": 677263, "answer_text": "UPDATE\n\n\n\n\nI realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.\n\n\n\n\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.\n\n\n\n\n\n\n\nAs usual, @whuber has provided an excellent answer to this question (https://stats.stackexchange.com/a/159203/97844). Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:\n\n\n\n\n\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.\n\n\n\n\n\n\n\nI wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:\n\n\n\n\n## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\n\n\n\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.\n\n\n\n\nNow, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.\n\n\n\n\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting (https://stats.stackexchange.com/a/45764/97844). My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!", "answer_url": "https://stats.stackexchange.com/a/677263", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T13:44:43+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": 677262, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:44:43+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D364CE58-9CC7-407D-B6A6-CA7B48039B16", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D364CE58-9CC7-407D-B6A6-CA7B48039B16/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:54:35+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "311A980C-8FF9-4553-B91E-EB438CA49CF5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/311A980C-8FF9-4553-B91E-EB438CA49CF5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T15:56:42+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "63585334-0D98-4386-B087-8A28FC121807", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/63585334-0D98-4386-B087-8A28FC121807/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T17:46:48+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D32B7BD3-C3DC-4992-8803-1AE622335BD6", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D32B7BD3-C3DC-4992-8803-1AE622335BD6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T19:02:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "FEC7CF2B-92E8-41E2-A10B-658E5657A289", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEC7CF2B-92E8-41E2-A10B-658E5657A289/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-27T15:15:15+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "64ED3E27-F5FD-4A41-AA22-C4265D46E82F", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/64ED3E27-F5FD-4A41-AA22-C4265D46E82F/view-source"}], "score": 7, "updated_at": "2026-09-27T15:15:15+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677263, "answers": [{"answer_html": "I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.
\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.
\nAs usual, @whuber has provided an excellent answer to this question. Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:
\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.
\n
I wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:
## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.
Now, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.
\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting. My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!
\n", "answer_id": 677263, "answer_text": "UPDATE\n\n\n\n\nI realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up to you. Logistic regression in this case would probably work out ok because you're not likely to overfit with your continuous single predictor. You may end up with a poor classifier in terms of discrimination, but you can still do it. The issue that the statistician may be talking about is how to obtain good predicted probabilities from a small sample. ROC itself is not an asymptotic method, but the usual MLE methods for logistic regression are. Firth regression will produce biased estimates, which will be fine for prediction, but I don't think you'd need to use that method unless you have complete separation. If there is any overlap in the distribution of widths between the two groups, then you won't have an issue with MLE.\n\n\n\n\nBelow I discuss the other part: two-sample comparisons with the binary variable as the grouping variable v. logistic regression with the binary variable as the outcome.\n\n\n\n\n\n\n\nAs usual, @whuber has provided an excellent answer to this question (https://stats.stackexchange.com/a/159203/97844). Note that results will be slightly different as they're not all equivalent, whereas if you performed linear regression with a binary predictor and a continuous outcome, the results are just a re-parameterized version of a $t$-test in that case. From Whuber's answer:\n\n\n\n\n\n\n\nA t-test detects whether the average ages differ between no-and yes-respondents in the population. A logistic regression estimates how the response rate varies by age. As such it is more flexible and capable of supplying more detailed information than the t-test is. On the other hand, it tends to be less powerful than the t-test for the basic purpose of detecting a difference between the average ages in the groups.\n\n\n\n\n\n\n\nI wanted to further illustrate this in a small sample, where the data generating process is Poisson (though with a very large $\\lambda$). Here's a little simulation in R:\n\n\n\n\n## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data = d)\nt.test(width ~ outcome, var.equal = TRUE) # ordinary\nt.test(width ~ outcome, var.equal = FALSE) # Welch\nwilcox.test(x = g1, y = g2) # Mann-Whitney\n\n\n\n\n\nYou'll note that the $p$-values among the two t.test calls and wilcox.test are very very close (in order: $0.0037, 0.0036, 0.0026$). This remains true even with different seeds. So at least, numerically, without a normally distributed data generating process, the three two-sample tests agree quite well. That is, no need to use Shapiro-Wilk if you don't want to.\n\n\n\n\nNow, the logistic regression is quite different. In this case, the $p$-value is larger ($0.0276$), and of course, we're testing something very different from the other three tests. We've now parameterized the problem as predicting the log-odds of being a responder as a (linear) function of width. The qualitative answer is the same: greater width associates with greater log-odds of response, but that's just how I generated the data.\n\n\n\n\nIt's not immediately obvious to me why the logistic model has lower power, except for the oft-quoted rules of thumb for avoiding overfitting (https://stats.stackexchange.com/a/45764/97844). My intuition is that it has something to do with the differences in how standard errors are computed in the two cases. I will edit once I get to the bottom of that!", "answer_url": "https://stats.stackexchange.com/a/677263", "author": "Rick Hass", "author_url": "https://stats.stackexchange.com/users/97844/rick-hass", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-25T13:44:43+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": 677262, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:44:43+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D364CE58-9CC7-407D-B6A6-CA7B48039B16", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D364CE58-9CC7-407D-B6A6-CA7B48039B16/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T13:54:35+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "311A980C-8FF9-4553-B91E-EB438CA49CF5", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/311A980C-8FF9-4553-B91E-EB438CA49CF5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T15:56:42+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "63585334-0D98-4386-B087-8A28FC121807", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/63585334-0D98-4386-B087-8A28FC121807/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T17:46:48+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D32B7BD3-C3DC-4992-8803-1AE622335BD6", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D32B7BD3-C3DC-4992-8803-1AE622335BD6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-25T19:02:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "FEC7CF2B-92E8-41E2-A10B-658E5657A289", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/FEC7CF2B-92E8-41E2-A10B-658E5657A289/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rick Hass", "profile_url": "https://stats.stackexchange.com/users/97844/rick-hass", "user_type": "registered"}, "created_at": "2026-09-27T15:15:15+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "64ED3E27-F5FD-4A41-AA22-C4265D46E82F", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/64ED3E27-F5FD-4A41-AA22-C4265D46E82F/view-source"}], "score": 7, "updated_at": "2026-09-27T15:15:15+00:00"}], "domain": "statistics", "external_links": [], "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": "Magnus", "question_author_url": "https://stats.stackexchange.com/users/91971/magnus", "question_author_user_type": "registered", "question_created_at": "2026-09-25T12:51:07+00:00", "question_html": "I'm writing my medical thesis and I want to test our research group's hypothesis that the width of the foramen magnum can predict response or non-response to a certain surgical intervention in a neurological disease. The sample is however quite small (only 23 patients) so any biological signal whould have to be quite strong to cut through the noise.
\nI asked stats support who wanted me to "find some exact version of the ROC analysis, some analogue to Fisher's exact test", but I can't really find anything like that in the literature. Generative AI tends to point me towards Mann-Whitney U-tests, exact logistic regression and/or Firth regression, but cannot point me towards any supporting literature.
\nIntuitively that's not a bad idea. I might test if the FM width is normally distributed with Shapiro-Wilk, then test for differences with t-test/U-test depending on distribution and only then proceed towards ROC-analyses/logistic regression if an interesting pattern emerges.
\nBut I will have to motivate the chosen approach formally. Is there an actual recommended approach? Is there any literature discussing the pros and cons of different strategies given this particular dilemma?
\n", "question_id": 677262, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "I'm writing my medical thesis and I want to test our research group's hypothesis that the width of the foramen magnum can predict response or non-response to a certain surgical intervention in a neurological disease. The sample is however quite small (only 23 patients) so any biological signal whould have to be quite strong to cut through the noise.\n\n\n\n\nI asked stats support who wanted me to \"find some exact version of the ROC analysis, some analogue to Fisher's exact test\", but I can't really find anything like that in the literature. Generative AI tends to point me towards Mann-Whitney U-tests, exact logistic regression and/or Firth regression, but cannot point me towards any supporting literature.\n\n\n\n\nIntuitively that's not a bad idea. I might test if the FM width is normally distributed with Shapiro-Wilk, then test for differences with t-test/U-test depending on distribution and only then proceed towards ROC-analyses/logistic regression if an interesting pattern emerges.\n\n\n\n\nBut I will have to motivate the chosen approach formally. Is there an actual recommended approach? Is there any literature discussing the pros and cons of different strategies given this particular dilemma?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Magnus", "profile_url": "https://stats.stackexchange.com/users/91971/magnus", "user_type": "registered"}, "created_at": "2026-09-25T12:51:07+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "1AFA5A57-BDDE-474E-91DC-1D2E2378AE47", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/1AFA5A57-BDDE-474E-91DC-1D2E2378AE47/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Nick Cox", "profile_url": "https://stats.stackexchange.com/users/22047/nick-cox", "user_type": "registered"}, "created_at": "2026-09-25T12:59:42+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "64F69FAD-C7B9-4C46-B108-F7598EB068D1", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/64F69FAD-C7B9-4C46-B108-F7598EB068D1/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-25T21:01:14+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C4BCF8DD-9A97-4832-BA8D-BAF89A4AF37C", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/C4BCF8DD-9A97-4832-BA8D-BAF89A4AF37C/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677262/binary-response-variable-with-one-continuous-independent-variable-in-small-sampl", "split": "train", "split_group": "1e66b45b615abb7305245529ef0b62a715e6d164ab6bdac80764f20b0da6fe64", "tags": ["binary-data", "small-sample"], "thread_id": "stats:677262", "title": "Binary response variable with one continuous independent variable in small sample?"}} {"accepted_answer": {"answer_html": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$
\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$
\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question, having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.
\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.
\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$
\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667 \n\n", "answer_id": 677268, "answer_text": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$\n\n\n\n\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$\n\n\n\n\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question (https://stats.stackexchange.com/q/677226/2958), having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.\n\n\n\n\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.\n\n\n\n\n\n\n\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$\n\n\n\n\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667", "answer_url": "https://stats.stackexchange.com/a/677268", "author": "Henry", "author_url": "https://stats.stackexchange.com/users/2958/henry", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T14:10:23+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": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Henry", "profile_url": "https://stats.stackexchange.com/users/2958/henry", "user_type": "registered"}, "created_at": "2026-09-26T14:10:23+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C96EACA9-97B0-4929-B972-DA5D20ED4759", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C96EACA9-97B0-4929-B972-DA5D20ED4759/view-source"}], "score": 4, "updated_at": "2026-09-26T14:10:23+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "set.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals) {\n max_var <- mu * (1 - mu)\n for (v in 1:n_var) {\n tau2 <- (v / (n_var + 1)) * max_var\n scenarios <- rbind(scenarios, data.frame(mu = mu, tau2 = tau2))\n }\n}\n\n\ncalc_mean <- function(ybar_i) {\n mean(ybar_i)\n}\n\ncalc_var_of_mean <- function(ybar_i) {\n n <- length(ybar_i)\n var(ybar_i) / n\n}\n\ncalc_coverage <- function(lower, upper, mu) {\n mean(lower <= mu & mu <= upper)\n}\n\ncalc_avg_ci_length <- function(lower, upper) {\n mean(upper - lower)\n}\n\nresults <- data.frame()\n\nfor (s in 1:nrow(scenarios)) {\n\n mu <- scenarios$mu[s]\n tau2 <- scenarios$tau2[s]\n\n alpha_plus_beta <- mu * (1 - mu) / tau2 - 1\n alpha <- mu * alpha_plus_beta\n beta <- (1 - mu) * alpha_plus_beta\n\n cat(sprintf(\"Scenario %d of %d: mu = %.2f, tau2 = %.4f\\n\",\n s, nrow(scenarios), mu, tau2))\n\n for (n in n_vals) {\n for (k in k_vals) {\n\n estimates <- numeric(R)\n var_estimates <- numeric(R)\n lower <- numeric(R)\n upper <- numeric(R)\n\n t_crit <- qt(1 - (1 - conf) / 2, df = n - 1)\n\n for (r in 1:R) {\n\n theta <- rbeta(n, alpha, beta)\n\n ybar_i <- numeric(n)\n for (i in 1:n) {\n y <- rbinom(k, size = 1, prob = theta[i])\n ybar_i[i] <- mean(y)\n }\n\n est <- calc_mean(ybar_i)\n v_est <- calc_var_of_mean(ybar_i)\n\n estimates[r] <- est\n var_estimates[r] <- v_est\n lower[r] <- est - t_crit * sqrt(v_est)\n upper[r] <- est + t_crit * sqrt(v_est)\n }\n\n true_var_of_mean <- (tau2 + (mu * (1 - mu) - tau2) / k) / n\n\n results <- rbind(results, data.frame(\n mu = mu,\n tau2 = tau2,\n n = n,\n k = k,\n avg_estimate = mean(estimates),\n true_var_of_mean = true_var_of_mean,\n sim_var_of_mean = var(estimates),\n avg_est_var_of_mean = mean(var_estimates),\n coverage = calc_coverage(lower, upper, mu),\n avg_ci_length = calc_avg_ci_length(lower, upper)\n ))\n }\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677266, "sha256": "b4b2cb661ed207973b568adb7f146f26de7721bf9d233fab67817288d6cbac29", "source_url": "https://stats.stackexchange.com/questions/677266/how-to-set-up-a-simulation-study"}, {"block_index": 0, "code_text": "yhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667 \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677268, "sha256": "1f520efb478c1a41ff425811f24e74461aaaf2f6cd8ba7834ea50d039660d1c6", "source_url": "https://stats.stackexchange.com/a/677268"}], "other_answers": [{"answer_html": "I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.
\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:
\nOptimise jointly $u,v$ (maximum likelihood).
\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).
\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable
\n", "answer_id": 677267, "answer_text": "I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.\n\n\n\n\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:\n\n\n\n\n\nHave variables $u$, $v$, and take $\\frac{\\alpha}{\\alpha+\\beta}=expit\\left(u\\right)=\\frac{1}{1+\\exp\\left(-u\\right)}$, $\\alpha=softplus(v)=\\log\\left(1+\\exp(v)\\right)$\n\n\n\n\n$\\sum_{j}y_{ij}=y_i\\sim BetaBinomial\\left(k, \\alpha,\\beta\\right)$\n\n\n\n\n\nOptimise jointly $u,v$ (maximum likelihood).\n\n\n\n\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).\n\n\n\n\n\n\n\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable", "answer_url": "https://stats.stackexchange.com/a/677267", "author": "Cryo", "author_url": "https://stats.stackexchange.com/users/275239/cryo", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T12:24:08+00:00", "is_accepted": false, "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": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Cryo", "profile_url": "https://stats.stackexchange.com/users/275239/cryo", "user_type": "registered"}, "created_at": "2026-09-26T12:24:08+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Cryo", "profile_url": "https://stats.stackexchange.com/users/275239/cryo", "user_type": "registered"}, "created_at": "2026-09-26T12:33:54+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "24348886-EE3F-4779-9F2E-6DF7895E9D85", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/24348886-EE3F-4779-9F2E-6DF7895E9D85/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-09-26T13:34:16+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "57B9D992-5586-4BC1-9973-DD3482A5AA98", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/57B9D992-5586-4BC1-9973-DD3482A5AA98/view-source"}], "score": 5, "updated_at": "2026-09-26T13:34:16+00:00"}], "product": "code_qa", "question": "Here is a hierarchical data generating process (DGP):\n\n\n\n\n\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$\n\n\n\n\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$\n\n\n\n\n\n\n\n$$\\mu = E[\\theta_i], \\qquad \\tau^2 = \\operatorname{Var}(\\theta_i)$$\n\n\n\n\nUsing a sample, my purpose is only to estimate the mean and the variance of the mean estimator. I want to know what values of $n$ and $k$ I should select to get good results (I know this hugely subjective) such that $nk$ is minimized (assume that increasing $n$ by 1 costs the same as increase $k$ by 1).\n\n\n\n\nAfter doing some research, it seems the best way to handle this question is by a simulation study. Assuming $\\alpha,\\ \\beta$ are known, I could sample from the DGP for different combinations of $n$ and $k$ and record the average length of the confidence intervals and average coverage rate at each combination. Since the mean estimator is unbiased regardless of the choice in $n$ or $k$, I could use average CI length and average coverage rate to make sure I am not getting a misleadingly good coverage rate at the expense of a large CI.\n\n\n\n\nHere is how I plan to do this in R (I wrote the code to focus on readability instead of speed - I use a moment based estimator and consider different true combinations of parameters):\n\n\n\n\nset.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals) {\n max_var <- mu * (1 - mu)\n for (v in 1:n_var) {\n tau2 <- (v / (n_var + 1)) * max_var\n scenarios <- rbind(scenarios, data.frame(mu = mu, tau2 = tau2))\n }\n}\n\n\ncalc_mean <- function(ybar_i) {\n mean(ybar_i)\n}\n\ncalc_var_of_mean <- function(ybar_i) {\n n <- length(ybar_i)\n var(ybar_i) / n\n}\n\ncalc_coverage <- function(lower, upper, mu) {\n mean(lower <= mu & mu <= upper)\n}\n\ncalc_avg_ci_length <- function(lower, upper) {\n mean(upper - lower)\n}\n\nresults <- data.frame()\n\nfor (s in 1:nrow(scenarios)) {\n\n mu <- scenarios$mu[s]\n tau2 <- scenarios$tau2[s]\n\n alpha_plus_beta <- mu * (1 - mu) / tau2 - 1\n alpha <- mu * alpha_plus_beta\n beta <- (1 - mu) * alpha_plus_beta\n\n cat(sprintf(\"Scenario %d of %d: mu = %.2f, tau2 = %.4f\\n\",\n s, nrow(scenarios), mu, tau2))\n\n for (n in n_vals) {\n for (k in k_vals) {\n\n estimates <- numeric(R)\n var_estimates <- numeric(R)\n lower <- numeric(R)\n upper <- numeric(R)\n\n t_crit <- qt(1 - (1 - conf) / 2, df = n - 1)\n\n for (r in 1:R) {\n\n theta <- rbeta(n, alpha, beta)\n\n ybar_i <- numeric(n)\n for (i in 1:n) {\n y <- rbinom(k, size = 1, prob = theta[i])\n ybar_i[i] <- mean(y)\n }\n\n est <- calc_mean(ybar_i)\n v_est <- calc_var_of_mean(ybar_i)\n\n estimates[r] <- est\n var_estimates[r] <- v_est\n lower[r] <- est - t_crit * sqrt(v_est)\n upper[r] <- est + t_crit * sqrt(v_est)\n }\n\n true_var_of_mean <- (tau2 + (mu * (1 - mu) - tau2) / k) / n\n\n results <- rbind(results, data.frame(\n mu = mu,\n tau2 = tau2,\n n = n,\n k = k,\n avg_estimate = mean(estimates),\n true_var_of_mean = true_var_of_mean,\n sim_var_of_mean = var(estimates),\n avg_est_var_of_mean = mean(var_estimates),\n coverage = calc_coverage(lower, upper, mu),\n avg_ci_length = calc_avg_ci_length(lower, upper)\n ))\n }\n }\n}\n\n\n\n\n\nWhen visualized, the results look like this (direct upload was not working - however it seems to show that when $n$ and $k$ are both large, for many cases, we get high coverage and smaller CI lengths on average): https://imgur.com/a/tgHbtLz (https://imgur.com/a/tgHbtLz)\n\n\n\n\nThe tricky part now is to try and guess what the true value of $\\alpha,\\ \\beta$ might be. If I can get some knowledge of this beforehand (e.g. possible range), I could try to determine what $n,k$ to use if I want average CI length and average coverage rate to be within certain ranges.\n\n\n\n\nI am looking for feedback on my methodology. Should I have done this a different way?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677266", "selected_answer": {"answer_html": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$
\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$
\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question, having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.
\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.
\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$
\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667 \n\n", "answer_id": 677268, "answer_text": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$\n\n\n\n\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$\n\n\n\n\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question (https://stats.stackexchange.com/q/677226/2958), having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.\n\n\n\n\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.\n\n\n\n\n\n\n\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$\n\n\n\n\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667", "answer_url": "https://stats.stackexchange.com/a/677268", "author": "Henry", "author_url": "https://stats.stackexchange.com/users/2958/henry", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T14:10:23+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": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Henry", "profile_url": "https://stats.stackexchange.com/users/2958/henry", "user_type": "registered"}, "created_at": "2026-09-26T14:10:23+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C96EACA9-97B0-4929-B972-DA5D20ED4759", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C96EACA9-97B0-4929-B972-DA5D20ED4759/view-source"}], "score": 4, "updated_at": "2026-09-26T14:10:23+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 677268, "answers": [{"answer_html": "I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.
\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:
\nOptimise jointly $u,v$ (maximum likelihood).
\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).
\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable
\n", "answer_id": 677267, "answer_text": "I would not go through mean and variance here. Your model for data generation is based on $\\alpha$ and $\\beta$ right? So why not work with them? Your population variable $\\theta$, as per your model is beta-distirbuted, so why not work with beta-likelihood? The problem is that sample variance and sample mean of a beta-distributed variable set, such as $\\{\\theta_i\\}$, are not independent variables, so you should not estimate them independently of each other.\n\n\n\n\nIf I had a sample $\\{y_{ij}\\}$ I would estimate it like this:\n\n\n\n\n\nHave variables $u$, $v$, and take $\\frac{\\alpha}{\\alpha+\\beta}=expit\\left(u\\right)=\\frac{1}{1+\\exp\\left(-u\\right)}$, $\\alpha=softplus(v)=\\log\\left(1+\\exp(v)\\right)$\n\n\n\n\n$\\sum_{j}y_{ij}=y_i\\sim BetaBinomial\\left(k, \\alpha,\\beta\\right)$\n\n\n\n\n\nOptimise jointly $u,v$ (maximum likelihood).\n\n\n\n\nSo your sample size calculation would be a wrap-around for this procedure, i.e. select, $n, k$ etc. It may be slower, but not too slow with your numbers. But it will be giving correct estimates even when $\\theta$ is close to the edges for the given variance (and thus cannot be treated as normal).\n\n\n\n\n\n\n\nIf you want to stick to variance and mean, you should be honest with yourself and state $\\theta_i \\sim Normal\\left(\\mu,\\sigma^2\\right)$. If you get reasonable numbers, good, if not then you know your approximation is not suitable", "answer_url": "https://stats.stackexchange.com/a/677267", "author": "Cryo", "author_url": "https://stats.stackexchange.com/users/275239/cryo", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T12:24:08+00:00", "is_accepted": false, "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": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Cryo", "profile_url": "https://stats.stackexchange.com/users/275239/cryo", "user_type": "registered"}, "created_at": "2026-09-26T12:24:08+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D52BEFB1-287A-4A8F-B3B4-FF67FD14E1AD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Cryo", "profile_url": "https://stats.stackexchange.com/users/275239/cryo", "user_type": "registered"}, "created_at": "2026-09-26T12:33:54+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "24348886-EE3F-4779-9F2E-6DF7895E9D85", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/24348886-EE3F-4779-9F2E-6DF7895E9D85/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-09-26T13:34:16+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "57B9D992-5586-4BC1-9973-DD3482A5AA98", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/57B9D992-5586-4BC1-9973-DD3482A5AA98/view-source"}], "score": 5, "updated_at": "2026-09-26T13:34:16+00:00"}, {"answer_html": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$
\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$
\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question, having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.
\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.
\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$
\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667 \n\n", "answer_id": 677268, "answer_text": "I think you can find the mean and variance of $\\bar y$ analytically. Clearly $\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$ and, using the law of total variance $$\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{nk(\\alpha+\\beta)^2} \\frac{\\alpha+\\beta+n}{\\alpha+\\beta+1} = \\frac{1}{nk}E[\\bar y]\\left(1-E[\\bar y]\\right) \\frac{\\alpha+\\beta+k}{\\alpha+\\beta+1}.$$\n\n\n\n\nSince $\\alpha\\ge 0, \\beta\\ge 0, 0 \\le E[\\bar y]\\le 1$, you can then say $$\\operatorname{Var}(\\bar y) \\le \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right) \\le \\frac1{4n}.$$\n\n\n\n\nFor given $nk$, you will minimise $\\operatorname{Var}(\\bar y)$ when $k$ is as small as possible, i.e. when $k=1$ and $n=nk$, at which point $\\operatorname{Var}(\\bar y) = \\frac{\\alpha \\beta}{n(\\alpha+\\beta)^2}= \\frac{1}{n}E[\\bar y]\\left(1-E[\\bar y]\\right)$, again bounded above by $\\frac1{4n}$. As discussed on your previous question (https://stats.stackexchange.com/q/677226/2958), having $k=1$ would make it impossible to estimate $\\alpha$ and $\\beta$ separately.\n\n\n\n\nSo using $k=1$ together with $n$ large enough to make $\\frac1{4n}$ small enough to meet your needs as an upper bound for $\\operatorname{Var}(\\bar y)$ should work well.\n\n\n\n\n\n\n\nHere is an illustrative simulation in R confirming these (with minor simulation noise) for $\\alpha=2$, $\\beta=3$ and $nk=12$\n\n\n\n\nyhatsim <- function(alpha, beta, n, k){\n thetai <- rbeta(n, alpha, beta)\n sum(rbinom(n, k, thetai)) / (n * k) \n }\nyhat <- function(alpha, beta, n, k, cases=10^6){\n simyhat <- replicate(cases, yhatsim(alpha, beta, n, k))\n c(simulatedmean=mean(simyhat), \n expectedmean=alpha/(alpha+beta), \n simulatedvar=var(simyhat),\n expectedvar=alpha*beta/(alpha+beta)^2*(alpha+beta+k)/(alpha+beta+1)/(n*k))\n }\n\n\nset.seed(2026)\n\nyhat(alpha=2, beta=3, n=12, k=1)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.4000867 0.4000000 0.0199709 0.0200000 \n\nyhat(alpha=2, beta=3, n=6, k=2)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39994625 0.40000000 0.02330732 0.02333333 \n\nyhat(alpha=2, beta=3, n=4, k=3)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40013683 0.40000000 0.02668078 0.02666667 \n\nyhat(alpha=2, beta=3, n=3, k=4)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39973175 0.40000000 0.03001747 0.03000000 \n\nyhat(alpha=2, beta=3, n=2, k=6)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.40039333 0.40000000 0.03666519 0.03666667 \n\nyhat(alpha=2, beta=3, n=1, k=12)\n# simulatedmean expectedmean simulatedvar expectedvar \n# 0.39992283 0.40000000 0.05659828 0.05666667", "answer_url": "https://stats.stackexchange.com/a/677268", "author": "Henry", "author_url": "https://stats.stackexchange.com/users/2958/henry", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-26T14:10:23+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": 677266, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Henry", "profile_url": "https://stats.stackexchange.com/users/2958/henry", "user_type": "registered"}, "created_at": "2026-09-26T14:10:23+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C96EACA9-97B0-4929-B972-DA5D20ED4759", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C96EACA9-97B0-4929-B972-DA5D20ED4759/view-source"}], "score": 4, "updated_at": "2026-09-26T14:10:23+00:00"}], "domain": "statistics", "external_links": ["https://imgur.com/a/tgHbtLz"], "medical_sensitive": false, "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": "adamkostanov", "question_author_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "question_author_user_type": "registered", "question_created_at": "2026-09-25T19:59:10+00:00", "question_html": "Here is a hierarchical data generating process (DGP):
\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$
\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$
\n
$$\\mu = E[\\theta_i], \\qquad \\tau^2 = \\operatorname{Var}(\\theta_i)$$
\nUsing a sample, my purpose is only to estimate the mean and the variance of the mean estimator. I want to know what values of $n$ and $k$ I should select to get good results (I know this hugely subjective) such that $nk$ is minimized (assume that increasing $n$ by 1 costs the same as increase $k$ by 1).
\nAfter doing some research, it seems the best way to handle this question is by a simulation study. Assuming $\\alpha,\\ \\beta$ are known, I could sample from the DGP for different combinations of $n$ and $k$ and record the average length of the confidence intervals and average coverage rate at each combination. Since the mean estimator is unbiased regardless of the choice in $n$ or $k$, I could use average CI length and average coverage rate to make sure I am not getting a misleadingly good coverage rate at the expense of a large CI.
\nHere is how I plan to do this in R (I wrote the code to focus on readability instead of speed - I use a moment based estimator and consider different true combinations of parameters):
\nset.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals) {\n max_var <- mu * (1 - mu)\n for (v in 1:n_var) {\n tau2 <- (v / (n_var + 1)) * max_var\n scenarios <- rbind(scenarios, data.frame(mu = mu, tau2 = tau2))\n }\n}\n\n\ncalc_mean <- function(ybar_i) {\n mean(ybar_i)\n}\n\ncalc_var_of_mean <- function(ybar_i) {\n n <- length(ybar_i)\n var(ybar_i) / n\n}\n\ncalc_coverage <- function(lower, upper, mu) {\n mean(lower <= mu & mu <= upper)\n}\n\ncalc_avg_ci_length <- function(lower, upper) {\n mean(upper - lower)\n}\n\nresults <- data.frame()\n\nfor (s in 1:nrow(scenarios)) {\n\n mu <- scenarios$mu[s]\n tau2 <- scenarios$tau2[s]\n\n alpha_plus_beta <- mu * (1 - mu) / tau2 - 1\n alpha <- mu * alpha_plus_beta\n beta <- (1 - mu) * alpha_plus_beta\n\n cat(sprintf("Scenario %d of %d: mu = %.2f, tau2 = %.4f\\n",\n s, nrow(scenarios), mu, tau2))\n\n for (n in n_vals) {\n for (k in k_vals) {\n\n estimates <- numeric(R)\n var_estimates <- numeric(R)\n lower <- numeric(R)\n upper <- numeric(R)\n\n t_crit <- qt(1 - (1 - conf) / 2, df = n - 1)\n\n for (r in 1:R) {\n\n theta <- rbeta(n, alpha, beta)\n\n ybar_i <- numeric(n)\n for (i in 1:n) {\n y <- rbinom(k, size = 1, prob = theta[i])\n ybar_i[i] <- mean(y)\n }\n\n est <- calc_mean(ybar_i)\n v_est <- calc_var_of_mean(ybar_i)\n\n estimates[r] <- est\n var_estimates[r] <- v_est\n lower[r] <- est - t_crit * sqrt(v_est)\n upper[r] <- est + t_crit * sqrt(v_est)\n }\n\n true_var_of_mean <- (tau2 + (mu * (1 - mu) - tau2) / k) / n\n\n results <- rbind(results, data.frame(\n mu = mu,\n tau2 = tau2,\n n = n,\n k = k,\n avg_estimate = mean(estimates),\n true_var_of_mean = true_var_of_mean,\n sim_var_of_mean = var(estimates),\n avg_est_var_of_mean = mean(var_estimates),\n coverage = calc_coverage(lower, upper, mu),\n avg_ci_length = calc_avg_ci_length(lower, upper)\n ))\n }\n }\n}\n\nWhen visualized, the results look like this (direct upload was not working - however it seems to show that when $n$ and $k$ are both large, for many cases, we get high coverage and smaller CI lengths on average): https://imgur.com/a/tgHbtLz
\nThe tricky part now is to try and guess what the true value of $\\alpha,\\ \\beta$ might be. If I can get some knowledge of this beforehand (e.g. possible range), I could try to determine what $n,k$ to use if I want average CI length and average coverage rate to be within certain ranges.
\nI am looking for feedback on my methodology. Should I have done this a different way?
\n", "question_id": 677266, "question_license": "CC BY-SA 4.0", "question_score": 6, "question_text": "Here is a hierarchical data generating process (DGP):\n\n\n\n\n\n\n\n(Population) Layer 1: $$\\theta_i \\overset{\\text{iid}}{\\sim} \\text{Beta}(\\alpha,\\ \\beta), \\qquad i = 1, \\dots, n$$\n\n\n\n\n(Individual) Layer 2: $$y_{ij} \\mid \\theta_i \\overset{\\text{iid}}{\\sim} \\text{Bernoulli}(\\theta_i), \\qquad j = 1, \\dots, k$$\n\n\n\n\n\n\n\n$$\\mu = E[\\theta_i], \\qquad \\tau^2 = \\operatorname{Var}(\\theta_i)$$\n\n\n\n\nUsing a sample, my purpose is only to estimate the mean and the variance of the mean estimator. I want to know what values of $n$ and $k$ I should select to get good results (I know this hugely subjective) such that $nk$ is minimized (assume that increasing $n$ by 1 costs the same as increase $k$ by 1).\n\n\n\n\nAfter doing some research, it seems the best way to handle this question is by a simulation study. Assuming $\\alpha,\\ \\beta$ are known, I could sample from the DGP for different combinations of $n$ and $k$ and record the average length of the confidence intervals and average coverage rate at each combination. Since the mean estimator is unbiased regardless of the choice in $n$ or $k$, I could use average CI length and average coverage rate to make sure I am not getting a misleadingly good coverage rate at the expense of a large CI.\n\n\n\n\nHere is how I plan to do this in R (I wrote the code to focus on readability instead of speed - I use a moment based estimator and consider different true combinations of parameters):\n\n\n\n\nset.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals) {\n max_var <- mu * (1 - mu)\n for (v in 1:n_var) {\n tau2 <- (v / (n_var + 1)) * max_var\n scenarios <- rbind(scenarios, data.frame(mu = mu, tau2 = tau2))\n }\n}\n\n\ncalc_mean <- function(ybar_i) {\n mean(ybar_i)\n}\n\ncalc_var_of_mean <- function(ybar_i) {\n n <- length(ybar_i)\n var(ybar_i) / n\n}\n\ncalc_coverage <- function(lower, upper, mu) {\n mean(lower <= mu & mu <= upper)\n}\n\ncalc_avg_ci_length <- function(lower, upper) {\n mean(upper - lower)\n}\n\nresults <- data.frame()\n\nfor (s in 1:nrow(scenarios)) {\n\n mu <- scenarios$mu[s]\n tau2 <- scenarios$tau2[s]\n\n alpha_plus_beta <- mu * (1 - mu) / tau2 - 1\n alpha <- mu * alpha_plus_beta\n beta <- (1 - mu) * alpha_plus_beta\n\n cat(sprintf(\"Scenario %d of %d: mu = %.2f, tau2 = %.4f\\n\",\n s, nrow(scenarios), mu, tau2))\n\n for (n in n_vals) {\n for (k in k_vals) {\n\n estimates <- numeric(R)\n var_estimates <- numeric(R)\n lower <- numeric(R)\n upper <- numeric(R)\n\n t_crit <- qt(1 - (1 - conf) / 2, df = n - 1)\n\n for (r in 1:R) {\n\n theta <- rbeta(n, alpha, beta)\n\n ybar_i <- numeric(n)\n for (i in 1:n) {\n y <- rbinom(k, size = 1, prob = theta[i])\n ybar_i[i] <- mean(y)\n }\n\n est <- calc_mean(ybar_i)\n v_est <- calc_var_of_mean(ybar_i)\n\n estimates[r] <- est\n var_estimates[r] <- v_est\n lower[r] <- est - t_crit * sqrt(v_est)\n upper[r] <- est + t_crit * sqrt(v_est)\n }\n\n true_var_of_mean <- (tau2 + (mu * (1 - mu) - tau2) / k) / n\n\n results <- rbind(results, data.frame(\n mu = mu,\n tau2 = tau2,\n n = n,\n k = k,\n avg_estimate = mean(estimates),\n true_var_of_mean = true_var_of_mean,\n sim_var_of_mean = var(estimates),\n avg_est_var_of_mean = mean(var_estimates),\n coverage = calc_coverage(lower, upper, mu),\n avg_ci_length = calc_avg_ci_length(lower, upper)\n ))\n }\n }\n}\n\n\n\n\n\nWhen visualized, the results look like this (direct upload was not working - however it seems to show that when $n$ and $k$ are both large, for many cases, we get high coverage and smaller CI lengths on average): https://imgur.com/a/tgHbtLz (https://imgur.com/a/tgHbtLz)\n\n\n\n\nThe tricky part now is to try and guess what the true value of $\\alpha,\\ \\beta$ might be. If I can get some knowledge of this beforehand (e.g. possible range), I could try to determine what $n,k$ to use if I want average CI length and average coverage rate to be within certain ranges.\n\n\n\n\nI am looking for feedback on my methodology. Should I have done this a different way?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-25T19:59:10+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "BDACA524-F3A6-491A-880E-A6871C920AE2", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/BDACA524-F3A6-491A-880E-A6871C920AE2/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-25T20:06:02+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "AD0D55CA-D20D-43CE-AF14-F3B414CC07CC", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD0D55CA-D20D-43CE-AF14-F3B414CC07CC/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-09-26T14:16:51+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "33D7D8BE-907F-442F-B2B0-F7C572555835", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://stats.stackexchange.com/revisions/33D7D8BE-907F-442F-B2B0-F7C572555835/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "adamkostanov", "profile_url": "https://stats.stackexchange.com/users/512554/adamkostanov", "user_type": "registered"}, "created_at": "2026-09-26T17:38:27+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "CAC7EE3C-CE9C-4299-BF6B-07246FC0E1C1", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/CAC7EE3C-CE9C-4299-BF6B-07246FC0E1C1/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677266/how-to-set-up-a-simulation-study", "split": "train", "split_group": "21d3364431200c413f5adef6742bd9555e0cb33cda58781dfab79e3d31d1b7fb", "tags": ["r", "sampling", "estimation"], "thread_id": "stats:677266", "title": "How to set up a simulation study?"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 1 2 yes short 84 7 0.08333333\n3 2024 1 3 yes short 69 30 0.43478261\n4 2024 1 4 yes short 100 22 0.22000000\n5 2024 1 5 yes short 100 36 0.36000000\n6 2024 1 6 no short 100 15 0.15000000\n7 2024 1 7 no short 100 8 0.08000000\n8 2024 1 8 no short 100 10 0.10000000\n9 2024 1 9 no short 100 10 0.10000000\n10 2024 1 10 no short 100 2 0.02000000\n\n\nseeddamage<-structure(list(year = c(2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L), planting_block = c(1L, \n 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, \n 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, \n 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), plant_genotype = c(1L, \n 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, \n 16L, 17L, 18L, 19L, 20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, \n 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 16L, 17L, \n 18L, 19L, 20L, 11L, 12L, 14L, 15L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, \n 3L, 4L, 5L), plant_trait_a = c(\"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \n \"yes\", \"yes\", \"yes\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \n \"yes\", \"yes\", \"yes\"), plant_trait_b = c(\"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\"), seeds_total = c(100L, 84L, \n 69L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 71L, \n 100L, 100L, 100L, 100L, 100L, 100L, 56L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L), seeds_beetle_damaged = c(59L, 7L, 30L, 22L, 36L, \n 15L, 8L, 10L, 10L, 2L, 25L, 6L, 0L, 24L, 21L, 10L, 13L, 10L, \n 14L, 0L, 13L, 19L, 18L, 15L, 28L, 7L, 3L, 11L, 0L, 2L, 15L, 9L, \n 11L, 24L, 44L, 0L, 0L, 0L, 5L, 9L, 8L, 3L, 2L, 3L, 3L, 9L, 0L, \n 8L, 3L, 6L, 2L, 5L, 5L, 4L, 9L, 4L, 7L, 0L, 6L), prop_beetle_damaged = c(0.59, \n 0.0833333333333333, 0.434782608695652, 0.22, 0.36, 0.15, 0.08, \n 0.1, 0.1, 0.02, 0.25, 0.06, 0, 0.24, 0.21, 0.1, 0.13, 0.1, 0.14, \n 0, 0.13, 0.19, 0.18, 0.15, 0.28, 0.07, 0.03, 0.11, 0, 0.02, 0.15, \n 0.09, 0.11, 0.24, 0.44, 0, 0, 0, 0.05, 0.09, 0.08, 0.03, 0.02, \n 0.03, 0.03, 0.09, 0, 0.08, 0.03, 0.06, 0.02, 0.05, 0.05, 0.04, \n 0.09, 0.04, 0.07, 0, 0.06)), row.names = c(NA, 59L), class = \"data.frame\")\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677298, "sha256": "0d4c015350ac6e446deed395928107c80f7a47277dbc4f431608021b6d63ad2f", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom"}, {"block_index": 1, "code_text": "library(tidyverse)\nlibrary(glmmTMB)\nlibrary(DHARMa)\n\nset.seed(42)\nbeetle<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=binomial, data=seeddamage)\nsummary(beetle)\n#AIC BIC logLik -2*log(L) df.resid \n# 566.2 576.6 -278.1 556.2 54 \n\nresidbeetle<-simulateResiduals(fittedModel=beetle)\nplot(residbeetle)\n#left plot or QQ plot residuals was S shaped\n#right plot looked ok: Levene test for homogeneity of variance was n.s. and within group deviation from uniformity was n.s.\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle) \n#dispersion = 1.9633, p-value < 2.2e-16, significant overdispersion\n#see plot, red line is far to the right of predicted values\n\ntestZeroInflation(residbeetle)\n#ratioObsSim = 8.2305, p-value < 2.2e-16, significant zero inflation\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677298, "sha256": "21c4e8e4e0ff8e7c76472b5d9535727acc2468c51f9a428547eae7bec6bfcf35", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom"}, {"block_index": 2, "code_text": "beetle2<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=betabinomial, ziformula = ~ 1, data=seeddamage)\nsummary(beetle2)\n# AIC BIC logLik -2*log(L) df.resid \n# 391.6 406.1 -188.8 377.6 52 \n\nresidbeetle2<-simulateResiduals(fittedModel=beetle2)\nplot(residbeetle2)\n#both residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle2) # Tests for over/underdispersion\n#dispersion = 1.3461, p-value = 0.096\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677298, "sha256": "96123ee4548f527a2d06370f07e0b7bca8e69441c77e97e0528da1a32687db42", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom"}, {"block_index": 3, "code_text": "beetle3<-glmmTMB(prop_beetle_damaged ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=beta_family(), ziformula = ~ 1, data=seeddamage)\nsummary(beetle3)\n# AIC BIC logLik -2*log(L) df.resid \n# -75.6 -61.1 44.8 -89.6 52 \n\nresidbeetle3<-simulateResiduals(fittedModel=beetle3)\nplot(residbeetle3)\n#residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle3) # Tests for over/underdispersion\n#dispersion = 1.3836, p-value = 0.056\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 677298, "sha256": "3286f8f7a09d30d949cc01f68d5acdb326946b1d7ea1d1a42bef267b312e121a", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom"}], "other_answers": [], "product": "code_qa", "question": "I'm trying to decide which GLMM distribution is best for my data.\n\n\n\n\nI want to determine how plant_trait_a and plant_trait_b affect beetle seed damage.\n\n\n\n\nThere were two levels of plant_trait_a and two levels of plant_trait_b that made up 4 treatment groups. We selected 20 plant_genotypes for our field experiment, each treatment group had 5. Each plant genotype was planted 3 times, in 3 different planting_blocks.\n\n\n\n\nWe collected 56-100 seeds per plot (plot=planting_blockxplant_genotype combination); most had 100 seeds, but 4 plots had less than 100 seeds available. I then counted the number of beetle damaged seeds (seeds_beetle_damaged) in each sample.\n\n\n\n\n#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 1 2 yes short 84 7 0.08333333\n3 2024 1 3 yes short 69 30 0.43478261\n4 2024 1 4 yes short 100 22 0.22000000\n5 2024 1 5 yes short 100 36 0.36000000\n6 2024 1 6 no short 100 15 0.15000000\n7 2024 1 7 no short 100 8 0.08000000\n8 2024 1 8 no short 100 10 0.10000000\n9 2024 1 9 no short 100 10 0.10000000\n10 2024 1 10 no short 100 2 0.02000000\n\n\nseeddamage<-structure(list(year = c(2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L), planting_block = c(1L, \n 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, \n 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, \n 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), plant_genotype = c(1L, \n 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, \n 16L, 17L, 18L, 19L, 20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, \n 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 16L, 17L, \n 18L, 19L, 20L, 11L, 12L, 14L, 15L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, \n 3L, 4L, 5L), plant_trait_a = c(\"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \n \"yes\", \"yes\", \"yes\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \n \"yes\", \"yes\", \"yes\"), plant_trait_b = c(\"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\"), seeds_total = c(100L, 84L, \n 69L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 71L, \n 100L, 100L, 100L, 100L, 100L, 100L, 56L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L), seeds_beetle_damaged = c(59L, 7L, 30L, 22L, 36L, \n 15L, 8L, 10L, 10L, 2L, 25L, 6L, 0L, 24L, 21L, 10L, 13L, 10L, \n 14L, 0L, 13L, 19L, 18L, 15L, 28L, 7L, 3L, 11L, 0L, 2L, 15L, 9L, \n 11L, 24L, 44L, 0L, 0L, 0L, 5L, 9L, 8L, 3L, 2L, 3L, 3L, 9L, 0L, \n 8L, 3L, 6L, 2L, 5L, 5L, 4L, 9L, 4L, 7L, 0L, 6L), prop_beetle_damaged = c(0.59, \n 0.0833333333333333, 0.434782608695652, 0.22, 0.36, 0.15, 0.08, \n 0.1, 0.1, 0.02, 0.25, 0.06, 0, 0.24, 0.21, 0.1, 0.13, 0.1, 0.14, \n 0, 0.13, 0.19, 0.18, 0.15, 0.28, 0.07, 0.03, 0.11, 0, 0.02, 0.15, \n 0.09, 0.11, 0.24, 0.44, 0, 0, 0, 0.05, 0.09, 0.08, 0.03, 0.02, \n 0.03, 0.03, 0.09, 0, 0.08, 0.03, 0.06, 0.02, 0.05, 0.05, 0.04, \n 0.09, 0.04, 0.07, 0, 0.06)), row.names = c(NA, 59L), class = \"data.frame\")\n\n\n\n\n\n\n1. Binomial GLMM\n\n\n\n\nI first ran a binomial model with the glmmtmb package in R. My y variable was modeled as a binomial outcome that represented the number of beetle damaged seeds per plot. My fixed effects were plant_trait_a and plant_trait_b and I set planting_block as a random effect.\n\n\n\n\nUsing the DHARMa package I checked the residuals plots then tested for overdispersion and zero-inflation. I found that there was significant overdispersion (dispersion = 1.9633, p-value < 2.2e-16) and zero-inflation (ratioObsSim = 8.2305, p-value < 2.2e-16).\n\n\n\n\nlibrary(tidyverse)\nlibrary(glmmTMB)\nlibrary(DHARMa)\n\nset.seed(42)\nbeetle<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=binomial, data=seeddamage)\nsummary(beetle)\n#AIC BIC logLik -2*log(L) df.resid \n# 566.2 576.6 -278.1 556.2 54 \n\nresidbeetle<-simulateResiduals(fittedModel=beetle)\nplot(residbeetle)\n#left plot or QQ plot residuals was S shaped\n#right plot looked ok: Levene test for homogeneity of variance was n.s. and within group deviation from uniformity was n.s.\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle) \n#dispersion = 1.9633, p-value < 2.2e-16, significant overdispersion\n#see plot, red line is far to the right of predicted values\n\ntestZeroInflation(residbeetle)\n#ratioObsSim = 8.2305, p-value < 2.2e-16, significant zero inflation\n\n\n\n\n\n\n2. Zero-inflated beta binomial\n\n\n\n\nNext I ran a zero-inflated beta binomial model using the same fixed and random effects. I read online that the beta binomial distribution can address overdispersion in binomial models. Compared to the binomial model, the left side residuals plot (QQ plot) looked better - no longer S-shaped, data points were closer to red diagonal line. The p-value from the dispersion test was nonsignificant (dispersion = 1.3461, p-value = 0.096).\n\n\n\n\nbeetle2<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=betabinomial, ziformula = ~ 1, data=seeddamage)\nsummary(beetle2)\n# AIC BIC logLik -2*log(L) df.resid \n# 391.6 406.1 -188.8 377.6 52 \n\nresidbeetle2<-simulateResiduals(fittedModel=beetle2)\nplot(residbeetle2)\n#both residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle2) # Tests for over/underdispersion\n#dispersion = 1.3461, p-value = 0.096\n\n\n\n\n\n\n3.Zero-inflated beta\n\n\n\n\nI shared the results from the zero-inflated beta binomal model with a stats consultant at my university who uses SAS and has mostly worked with binomial GLMs. He said he's only seen one textbook mention the beta binomial distribution, and that since it's not as common as other distributions he is skeptical of the results.\n\n\n\n\nSo I decided to try running a model with a zero-inflated beta distribution. This seems somewhat more common than the beta binomial. I used the same fixed and random effects, but the y variable was changed to the proportion of beetle damaged seeds per sample (prop_beetle_damaged). The residuals plots looked good and the dispersion value was nonsignificant (dispersion = 1.3836, p-value = 0.056)\n\n\n\n\nbeetle3<-glmmTMB(prop_beetle_damaged ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=beta_family(), ziformula = ~ 1, data=seeddamage)\nsummary(beetle3)\n# AIC BIC logLik -2*log(L) df.resid \n# -75.6 -61.1 44.8 -89.6 52 \n\nresidbeetle3<-simulateResiduals(fittedModel=beetle3)\nplot(residbeetle3)\n#residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle3) # Tests for over/underdispersion\n#dispersion = 1.3836, p-value = 0.056\n\n\n\n\n\n\nWhich model seems most appropriate for my data? I've read that when deciding between models with different distributions, the one with the lowest AIC value is the best fit. So should I go with the zero-inflated beta model?", "record_id": "Scientific-Code-and-Analysis-QA:stats:677298", "selected_answer": {"answer_html": "I think a non Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known integer denominator (total number of seeds in your case). (That said, with a large denominator the binomial variance decreases and the differences between binomial and beta-binomial become less important.) I hope to come back and post a more complete answer later ...
\n", "answer_id": 677305, "answer_text": "I think a non Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known integer denominator (total number of seeds in your case). (That said, with a large denominator the binomial variance decreases and the differences between binomial and beta-binomial become less important.) I hope to come back and post a more complete answer later ...", "answer_url": "https://stats.stackexchange.com/a/677305", "author": "Ben Bolker", "author_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-30T16:30:37+00:00", "is_accepted": false, "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": 677298, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ben Bolker", "profile_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "user_type": "registered"}, "created_at": "2026-09-30T16:30:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "AD4B46E9-D946-4A17-BABC-04F3EE32D07E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD4B46E9-D946-4A17-BABC-04F3EE32D07E/view-source"}], "score": 1, "updated_at": "2026-09-30T16:30:37+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "I think a non Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known integer denominator (total number of seeds in your case). (That said, with a large denominator the binomial variance decreases and the differences between binomial and beta-binomial become less important.) I hope to come back and post a more complete answer later ...
\n", "answer_id": 677305, "answer_text": "I think a non Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known integer denominator (total number of seeds in your case). (That said, with a large denominator the binomial variance decreases and the differences between binomial and beta-binomial become less important.) I hope to come back and post a more complete answer later ...", "answer_url": "https://stats.stackexchange.com/a/677305", "author": "Ben Bolker", "author_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-30T16:30:37+00:00", "is_accepted": false, "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": 677298, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ben Bolker", "profile_url": "https://stats.stackexchange.com/users/2126/ben-bolker", "user_type": "registered"}, "created_at": "2026-09-30T16:30:37+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "AD4B46E9-D946-4A17-BABC-04F3EE32D07E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/AD4B46E9-D946-4A17-BABC-04F3EE32D07E/view-source"}], "score": 1, "updated_at": "2026-09-30T16:30:37+00:00"}], "domain": "statistics", "external_links": [], "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": "glew", "question_author_url": "https://stats.stackexchange.com/users/517245/glew", "question_author_user_type": "registered", "question_created_at": "2026-09-29T20:13:50+00:00", "question_html": "I'm trying to decide which GLMM distribution is best for my data.
\nI want to determine how plant_trait_a and plant_trait_b affect beetle seed damage.
There were two levels of plant_trait_a and two levels of plant_trait_b that made up 4 treatment groups. We selected 20 plant_genotypes for our field experiment, each treatment group had 5. Each plant genotype was planted 3 times, in 3 different planting_blocks.
We collected 56-100 seeds per plot (plot=planting_blockxplant_genotype combination); most had 100 seeds, but 4 plots had less than 100 seeds available. I then counted the number of beetle damaged seeds (seeds_beetle_damaged) in each sample.
#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 1 2 yes short 84 7 0.08333333\n3 2024 1 3 yes short 69 30 0.43478261\n4 2024 1 4 yes short 100 22 0.22000000\n5 2024 1 5 yes short 100 36 0.36000000\n6 2024 1 6 no short 100 15 0.15000000\n7 2024 1 7 no short 100 8 0.08000000\n8 2024 1 8 no short 100 10 0.10000000\n9 2024 1 9 no short 100 10 0.10000000\n10 2024 1 10 no short 100 2 0.02000000\n\n\nseeddamage<-structure(list(year = c(2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L), planting_block = c(1L, \n 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, \n 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, \n 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), plant_genotype = c(1L, \n 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, \n 16L, 17L, 18L, 19L, 20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, \n 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 16L, 17L, \n 18L, 19L, 20L, 11L, 12L, 14L, 15L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, \n 3L, 4L, 5L), plant_trait_a = c("yes", "yes", "yes", "yes", "yes", \n "no", "no", "no", "no", "no", "yes", "yes", "yes", "yes", "yes", \n "no", "no", "no", "no", "no", "yes", "yes", "yes", "yes", "yes", \n "no", "no", "no", "no", "no", "yes", "yes", "yes", "yes", "yes", \n "no", "no", "no", "no", "no", "no", "no", "no", "no", "no", "yes", \n "yes", "yes", "yes", "no", "no", "no", "no", "no", "yes", "yes", \n "yes", "yes", "yes"), plant_trait_b = c("short", "short", "short", \n "short", "short", "short", "short", "short", "short", "short", \n "long", "long", "long", "long", "long", "long", "long", "long", \n "long", "long", "short", "short", "short", "short", "short", \n "short", "short", "short", "short", "short", "long", "long", \n "long", "long", "long", "long", "long", "long", "long", "long", \n "long", "long", "long", "long", "long", "long", "long", "long", \n "long", "short", "short", "short", "short", "short", "short", \n "short", "short", "short", "short"), seeds_total = c(100L, 84L, \n 69L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 71L, \n 100L, 100L, 100L, 100L, 100L, 100L, 56L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L), seeds_beetle_damaged = c(59L, 7L, 30L, 22L, 36L, \n 15L, 8L, 10L, 10L, 2L, 25L, 6L, 0L, 24L, 21L, 10L, 13L, 10L, \n 14L, 0L, 13L, 19L, 18L, 15L, 28L, 7L, 3L, 11L, 0L, 2L, 15L, 9L, \n 11L, 24L, 44L, 0L, 0L, 0L, 5L, 9L, 8L, 3L, 2L, 3L, 3L, 9L, 0L, \n 8L, 3L, 6L, 2L, 5L, 5L, 4L, 9L, 4L, 7L, 0L, 6L), prop_beetle_damaged = c(0.59, \n 0.0833333333333333, 0.434782608695652, 0.22, 0.36, 0.15, 0.08, \n 0.1, 0.1, 0.02, 0.25, 0.06, 0, 0.24, 0.21, 0.1, 0.13, 0.1, 0.14, \n 0, 0.13, 0.19, 0.18, 0.15, 0.28, 0.07, 0.03, 0.11, 0, 0.02, 0.15, \n 0.09, 0.11, 0.24, 0.44, 0, 0, 0, 0.05, 0.09, 0.08, 0.03, 0.02, \n 0.03, 0.03, 0.09, 0, 0.08, 0.03, 0.06, 0.02, 0.05, 0.05, 0.04, \n 0.09, 0.04, 0.07, 0, 0.06)), row.names = c(NA, 59L), class = "data.frame")\n\n\n1. Binomial GLMM
\nI first ran a binomial model with the glmmtmb package in R. My y variable was modeled as a binomial outcome that represented the number of beetle damaged seeds per plot. My fixed effects were plant_trait_a and plant_trait_b and I set planting_block as a random effect.
Using the DHARMa package I checked the residuals plots then tested for overdispersion and zero-inflation. I found that there was significant overdispersion (dispersion = 1.9633, p-value < 2.2e-16) and zero-inflation (ratioObsSim = 8.2305, p-value < 2.2e-16).
\nlibrary(tidyverse)\nlibrary(glmmTMB)\nlibrary(DHARMa)\n\nset.seed(42)\nbeetle<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=binomial, data=seeddamage)\nsummary(beetle)\n#AIC BIC logLik -2*log(L) df.resid \n# 566.2 576.6 -278.1 556.2 54 \n\nresidbeetle<-simulateResiduals(fittedModel=beetle)\nplot(residbeetle)\n#left plot or QQ plot residuals was S shaped\n#right plot looked ok: Levene test for homogeneity of variance was n.s. and within group deviation from uniformity was n.s.\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle) \n#dispersion = 1.9633, p-value < 2.2e-16, significant overdispersion\n#see plot, red line is far to the right of predicted values\n\ntestZeroInflation(residbeetle)\n#ratioObsSim = 8.2305, p-value < 2.2e-16, significant zero inflation\n\n\n2. Zero-inflated beta binomial
\nNext I ran a zero-inflated beta binomial model using the same fixed and random effects. I read online that the beta binomial distribution can address overdispersion in binomial models. Compared to the binomial model, the left side residuals plot (QQ plot) looked better - no longer S-shaped, data points were closer to red diagonal line. The p-value from the dispersion test was nonsignificant (dispersion = 1.3461, p-value = 0.096).
\nbeetle2<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=betabinomial, ziformula = ~ 1, data=seeddamage)\nsummary(beetle2)\n# AIC BIC logLik -2*log(L) df.resid \n# 391.6 406.1 -188.8 377.6 52 \n\nresidbeetle2<-simulateResiduals(fittedModel=beetle2)\nplot(residbeetle2)\n#both residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle2) # Tests for over/underdispersion\n#dispersion = 1.3461, p-value = 0.096\n\n\n3.Zero-inflated beta
\nI shared the results from the zero-inflated beta binomal model with a stats consultant at my university who uses SAS and has mostly worked with binomial GLMs. He said he's only seen one textbook mention the beta binomial distribution, and that since it's not as common as other distributions he is skeptical of the results.
\nSo I decided to try running a model with a zero-inflated beta distribution. This seems somewhat more common than the beta binomial. I used the same fixed and random effects, but the y variable was changed to the proportion of beetle damaged seeds per sample (prop_beetle_damaged). The residuals plots looked good and the dispersion value was nonsignificant (dispersion = 1.3836, p-value = 0.056)
beetle3<-glmmTMB(prop_beetle_damaged ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=beta_family(), ziformula = ~ 1, data=seeddamage)\nsummary(beetle3)\n# AIC BIC logLik -2*log(L) df.resid \n# -75.6 -61.1 44.8 -89.6 52 \n\nresidbeetle3<-simulateResiduals(fittedModel=beetle3)\nplot(residbeetle3)\n#residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle3) # Tests for over/underdispersion\n#dispersion = 1.3836, p-value = 0.056\n\n\nWhich model seems most appropriate for my data? I've read that when deciding between models with different distributions, the one with the lowest AIC value is the best fit. So should I go with the zero-inflated beta model?
\n", "question_id": 677298, "question_license": "CC BY-SA 4.0", "question_score": 0, "question_text": "I'm trying to decide which GLMM distribution is best for my data.\n\n\n\n\nI want to determine how plant_trait_a and plant_trait_b affect beetle seed damage.\n\n\n\n\nThere were two levels of plant_trait_a and two levels of plant_trait_b that made up 4 treatment groups. We selected 20 plant_genotypes for our field experiment, each treatment group had 5. Each plant genotype was planted 3 times, in 3 different planting_blocks.\n\n\n\n\nWe collected 56-100 seeds per plot (plot=planting_blockxplant_genotype combination); most had 100 seeds, but 4 plots had less than 100 seeds available. I then counted the number of beetle damaged seeds (seeds_beetle_damaged) in each sample.\n\n\n\n\n#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 1 2 yes short 84 7 0.08333333\n3 2024 1 3 yes short 69 30 0.43478261\n4 2024 1 4 yes short 100 22 0.22000000\n5 2024 1 5 yes short 100 36 0.36000000\n6 2024 1 6 no short 100 15 0.15000000\n7 2024 1 7 no short 100 8 0.08000000\n8 2024 1 8 no short 100 10 0.10000000\n9 2024 1 9 no short 100 10 0.10000000\n10 2024 1 10 no short 100 2 0.02000000\n\n\nseeddamage<-structure(list(year = c(2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, \n 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, \n 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L, 2025L), planting_block = c(1L, \n 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, \n 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, \n 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), plant_genotype = c(1L, \n 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, \n 16L, 17L, 18L, 19L, 20L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, \n 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 16L, 17L, \n 18L, 19L, 20L, 11L, 12L, 14L, 15L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, \n 3L, 4L, 5L), plant_trait_a = c(\"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \"yes\", \"yes\", \"yes\", \n \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \n \"yes\", \"yes\", \"yes\", \"no\", \"no\", \"no\", \"no\", \"no\", \"yes\", \"yes\", \n \"yes\", \"yes\", \"yes\"), plant_trait_b = c(\"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\", \"short\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \"long\", \n \"long\", \"short\", \"short\", \"short\", \"short\", \"short\", \"short\", \n \"short\", \"short\", \"short\", \"short\"), seeds_total = c(100L, 84L, \n 69L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 71L, \n 100L, 100L, 100L, 100L, 100L, 100L, 56L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, 100L, \n 100L, 100L), seeds_beetle_damaged = c(59L, 7L, 30L, 22L, 36L, \n 15L, 8L, 10L, 10L, 2L, 25L, 6L, 0L, 24L, 21L, 10L, 13L, 10L, \n 14L, 0L, 13L, 19L, 18L, 15L, 28L, 7L, 3L, 11L, 0L, 2L, 15L, 9L, \n 11L, 24L, 44L, 0L, 0L, 0L, 5L, 9L, 8L, 3L, 2L, 3L, 3L, 9L, 0L, \n 8L, 3L, 6L, 2L, 5L, 5L, 4L, 9L, 4L, 7L, 0L, 6L), prop_beetle_damaged = c(0.59, \n 0.0833333333333333, 0.434782608695652, 0.22, 0.36, 0.15, 0.08, \n 0.1, 0.1, 0.02, 0.25, 0.06, 0, 0.24, 0.21, 0.1, 0.13, 0.1, 0.14, \n 0, 0.13, 0.19, 0.18, 0.15, 0.28, 0.07, 0.03, 0.11, 0, 0.02, 0.15, \n 0.09, 0.11, 0.24, 0.44, 0, 0, 0, 0.05, 0.09, 0.08, 0.03, 0.02, \n 0.03, 0.03, 0.09, 0, 0.08, 0.03, 0.06, 0.02, 0.05, 0.05, 0.04, \n 0.09, 0.04, 0.07, 0, 0.06)), row.names = c(NA, 59L), class = \"data.frame\")\n\n\n\n\n\n\n1. Binomial GLMM\n\n\n\n\nI first ran a binomial model with the glmmtmb package in R. My y variable was modeled as a binomial outcome that represented the number of beetle damaged seeds per plot. My fixed effects were plant_trait_a and plant_trait_b and I set planting_block as a random effect.\n\n\n\n\nUsing the DHARMa package I checked the residuals plots then tested for overdispersion and zero-inflation. I found that there was significant overdispersion (dispersion = 1.9633, p-value < 2.2e-16) and zero-inflation (ratioObsSim = 8.2305, p-value < 2.2e-16).\n\n\n\n\nlibrary(tidyverse)\nlibrary(glmmTMB)\nlibrary(DHARMa)\n\nset.seed(42)\nbeetle<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=binomial, data=seeddamage)\nsummary(beetle)\n#AIC BIC logLik -2*log(L) df.resid \n# 566.2 576.6 -278.1 556.2 54 \n\nresidbeetle<-simulateResiduals(fittedModel=beetle)\nplot(residbeetle)\n#left plot or QQ plot residuals was S shaped\n#right plot looked ok: Levene test for homogeneity of variance was n.s. and within group deviation from uniformity was n.s.\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle) \n#dispersion = 1.9633, p-value < 2.2e-16, significant overdispersion\n#see plot, red line is far to the right of predicted values\n\ntestZeroInflation(residbeetle)\n#ratioObsSim = 8.2305, p-value < 2.2e-16, significant zero inflation\n\n\n\n\n\n\n2. Zero-inflated beta binomial\n\n\n\n\nNext I ran a zero-inflated beta binomial model using the same fixed and random effects. I read online that the beta binomial distribution can address overdispersion in binomial models. Compared to the binomial model, the left side residuals plot (QQ plot) looked better - no longer S-shaped, data points were closer to red diagonal line. The p-value from the dispersion test was nonsignificant (dispersion = 1.3461, p-value = 0.096).\n\n\n\n\nbeetle2<-glmmTMB(cbind(seeds_beetle_damaged, seeds_total-seeds_beetle_damaged) ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=betabinomial, ziformula = ~ 1, data=seeddamage)\nsummary(beetle2)\n# AIC BIC logLik -2*log(L) df.resid \n# 391.6 406.1 -188.8 377.6 52 \n\nresidbeetle2<-simulateResiduals(fittedModel=beetle2)\nplot(residbeetle2)\n#both residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle2) # Tests for over/underdispersion\n#dispersion = 1.3461, p-value = 0.096\n\n\n\n\n\n\n3.Zero-inflated beta\n\n\n\n\nI shared the results from the zero-inflated beta binomal model with a stats consultant at my university who uses SAS and has mostly worked with binomial GLMs. He said he's only seen one textbook mention the beta binomial distribution, and that since it's not as common as other distributions he is skeptical of the results.\n\n\n\n\nSo I decided to try running a model with a zero-inflated beta distribution. This seems somewhat more common than the beta binomial. I used the same fixed and random effects, but the y variable was changed to the proportion of beetle damaged seeds per sample (prop_beetle_damaged). The residuals plots looked good and the dispersion value was nonsignificant (dispersion = 1.3836, p-value = 0.056)\n\n\n\n\nbeetle3<-glmmTMB(prop_beetle_damaged ~ plant_trait_a*plant_trait_b + (1|planting_block),\n family=beta_family(), ziformula = ~ 1, data=seeddamage)\nsummary(beetle3)\n# AIC BIC logLik -2*log(L) df.resid \n# -75.6 -61.1 44.8 -89.6 52 \n\nresidbeetle3<-simulateResiduals(fittedModel=beetle3)\nplot(residbeetle3)\n#residuals plots look good\n\n#check dispersion and zero inflation\ntestDispersion(residbeetle3) # Tests for over/underdispersion\n#dispersion = 1.3836, p-value = 0.056\n\n\n\n\n\n\nWhich model seems most appropriate for my data? I've read that when deciding between models with different distributions, the one with the lowest AIC value is the best fit. So should I go with the zero-inflated beta model?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "glew", "profile_url": "https://stats.stackexchange.com/users/517245/glew", "user_type": "registered"}, "created_at": "2026-09-29T20:13:50+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "D8B5E82E-0E38-4027-9C48-93E1F5E3D662", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/D8B5E82E-0E38-4027-9C48-93E1F5E3D662/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "glew", "profile_url": "https://stats.stackexchange.com/users/517245/glew", "user_type": "registered"}, "created_at": "2026-09-30T15:18:51+00:00", "raw_file": "raw/codex_api_v1/ab5f4cd7f0a10bde5970354a9b213efcc81e232042487437e8579705d4ca6a20_1790825258916612700_0.json", "raw_sha256": "4cf167c399d03b9ae013b65260fcb4e38139c42cfc70aba4807f070550c1768e", "revision_guid": "C946D7BE-B64A-4585-AC40-0C1885066383", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://stats.stackexchange.com/revisions/C946D7BE-B64A-4585-AC40-0C1885066383/view-source"}], "source_site": "stats", "source_url": "https://stats.stackexchange.com/questions/677298/need-help-deciding-what-zero-inflated-glmm-to-use-beta-binomial-or-beta-binom", "split": "train", "split_group": "3123c426022f04d2481edd65d05980cf35eac64127fe7532f97efe75c659bca6", "tags": ["binomial-distribution", "glmm", "beta-distribution", "glmmtmb", "beta-binomial-distribution"], "thread_id": "stats:677298", "title": "Need help deciding what zero-inflated GLMM to use: beta, binomial, or beta binomial"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45100, "sha256": "c2c40b470711cdaff8fdd07d388ca7dbff1238a76bfd60220b44fdb4267ddeeb", "source_url": "https://scicomp.stackexchange.com/questions/45100/gradient-descent-vs-accelerated-gradient-descent"}], "other_answers": [], "product": "code_qa", "question": "I have this Exercise in my Numerical Optimization class and here it is:\n\n\n\n\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:\n\n\n\n\n\nthe underlying signal is drawn $x_{\\text{opt}} \\sim N(0, I)$\n\n\n\n\nthe measurement matrix $A \\in \\mathbb{R}^{m \\times n}$ is drawn with independent standard Gaussian rows $A_i \\sim N(0, I)$\n\n\n\n\nthe observed data $y \\in \\mathbb{R}^m$ is $y=Ax_{\\text{opt}}+\\epsilon$ and $\\epsilon \\sim N(0, 0.25) \\text{ independent and identically distributed}$\n\n\n\n\n\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:\n\n\n\n\n\nGradient descent\n\n\n\n\nAccelerated gradient descent\n\n\n\n\n\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.\n\n\n\n\nThis is my code in Python:\n\n\n\n\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm (https://ibb.co/KjKshhKm) , https://ibb.co/2DN3bnV (https://ibb.co/2DN3bnV) , and https://ibb.co/Zpn0JY7z (https://ibb.co/Zpn0JY7z) .\n\n\n\n\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45100", "selected_answer": {"answer_html": "Accelerated Methods (Momentum / NESTEROV / FISTA) in their vanilla form do not guarantee a descent direction.
\nHence one might get steps where the objective is not minimized.
There are monotonic versions of some of the methods.
\nSee Monotone FISTA With Variable Acceleration for Compressed Sensing Magnetic Resonance Imaging (Code) and Monotonicity and Restart in Fast Gradient Methods.
Accelerated Methods (Momentum / NESTEROV / FISTA) in their vanilla form do not guarantee a descent direction.
\nHence one might get steps where the objective is not minimized.
There are monotonic versions of some of the methods.
\nSee Monotone FISTA With Variable Acceleration for Compressed Sensing Magnetic Resonance Imaging (Code) and Monotonicity and Restart in Fast Gradient Methods.
I have this Exercise in my Numerical Optimization class and here it is:
\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:
\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:
\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.
\nThis is my code in Python:
\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = "Gradient Descent")\n plt.semilogy(agd_values, label = "Accelerated Gradient Descent")\n plt.xlabel("Iteration")\n plt.ylabel("Objective Value with Logarithmic Scale")\n plt.title("Ridge Regression: Objective Value vs Iteration "+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm , https://ibb.co/2DN3bnV , and https://ibb.co/Zpn0JY7z .
\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.
\n", "question_id": 45100, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I have this Exercise in my Numerical Optimization class and here it is:\n\n\n\n\nIn this exercise, you will consider the ridge regression problem:\n$$\\min_{x \\in \\mathbb{R}^n}\\frac{1}{2}\\|Ax-y\\|^2_2+\\frac{\\lambda}{2}\\|x\\|^2_2$$\nwhich aims to recover a point $x_{\\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m=80$, and $\\lambda=1$, generate data as follows:\n\n\n\n\n\nthe underlying signal is drawn $x_{\\text{opt}} \\sim N(0, I)$\n\n\n\n\nthe measurement matrix $A \\in \\mathbb{R}^{m \\times n}$ is drawn with independent standard Gaussian rows $A_i \\sim N(0, I)$\n\n\n\n\nthe observed data $y \\in \\mathbb{R}^m$ is $y=Ax_{\\text{opt}}+\\epsilon$ and $\\epsilon \\sim N(0, 0.25) \\text{ independent and identically distributed}$\n\n\n\n\n\nNote that the objective function is $\\beta$ smooth with $\\beta=\\|A^*A\\|_\\text{op}+\\lambda$ and $\\alpha$ strongly convex with $\\alpha=\\lambda$. In your experiments, you may set $\\beta=4(m+n)+\\lambda$. Write code that generates the problem data as above and implement the following algorithms:\n\n\n\n\n\nGradient descent\n\n\n\n\nAccelerated gradient descent\n\n\n\n\n\nFor each algorithm, plot the function value over the first $50$ iterations on a semilog plot.\n\n\n\n\nThis is my code in Python:\n\n\n\n\nimport numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n\n for k in range(num_iters):\n grad = A.T @ (A @ x - y) + lmbda * x\n x = x - alpha * grad\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50):\n n = A.shape[1]\n x = np.zeros(n)\n z = np.zeros(n)\n f_values = []\n alpha = 1 / beta #Step size\n gamma = 0\n for k in range(num_iters):\n prev_x = x.copy()\n grad = A.T @ (A @ z - y) + lmbda * z\n x = z - alpha * grad\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(lmbda)) / (np.sqrt(beta) + np.sqrt(lmbda))\n z = x + gamma * (x - prev_x)\n f_values.append(ridge_objective(x, A, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 100\n m = 80\n lmbda = 1\n x_opt = np.random.randn(n)\n A = np.random.randn(m, n)\n myVariance = 0.25\n mySTD = math.sqrt(myVariance)\n epsilon = np.random.normal(0, mySTD, m)\n y = A @ x_opt + epsilon\n beta = 4*(m+n) + lmbda\n \n gd_values = gradient_descent(A, y, lmbda, beta, num_iters=50)\n agd_values = accelerated_gradient_descent(A, y, lmbda, beta, num_iters=50)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label = \"Gradient Descent\")\n plt.semilogy(agd_values, label = \"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Ridge Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\n\nAdditionally, here are the plots I have: https://ibb.co/KjKshhKm (https://ibb.co/KjKshhKm) , https://ibb.co/2DN3bnV (https://ibb.co/2DN3bnV) , and https://ibb.co/Zpn0JY7z (https://ibb.co/Zpn0JY7z) .\n\n\n\n\nI would put the images directly here, but I can't due to Stack Exchange having issues with image uploads at the moment. I suggest that you open the links in a new tab; it would make coming back to this post a lot easier. Am I supposed to get these bumps in my Accelerated Gradient Descent or is that an error or due to faulty coding? In other words, is it expected to get those bumps or should the correct solution not have those? Please reference the images if you can. If you cannot access them, please let me know. I would appreciate if someone could let me know.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Sid Meka", "profile_url": "https://scicomp.stackexchange.com/users/51369/sid-meka", "user_type": "registered"}, "created_at": "2025-06-07T03:14:18+00:00", "raw_file": "raw/codex_api_v1/18019c65cead443968e23d401a2956091deb8b40ada648e04bed5e2f03ce54b5_1790825348716030900_0.json", "raw_sha256": "05729e3e9dd3f73dae19eda7639475c736dfb4d5818353d669924bc12ddae880", "revision_guid": "211F9448-16A8-4E36-8763-3B16D1CD1986", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/211F9448-16A8-4E36-8763-3B16D1CD1986/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45100/gradient-descent-vs-accelerated-gradient-descent", "split": "train", "split_group": "ddd364ccf30cc296781c53becb9c4293936b018fbfccf6baa82fcd982ae5b9df", "tags": ["optimization", "python", "numerics", "regression", "data-analysis"], "thread_id": "scicomp:45100", "title": "Gradient Descent vs Accelerated Gradient Descent"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45105, "sha256": "b1990766f774a1d5b850c3adb758d23b68bc5ef84affbe8978c36bc7ea02fb03", "source_url": "https://scicomp.stackexchange.com/questions/45105/logistic-regression-gradient-descent-and-accelerated-version-thereof-not-acting"}], "other_answers": [], "product": "code_qa", "question": "Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.\n\n\n\n\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:\n\n\n\n\n\n$\\theta_{\\text{opt}}=(1, \\ldots , 1)^T$\n\n\n\n\n$X \\in \\mathbb{R}^{m \\times n}$ has independent and identically distributed standard normal entries with rows $x^T_i$\n\n\n\n\n$z=X\\theta_{\\text{opt}}$ and the true vector of probabilities is $p=\\frac{1}{1+e^{-z}}$, where the operations are applied entrywise to the vector $z$\n\n\n\n\n$y \\in \\{\\pm 1\\}^m$ has independent Bernoulli entries with $P(y_i=1)=p_i$\n\n\n\n\n$\\theta_0$ has independent and identically distributed standard normal entries\n\n\n\n\n\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.\n\n\n\n\nHere is my code and these are the images that generate:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\nThese are the plots that generate:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/M60t0s9p.png] (https://i.sstatic.net/M60t0s9p.png)\n\n\n\n\nWhy are my plots increasing in general and not generally decreasing?\n\n\n\n\nWhat line of code do I need to fix?", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45105", "selected_answer": {"answer_html": "The error was that I stated ja = 1 / (1+np.exp(-yz)) , but instead I should state ja = 1 / (1+np.exp(yz)).
The error was that I stated ja = 1 / (1+np.exp(-yz)) , but instead I should state ja = 1 / (1+np.exp(yz)).
Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.
\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:
\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.
\nHere is my code and these are the images that generate:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label="Gradient Descent")\n plt.semilogy(agd_values, label="Accelerated Gradient Descent")\n plt.xlabel("Iteration")\n plt.ylabel("Objective Value with Logarithmic Scale")\n plt.title("Logistic Regression: Objective Value vs Iteration "+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\nThese are the plots that generate:
\n\nWhy are my plots increasing in general and not generally decreasing?
\nWhat line of code do I need to fix?
\n", "question_id": 45105, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Consider the regularized logistic regression problem:\n$$\\min_{\\theta \\in \\mathbb{R}^n}\\sum_{i=1}^m \\ln \\left(1+e^{-y_i\\theta^T x_i}\\right)+\\frac{\\lambda}{2}\\big\\lVert\\theta\\big\\rVert^2_2.$$\nHere, $y_i \\in \\{\\pm 1\\}$ are binary labels for the data points $x_i \\in \\mathbb{R}^n$ and we are trying to find the best vector $\\theta$ of parameters for the model\n$$P(y=1 \\mid x, \\theta)=\\frac{1}{1+e^{-\\theta^T x}}.$$\nWe are doing this by minimizing the negative log likelihood function plus a regularization term.\n\n\n\n\nImplement the Gradient Descent and Accelerated Gradient Descent with $n=50$ and $m=100$ and $\\lambda=1$. Generate data as follows:\n\n\n\n\n\n$\\theta_{\\text{opt}}=(1, \\ldots , 1)^T$\n\n\n\n\n$X \\in \\mathbb{R}^{m \\times n}$ has independent and identically distributed standard normal entries with rows $x^T_i$\n\n\n\n\n$z=X\\theta_{\\text{opt}}$ and the true vector of probabilities is $p=\\frac{1}{1+e^{-z}}$, where the operations are applied entrywise to the vector $z$\n\n\n\n\n$y \\in \\{\\pm 1\\}^m$ has independent Bernoulli entries with $P(y_i=1)=p_i$\n\n\n\n\n$\\theta_0$ has independent and identically distributed standard normal entries\n\n\n\n\n\nImplement the Algorithms for Gradient Descent and Accelerated Gradient Descent and plot the function values for the iterations in a semilog plot. You may take the smoothness parameter of the objective function to be $\\beta = 100$ and the strong convexity parameter to be $\\alpha=1$.\n\n\n\n\nHere is my code and these are the images that generate:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n return my_loss + r\n\ndef logistic_gradient(theta, X, y, lmbda):\n yz = y * (X @ theta)\n ja = 1 / (1+np.exp(-yz))\n toRETURN = -((y * ja) @ X) + lmbda * theta\n return toRETURN\n\ndef gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n f_values = []\n alpha = 1 / beta\n for k in range(num_iters):\n g = logistic_gradient(theta, X, y, lmbda)\n theta = theta - alpha * g\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\ndef accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100):\n n = X.shape[1]\n theta = np.random.randn(n)\n yk = theta.copy()\n f_values = []\n alpha = 1 / beta\n jf = 1 # Used for strong convexity\n for k in range(num_iters):\n previous_theta = theta.copy()\n gr = logistic_gradient(yk, X, y, lmbda)\n theta = yk - alpha * gr\n if k == 0:\n gamma = 0\n else:\n gamma = (np.sqrt(beta) - np.sqrt(jf)) / (np.sqrt(beta) + np.sqrt(jf))\n yk = theta + gamma * (theta - previous_theta)\n f_values.append(logistic_objective(theta, X, y, lmbda))\n return f_values\n\nfor i in range(5): #For loop here to show that answers vary\n n = 50\n m = 100\n lmbda = 1\n beta = 100\n\n theta_opt = np.ones(n)\n X = np.random.randn(m, n)\n z = X @ theta_opt\n p1857 = 1 / (1+np.exp(-z))\n\n y = np.where(np.random.rand(m) < p1857, 1, -1)\n\n gd_values = gradient_descent(X, y, lmbda, beta, num_iters=100)\n agd_values = accelerated_gradient_descent(X, y, lmbda, beta, num_iters=100)\n\n plt.figure(figsize=(8, 5))\n plt.semilogy(gd_values, label=\"Gradient Descent\")\n plt.semilogy(agd_values, label=\"Accelerated Gradient Descent\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Objective Value with Logarithmic Scale\")\n plt.title(\"Logistic Regression: Objective Value vs Iteration \"+str(i+1))\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\n\n\n\nThese are the plots that generate:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/M60t0s9p.png] (https://i.sstatic.net/M60t0s9p.png)\n\n\n\n\nWhy are my plots increasing in general and not generally decreasing?\n\n\n\n\nWhat line of code do I need to fix?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Sid Meka", "profile_url": "https://scicomp.stackexchange.com/users/51369/sid-meka", "user_type": "registered"}, "created_at": "2025-06-09T03:53:39+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "6C5B17A4-CCFF-4791-B573-A3BEFEA6E971", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6C5B17A4-CCFF-4791-B573-A3BEFEA6E971/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Anton Menshov", "profile_url": "https://scicomp.stackexchange.com/users/20688/anton-menshov", "user_type": "moderator"}, "created_at": "2025-06-10T17:23:33+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "04CCF3DF-8003-43DC-8B20-604199CED7CE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/04CCF3DF-8003-43DC-8B20-604199CED7CE/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "M. A.", "profile_url": "https://scicomp.stackexchange.com/users/54367/m-a", "user_type": "registered"}, "created_at": "2025-08-03T03:10:56+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "432A63F6-E7D4-4894-AE88-DA68EC44307B", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/432A63F6-E7D4-4894-AE88-DA68EC44307B/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45105/logistic-regression-gradient-descent-and-accelerated-version-thereof-not-acting", "split": "train", "split_group": "10d72cc0b1e82969ed446d7f6bc4fec359af8252377e4286e10dc421d486cc6e", "tags": ["optimization", "numpy", "regression"], "thread_id": "scicomp:45105", "title": "Logistic Regression: Gradient Descent and Accelerated Version Thereof not acting as intended"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import cvxpy as cp\nimport numpy as np\nnp.random.seed(1)\nm = 3\nn = 3\nA = np.random.randint(0, 100, m*n).reshape(m, n)\nb = np.random.randint(0, 100, m)\nx = cp.Variable(n, integer=True)\nobjective = cp.Minimize(cp.sum_squares(A @ x - b))\nprob = cp.Problem(objective)\nresult = prob.solve()\nx.value \n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45109, "sha256": "532c98e14e0ee86c315b722062ea598c158c676673e4d0e5ca72fb3320273bef", "source_url": "https://scicomp.stackexchange.com/a/45109"}], "other_answers": [{"answer_html": "You are looking at solving a system of Diophantine equations, for which there is no known general algorithm. For the linear case there are algorithms using linear programming. The least-squares constraint can be taken into account by seeing it is an optimization problem. Ignoring the constraints on the operations for now, you could solve it using cvxpy with pyscipopt as the solver:
\nimport cvxpy as cp\nimport numpy as np\nnp.random.seed(1)\nm = 3\nn = 3\nA = np.random.randint(0, 100, m*n).reshape(m, n)\nb = np.random.randint(0, 100, m)\nx = cp.Variable(n, integer=True)\nobjective = cp.Minimize(cp.sum_squares(A @ x - b))\nprob = cp.Problem(objective)\nresult = prob.solve()\nx.value \n\nI do not know if the packages satisfy your constraints on what operations are permissible. But given that the solution and coefficients live in $\\mathbb{Z}$, I would guess that at most they use rationals internally, which can be represented by two integers each anyway and so reduce to integer arithmetic. The algorithms they use should help with finding something which satisfies your operation constraints.
\n", "answer_id": 45109, "answer_text": "You are looking at solving a system of Diophantine equations, for which there is no known general algorithm. For the linear case there are algorithms using linear programming. The least-squares constraint can be taken into account by seeing it is an optimization problem. Ignoring the constraints on the operations for now, you could solve it using cvxpy with pyscipopt as the solver:\n\n\n\n\nimport cvxpy as cp\nimport numpy as np\nnp.random.seed(1)\nm = 3\nn = 3\nA = np.random.randint(0, 100, m*n).reshape(m, n)\nb = np.random.randint(0, 100, m)\nx = cp.Variable(n, integer=True)\nobjective = cp.Minimize(cp.sum_squares(A @ x - b))\nprob = cp.Problem(objective)\nresult = prob.solve()\nx.value \n\n\n\n\n\nI do not know if the packages satisfy your constraints on what operations are permissible. But given that the solution and coefficients live in $\\mathbb{Z}$, I would guess that at most they use rationals internally, which can be represented by two integers each anyway and so reduce to integer arithmetic. The algorithms they use should help with finding something which satisfies your operation constraints.", "answer_url": "https://scicomp.stackexchange.com/a/45109", "author": "niemc", "author_url": "https://scicomp.stackexchange.com/users/50632/niemc", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-11T03:49:42+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": 45108, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "niemc", "profile_url": "https://scicomp.stackexchange.com/users/50632/niemc", "user_type": "registered"}, "created_at": "2025-06-11T03:49:42+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "84D10C8F-D10A-4820-8862-228256BCD621", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/84D10C8F-D10A-4820-8862-228256BCD621/view-source"}], "score": 1, "updated_at": "2025-06-11T03:49:42+00:00"}], "product": "code_qa", "question": "I need to find an approximate solution (in the least-squares sense) to the system of linear equations $Ax = y$, where $A$ is a $3\\times3$ matrix, and elements of $A$, $x$ and $y$ are all 32-bit integers.\n\n\n\n\nThe constraint is that only 32-bit integer arithmetic is allowed in the process of solving the system. Ideally, we should restrict ourselves to using only addition, subtraction, and multiplication of 32-bit integers. However, for simplicity, let’s assume that 32-bit integer division is also permissible. Given this, how can we find an approximate solution?", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45108", "selected_answer": {"answer_html": "If the matrix is nonsingular and you're only looking for an approximate solution, I'd suggest using Gaussian Elimination. This is basically fixed-point arithmetic, which is how early computers did arithmetic for continuous-valued problems.
\nI don't know the error analysis for fixed-point off the top of my head. But, you can check the size of $r=y-Ax$ to judge the quality of the solution. If $r$ is too large, you can try using iterative refinement: solve $Au=r$ for $u$, then the improved solution is $x+u$. It might not always converge to $r$ equalling zero, but it'll give an approximate solution.
\n", "answer_id": 45111, "answer_text": "If the matrix is nonsingular and you're only looking for an approximate solution, I'd suggest using Gaussian Elimination. This is basically fixed-point arithmetic, which is how early computers did arithmetic for continuous-valued problems.\n\n\n\n\nI don't know the error analysis for fixed-point off the top of my head. But, you can check the size of $r=y-Ax$ to judge the quality of the solution. If $r$ is too large, you can try using iterative refinement: solve $Au=r$ for $u$, then the improved solution is $x+u$. It might not always converge to $r$ equalling zero, but it'll give an approximate solution.", "answer_url": "https://scicomp.stackexchange.com/a/45111", "author": "Neil Lindquist", "author_url": "https://scicomp.stackexchange.com/users/32895/neil-lindquist", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-11T13:23:20+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": 45108, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Neil Lindquist", "profile_url": "https://scicomp.stackexchange.com/users/32895/neil-lindquist", "user_type": "registered"}, "created_at": "2025-06-11T13:23:20+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "AFFA82D8-351C-4EEF-A083-7DEBDAB5B252", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AFFA82D8-351C-4EEF-A083-7DEBDAB5B252/view-source"}], "score": 2, "updated_at": "2025-06-11T13:23:20+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "You are looking at solving a system of Diophantine equations, for which there is no known general algorithm. For the linear case there are algorithms using linear programming. The least-squares constraint can be taken into account by seeing it is an optimization problem. Ignoring the constraints on the operations for now, you could solve it using cvxpy with pyscipopt as the solver:
\nimport cvxpy as cp\nimport numpy as np\nnp.random.seed(1)\nm = 3\nn = 3\nA = np.random.randint(0, 100, m*n).reshape(m, n)\nb = np.random.randint(0, 100, m)\nx = cp.Variable(n, integer=True)\nobjective = cp.Minimize(cp.sum_squares(A @ x - b))\nprob = cp.Problem(objective)\nresult = prob.solve()\nx.value \n\nI do not know if the packages satisfy your constraints on what operations are permissible. But given that the solution and coefficients live in $\\mathbb{Z}$, I would guess that at most they use rationals internally, which can be represented by two integers each anyway and so reduce to integer arithmetic. The algorithms they use should help with finding something which satisfies your operation constraints.
\n", "answer_id": 45109, "answer_text": "You are looking at solving a system of Diophantine equations, for which there is no known general algorithm. For the linear case there are algorithms using linear programming. The least-squares constraint can be taken into account by seeing it is an optimization problem. Ignoring the constraints on the operations for now, you could solve it using cvxpy with pyscipopt as the solver:\n\n\n\n\nimport cvxpy as cp\nimport numpy as np\nnp.random.seed(1)\nm = 3\nn = 3\nA = np.random.randint(0, 100, m*n).reshape(m, n)\nb = np.random.randint(0, 100, m)\nx = cp.Variable(n, integer=True)\nobjective = cp.Minimize(cp.sum_squares(A @ x - b))\nprob = cp.Problem(objective)\nresult = prob.solve()\nx.value \n\n\n\n\n\nI do not know if the packages satisfy your constraints on what operations are permissible. But given that the solution and coefficients live in $\\mathbb{Z}$, I would guess that at most they use rationals internally, which can be represented by two integers each anyway and so reduce to integer arithmetic. The algorithms they use should help with finding something which satisfies your operation constraints.", "answer_url": "https://scicomp.stackexchange.com/a/45109", "author": "niemc", "author_url": "https://scicomp.stackexchange.com/users/50632/niemc", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-11T03:49:42+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": 45108, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "niemc", "profile_url": "https://scicomp.stackexchange.com/users/50632/niemc", "user_type": "registered"}, "created_at": "2025-06-11T03:49:42+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "84D10C8F-D10A-4820-8862-228256BCD621", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/84D10C8F-D10A-4820-8862-228256BCD621/view-source"}], "score": 1, "updated_at": "2025-06-11T03:49:42+00:00"}, {"answer_html": "If the matrix is nonsingular and you're only looking for an approximate solution, I'd suggest using Gaussian Elimination. This is basically fixed-point arithmetic, which is how early computers did arithmetic for continuous-valued problems.
\nI don't know the error analysis for fixed-point off the top of my head. But, you can check the size of $r=y-Ax$ to judge the quality of the solution. If $r$ is too large, you can try using iterative refinement: solve $Au=r$ for $u$, then the improved solution is $x+u$. It might not always converge to $r$ equalling zero, but it'll give an approximate solution.
\n", "answer_id": 45111, "answer_text": "If the matrix is nonsingular and you're only looking for an approximate solution, I'd suggest using Gaussian Elimination. This is basically fixed-point arithmetic, which is how early computers did arithmetic for continuous-valued problems.\n\n\n\n\nI don't know the error analysis for fixed-point off the top of my head. But, you can check the size of $r=y-Ax$ to judge the quality of the solution. If $r$ is too large, you can try using iterative refinement: solve $Au=r$ for $u$, then the improved solution is $x+u$. It might not always converge to $r$ equalling zero, but it'll give an approximate solution.", "answer_url": "https://scicomp.stackexchange.com/a/45111", "author": "Neil Lindquist", "author_url": "https://scicomp.stackexchange.com/users/32895/neil-lindquist", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-11T13:23:20+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": 45108, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Neil Lindquist", "profile_url": "https://scicomp.stackexchange.com/users/32895/neil-lindquist", "user_type": "registered"}, "created_at": "2025-06-11T13:23:20+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "AFFA82D8-351C-4EEF-A083-7DEBDAB5B252", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AFFA82D8-351C-4EEF-A083-7DEBDAB5B252/view-source"}], "score": 2, "updated_at": "2025-06-11T13:23:20+00:00"}], "domain": "computational_science", "external_links": [], "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": "chaohuang", "question_author_url": "https://scicomp.stackexchange.com/users/1614/chaohuang", "question_author_user_type": "registered", "question_created_at": "2025-06-11T02:14:41+00:00", "question_html": "I need to find an approximate solution (in the least-squares sense) to the system of linear equations $Ax = y$, where $A$ is a $3\\times3$ matrix, and elements of $A$, $x$ and $y$ are all 32-bit integers.
\nThe constraint is that only 32-bit integer arithmetic is allowed in the process of solving the system. Ideally, we should restrict ourselves to using only addition, subtraction, and multiplication of 32-bit integers. However, for simplicity, let’s assume that 32-bit integer division is also permissible. Given this, how can we find an approximate solution?
\n", "question_id": 45108, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I need to find an approximate solution (in the least-squares sense) to the system of linear equations $Ax = y$, where $A$ is a $3\\times3$ matrix, and elements of $A$, $x$ and $y$ are all 32-bit integers.\n\n\n\n\nThe constraint is that only 32-bit integer arithmetic is allowed in the process of solving the system. Ideally, we should restrict ourselves to using only addition, subtraction, and multiplication of 32-bit integers. However, for simplicity, let’s assume that 32-bit integer division is also permissible. Given this, how can we find an approximate solution?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "chaohuang", "profile_url": "https://scicomp.stackexchange.com/users/1614/chaohuang", "user_type": "registered"}, "created_at": "2025-06-11T02:14:41+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "2A2B73FA-2753-4555-9144-F7C996DD4E57", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2A2B73FA-2753-4555-9144-F7C996DD4E57/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45108/solving-integer-equation", "split": "holdout", "split_group": "41c5cd54e4ec6c41b3a032f81fd634673733aeddcd700214fc94675e7bd774a8", "tags": ["linear-solver", "linear-programming", "least-squares", "mixed-integer-programming", "computer-arithmetic"], "thread_id": "scicomp:45108", "title": "Solving integer equation"}} {"accepted_answer": null, "code_blocks": [{"block_index": 2, "code_text": "#includeThere is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.
\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$
\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n
If we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n
My python code used to compute this and make the animation is below:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r"$\\phi(t)$", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f"Updating frame{frame}")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()\n\n", "answer_id": 45119, "answer_text": "There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.\n\n\n\n\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$\n\n\n\n\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n[image: wave equation simplification solution; source: https://i.sstatic.net/813fBMTK.gif] (https://i.sstatic.net/813fBMTK.gif)\n\n\n\n\nIf we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n[image: nonlinear pde example solution; source: https://i.sstatic.net/2fRhShDM.gif] (https://i.sstatic.net/2fRhShDM.gif)\n\n\n\n\nMy python code used to compute this and make the animation is below:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r\"$\\phi(t)$\", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f\"Updating frame{frame}\")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45119", "author": "spektr", "author_url": "https://scicomp.stackexchange.com/users/9804/spektr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-17T21:04:45+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": 45112, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "spektr", "profile_url": "https://scicomp.stackexchange.com/users/9804/spektr", "user_type": "registered"}, "created_at": "2025-06-17T21:04:45+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "E3F7E841-70B0-4D84-AA38-D0BBD92FA08E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E3F7E841-70B0-4D84-AA38-D0BBD92FA08E/view-source"}], "score": 3, "updated_at": "2025-06-17T21:04:45+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.
\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$
\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n
If we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n
My python code used to compute this and make the animation is below:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r"$\\phi(t)$", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f"Updating frame{frame}")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()\n\n", "answer_id": 45119, "answer_text": "There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.\n\n\n\n\n$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - \\frac{\\partial \\phi}{\\partial x} &= v\\\\\n\\frac{\\partial v}{\\partial t} + \\frac{\\partial v}{\\partial x} &= m^2 \\phi + \\lambda \\phi^3\n\\end{align*}$$\n\n\n\n\nApproximating the spatial derivatives of $\\phi$ and $v$ can now be done in a way that more easily takes into account the characteristics of each hyperbolic equation. Today I went ahead and implemented this approach based on the periodic boundary condition and the initial conditions you mentioned above, namely that $\\phi(x, 0) = \\cos(x)$ and $\\frac{\\partial \\phi}{\\partial t}(x, 0) = \\sin(x)$. Using these conditions, we obtain the initial condition for $v$ of $v(x, 0) = 2 \\sin(x)$. If we set $m^2 = \\lambda = 0$, we get the below solution:\n[image: wave equation simplification solution; source: https://i.sstatic.net/813fBMTK.gif] (https://i.sstatic.net/813fBMTK.gif)\n\n\n\n\nIf we set $m^2 = 0.8$ and $\\lambda = 1/60$, we get the below solution:\n[image: nonlinear pde example solution; source: https://i.sstatic.net/2fRhShDM.gif] (https://i.sstatic.net/2fRhShDM.gif)\n\n\n\n\nMy python code used to compute this and make the animation is below:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nplt.rcParams['text.usetex'] = True\n\ndef initial_condition(x):\n return np.concatenate((np.cos(x), 2.0*np.sin(x)))\n\ndef compute_time_derivatives(q, t, x, mu, lmda):\n # setup derivative approximation stencils using the fact\n # we are using periodic BCs\n dx = x[1] - x[0]\n c_upwind = np.array([0.5, -2.0, 1.5]) / dx\n c_downwind = np.array([-1.5, 2.0, -0.5]) / dx\n idx_upwind = np.array([-2, -1, 0], dtype=int)\n idx_downwind = np.array([0, 1, 2], dtype=int)\n\n # extract the two fields\n n = len(x)\n u = q[:n]\n v = q[n:]\n\n # compute time derivatives of both fields\n dudt = np.zeros((n,))\n dvdt = np.zeros((n,))\n for i in range(n):\n idu = i + idx_upwind\n idd = i + idx_downwind\n dudt[i] = np.dot(np.take(u, idd, mode='wrap'), c_downwind) + v[i]\n dvdt[i] = -np.dot(np.take(v, idu, mode='wrap'), c_upwind) - u[i]*(mu + lmda*u[i]**2)\n\n # return the concatenation of the two time derivative vectors\n return np.concatenate((dudt, dvdt))\n\ndef rk4_update(q, t, dt, f):\n k1 = f(t, q)\n k2 = f(t + 0.5 * dt, q + (0.5 * dt) * k1)\n k3 = f(t + 0.5 * dt, q + (0.5 * dt) * k2)\n k4 = f(t + dt, q + dt * k3)\n return q + (dt/6.0) * (k1 + 2.0*(k2 + k3) + k4)\n\ndef simulation(x_values, t_values, m, lmda):\n\n # setup the function to compute time derivatives\n f = lambda t, q: compute_time_derivatives(q, t, x_values, m, lmda)\n\n # solve the PDE\n nx = len(x_values)\n nt = len(t_values)\n dt = t_values[1] - t_values[0]\n q_soln = np.zeros((2 * nx, nt))\n q_soln[:, 0] = initial_condition(x_values)\n for i in range(1, nt):\n q_soln[:, i] = rk4_update(q_soln[:, i-1], t_values[i], dt, f)\n\n # return the solution to the PDE\n return q_soln\n\ndef plot_solution(t, x, q_soln):\n nv, nt = q_soln.shape\n nu = nv // 2\n\n # setup basics of figure\n fig, ax = plt.subplots(figsize=(10, 6))\n fig.set_dpi(80)\n line, = ax.plot(x, q_soln[:nu, 0])\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(-1.5, 1.5) # Set limits slightly wider\n ax.set_xlabel('X-coordinate')\n ax.set_ylabel(r\"$\\phi(t)$\", size=16)\n ax.set_title('Solution over Time: Time = 0.00')\n\n def update(frame):\n print(f\"Updating frame{frame}\")\n line.set_ydata(q_soln[:nu, frame])\n ax.set_title(f'Solution over Time: Time = {t[frame]:.2f}')\n return line,\n\n # Create the animation\n ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)\n\n # To save the animation (requires ffmpeg or imagemagick installed)\n #ani.save('non-trivial-soln.gif', writer='pillow', fps=60)\n ani.save('simplified-wave-eqn-soln.gif', writer='pillow', fps=60)\n #ani.save('pde_solution.mp4', writer='ffmpeg', fps=60)\n\ndef main(t_final = 20.0, num_times=500, num_pts=100):\n\n # setup the time and space grid\n t_values = np.linspace(0.0, t_final, num_times)\n x_values = np.linspace(0.0, 2.0 * np.pi, num=num_pts + 1)[:num_pts]\n\n # compute solution to PDE\n mu = 0.0*0.8\n lmda = 0.0*1e-1/6.0\n q_soln = simulation(x_values, t_values, mu, lmda)\n\n # plot solution to PDE\n plot_solution(t_values, x_values, q_soln)\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45119", "author": "spektr", "author_url": "https://scicomp.stackexchange.com/users/9804/spektr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-17T21:04:45+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": 45112, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "spektr", "profile_url": "https://scicomp.stackexchange.com/users/9804/spektr", "user_type": "registered"}, "created_at": "2025-06-17T21:04:45+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "E3F7E841-70B0-4D84-AA38-D0BBD92FA08E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E3F7E841-70B0-4D84-AA38-D0BBD92FA08E/view-source"}], "score": 3, "updated_at": "2025-06-17T21:04:45+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Leapfrog_integration", "https://i.sstatic.net/2fRhShDM.gif", "https://i.sstatic.net/813fBMTK.gif", "https://jumpshare.com/s/IyNNcFdCeCTAcpIShWLY", "https://jumpshare.com/s/zPqlo3o0AGXPfadHQmxG"], "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": "Peter", "question_author_url": "https://scicomp.stackexchange.com/users/46677/peter", "question_author_user_type": "registered", "question_created_at": "2025-06-13T14:05:56+00:00", "question_html": "i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.
\nBelow i listed some input files
\nUnstable simulation
\n256\n1000\n0.2\n0.05\n0.0\n0.0\n\nHere is much more stable simulation with this input file
\n64\n1000\n0.2\n0.05\n0.0\n0.0\n\nThis is my C++ code.
\nsimulation.cpp
\n#include <iostream>\n#include <fstream>\n#include <cmath>\nint main() {\n int nx, nt;\n double dx, dt, mu, lambda;\n std::ifstream fin("input.txt");\n fin >> nx >> nt >> dx >> dt >> mu >> lambda;\n fin.close();\n int *sup = new int[nx];\n int *sdn = new int[nx];\n double *phi = new double[nx];\n double *pi = new double[nx];\n double *psi = new double[nx];\n double *chi = new double[nx];\n for (int x = 0; x < nx; ++x) {\n if (x == 0) {\n sup[x] = x+1;\n sdn[x] = nx-1;\n }\n else if (x == nx-1) {\n sup[x] = 0;\n sdn[x] = x-1;\n }\n else {\n sup[x] = x+1;\n sdn[x] = x-1;\n }\n phi[x] = cos(x*dx);\n pi[x] = sin(x*dx);\n }\n std::ofstream fout;\n for (int t = 0; t < nt; ++t) {\n fout.open("output_"+std::to_string(t)+".txt");\n for (int x = 0; x < nx; ++x) {\n psi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n fout << x*dx << '\\t' << phi[x] << '\\n';\n }\n for (int x = 0; x < nx; ++x) {\n phi[x] = phi[x] + dt * pi[x] + dt*dt/2 * psi[x];\n }\n for (int x = 0; x < nx; ++x) {\n chi[x] = (phi[sup[x]]-2*phi[x]+phi[sdn[x]])/(dx*dx)-mu*phi[x]-lambda*phi[x]*phi[x]*phi[x];\n }\n for (int x = 0; x < nx; ++x) {\n pi[x] = pi[x] + dt/2 * (psi[x]+chi[x]);\n }\n fout.close();\n }\n delete[] psi;\n delete[] chi;\n delete[] pi;\n delete[] phi;\n delete[] sup;\n delete[] sdn;\n}\n\n\n", "question_id": 45112, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "i'm trying to simulate one dimensional phi^4 theory.\n$$\\frac{\\partial^2φ}{\\partial t^2}-\\frac{\\partial^2φ}{\\partial x^2}+m^2φ+λφ^3=0$$\nI'm using leapfrog (https://en.wikipedia.org/wiki/Leapfrog_integration) method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial conditions are phi = cos(xdx), pi = sin(xdx) (you see them in the code). But my problem is that after i output the field, i see that after some time fluctuations start to appear near the boundaries, and they propagate to whole simulation after a while.\nI'm using gnuplot to plot the field, and to make animations.\n\n\n\n\nBelow i listed some input files\n\n\n\n\nUnstable simulation (https://jumpshare.com/s/zPqlo3o0AGXPfadHQmxG)\n\n\n\n\n256\n1000\n0.2\n0.05\n0.0\n0.0\n\n\n\n\n\nHere is much more stable simulation (https://jumpshare.com/s/IyNNcFdCeCTAcpIShWLY) with this input file\n\n\n\n\n64\n1000\n0.2\n0.05\n0.0\n0.0\n\n\n\n\n\nThis is my C++ code.\n\n\n\n\nsimulation.cpp\n\n\n\n\n#include In the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:
\nIn the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:
\nI wrote a symbolic regression tool in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and correlation approaches, but they don't give good results for two function definitions (2*log(x1)+3*x2-x1*x2+5 and exp(x1)). An approach could be to consider first correlation term, do a regression, remove main component and iterate again but it should not work for cos(log) I think.\nGiven data sampled from a function like y = 3·cos(2·log(4·x+5)+1), how can one recover the involvement of operators like log and cos from input-output data only, ideally without pre-supplying them?
import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {"neg": (lambda x: sympy.sympify("neg(" + str(x) + ")"), operator.neg),\n "abs": (sympy.Abs, operator.abs),\n "inv_": (lambda x: sympy.sympify("inv_(" + str(x) + ")"), lambda x: 1 / x),\n "sqrt": (sympy.sqrt, np.sqrt),\n "cos": (sympy.cos, np.cos),\n "sin": (sympy.sin, np.sin),\n "exp": (sympy.tan, np.tan),\n "log": (sympy.log, np.log),\n "exp": (sympy.exp, np.exp),\n "sinh": (sympy.sinh, np.sinh),\n "cosh": (sympy.cosh, np.cosh),\n "floor": (lambda x: sympy.sympify("floor(" + str(x) + ")"), np.ceil),\n "ceil": (lambda x: sympy.sympify("ceil(" + str(x) + ")"), np.floor)}\n\nbinary_operators = {"+": (operator.add, operator.add),\n "-": (operator.sub, operator.sub),\n "*": (operator.mul, operator.mul),\n "/": (operator.truediv, operator.truediv),\n "//": (operator.floordiv, operator.floordiv),\n "%": (operator.mod, operator.mod),\n "**": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {"+": True, "-": True, "*": False, "conv": False}\nsymbols = sympy.symbols("x1 x2")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n \nfor i in range(0, len(symbols)):\n X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n sym_op, num_op = v\n\n for var in symbols:\n feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n sym_op, num_op = v\n \n indices1 = list(range(0, len(symbols)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(symbols)))\n\n if (k in list(symmetric_binary_operators.keys())):\n indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n \n for i2 in indices2:\n feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint("Top 10 features les plus corrélées (Pearson):\\n")\nfor name in correlations_sorted.head(10).index:\n print(f"{name:30} corr: {correlations[name]:+.4f}")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n features_sorted[i] = list(features_sorted[i])\n x = features_sorted[i]\n imp_ = x[1]\n x.append(abs(x[1] - imp))\n imp = imp_\n\nprint("Top 10 features les plus utiles :\\n")\nfor name, score, r in features_sorted[:10]:\n print(f"{name:30} importance: {score:.4f} {r:.4f}")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n #if (score > min_score):\n if (r > min_r):\n if (ops[name] in unary_operators):\n un_ops.add(ops[name])\n elif (ops[name] in binary_operators):\n bin_ops.add(ops[name]) \n\nprint("un_ops", un_ops)\nprint("bin_ops", bin_ops)\n\nThe corresponding output is:
\nTop 10 features les plus corrélées (Pearson):\n\nx1*x2 corr: -0.9480\nx1 + x2 corr: -0.8527\nneg(x1) corr: +0.8298\nAbs(x1) corr: -0.8298\nceil(x1) corr: -0.8244\nfloor(x1) corr: -0.8244\nsqrt(x1) corr: -0.8170\nlog(x1) corr: -0.7880\ninv_(x1) corr: +0.6826\nsinh(x1) corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2 importance: 0.7583 0.7583\nx1 + x2 importance: 0.0850 0.6734\nlog(x1) importance: 0.0192 0.0658\ninv_(x1) importance: 0.0170 0.0022\nsinh(x1) importance: 0.0164 0.0007\nneg(x1) importance: 0.0162 0.0002\nsqrt(x1) importance: 0.0159 0.0003\nexp(x1) importance: 0.0159 0.0001\ncosh(x1) importance: 0.0151 0.0008\nAbs(x1) importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n\nAnother approach is to consider this: I have as input x1 to xn data vectors, f1 to fm unary operators, g1 to gp binary operators, a1 to aq and b1 to bq real coefficients such that we can realize combinations like aixj+bi giving an Xj, or aifj(Xk)+bi or even ai*gj(Xk, Xl)+bi as new Xj.
\nThe corresponding code could approach this:
\nimport numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n l = np.sum((x - y) ** 2)\n\n if (np.isnan(l)):\n return np.inf\n\n return l\n\ndef num_modules(unary_ops, binary_ops):\n modules = ['numpy']\n\n for name, op in unary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.Function):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n for name, op in binary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n return modules\n\nclass Node:\n def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n self.symnet = symnet\n self.index = symnet.add_param()\n self.name = name\n self.op = op\n self.leaf1 = leaf1\n self.leaf2 = leaf2\n self.sym_x1 = sym_x1\n self.num_x1 = num_x1\n self.sym_x2 = sym_x2\n self.num_x2 = num_x2\n\n def evalf(self, modules):\n leaf1 = copy.deepcopy(self.leaf1)\n x = 0\n \n if (isinstance(leaf1, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n x = f(self.num_x1)\n else:\n x = leaf1.evalf(modules)\n\n leaf2 = copy.deepcopy(self.leaf2)\n\n if (leaf2 == None):\n if (self.op):\n return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n else:\n return x\n \n y = 0\n \n if (isinstance(leaf2, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n y = f(self.num_x2)\n else:\n y = leaf2.evalf(modules)\n \n return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n \n def expr(self):\n a = "a" + str(self.index)\n b = "b" + str(self.index)\n \n if (isinstance(self.leaf1, sympy.Symbol)):\n return sympy.sympify(a + "*" + str(self.leaf1) + "+" + b)\n \n if (self.leaf2 == None):\n if (self.op):\n return sympy.sympify(a + "*(" + str(self.op[0](self.leaf1.expr())) + ")+" + b)\n \n return sympy.sympify(a + "*(" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + ")+" + b)\n\nclass SymNet:\n def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n self.X = X\n self.symbols = symbols\n self.un_ops = un_ops\n self.bin_ops = bin_ops\n self.un_ops_index = 0\n self.bin_ops_index = 0\n self.symm_bin_ops = symm_bin_ops\n self.a = []\n self.b = []\n self.nodes = []\n \n assert(len(X) == len(symbols))\n \n for i in range(0, len(X)):\n self.nodes.append(Node(self, "", None, symbols[i], symbols[i], X[i]))\n\n def add_param(self):\n self.a = np.array(list(self.a) + [0])\n self.b = np.array(list(self.b) + [0])\n \n return len(self.a) - 1\n\n def add_layer(self): \n new_nodes = []\n \n for k, v in self.un_ops.items():\n for n in self.nodes[self.un_ops_index:]:\n new_nodes.append(Node(self, k, v, n))\n\n self.un_ops_index = len(self.nodes)\n self.nodes += new_nodes\n \n new_nodes = []\n nodes = self.nodes#[self.bin_ops_index:]\n \n for k, v in self.bin_ops.items():\n indices1 = list(range(0, len(nodes)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(nodes)))\n\n for key, value in self.symm_bin_ops.items():\n if (k == key):\n indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n break\n \n for i2 in indices2:\n new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n #self.bin_ops_index = len(self.nodes)\n self.nodes += new_nodes\n\n def compute_outputs(self, a, b):\n assert(len(a) == len(self.a))\n assert(len(b) == len(self.b))\n \n self.a = a\n self.b = b\n \n outputs = []\n modules = num_modules(self.un_ops, self.bin_ops)\n\n for n in self.nodes:\n outputs.append(n.evalf(modules))\n\n return outputs\n\n def expressions(self):\n exprs = []\n \n for n in self.nodes:\n exprs.append(n.expr())\n\n return exprs\n\n def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n outputs = None\n\n for i in range(0, N):\n o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n \n if (outputs is None):\n outputs = np.zeros(len(o))\n\n for j in range(0, len(o)):\n outputs[j] += loss_func(o[j], y)\n\n outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n \n #print([(x[0].expr(), x[1]) for x in l])\n #print([(x[0].expr(), np.log(x[1])) for x in l])\n \n m = l[-1][1]\n #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n print(0.75 * d[0])\n z = zip([x[0].expr() for x in l], d)\n print(list((x, y) for x, y in z))\n\nunary_operators = {#"neg": (lambda x: sympy.sympify("neg(" + str(x) + ")"), operator.neg),\n #"abs": (sympy.Abs, operator.abs),\n #"inv_": (lambda x: sympy.sympify("inv_(" + str(x) + ")"), lambda x: 1 / x),\n "sqrt": (sympy.sqrt, np.sqrt),\n "cos": (sympy.cos, np.cos),\n #"sin": (sympy.sin, np.sin),\n #"tan": (sympy.tan, np.tan),\n "log": (sympy.log, np.log),\n #"exp": (sympy.exp, np.exp),\n #"sinh": (sympy.sinh, np.sinh),\n #"cosh": (sympy.cosh, np.cosh),\n #"floor": (lambda x: sympy.sympify("floor(" + str(x) + ")"), np.ceil),\n #"ceil": (lambda x: sympy.sympify("ceil(" + str(x) + ")"), np.floor),\n }\n\nbinary_operators = {#"+": (operator.add, operator.add),\n #"-": (operator.sub, operator.sub),\n #"*": (operator.mul, operator.mul),\n #"/": (operator.truediv, operator.truediv),\n #"//": (operator.floordiv, operator.floordiv),\n #"%": (operator.mod, operator.mod),\n #"**": (sympy.Pow, operator.pow),\n }\n\nsymmetric_binary_operators = {"+": True, "-": True, "*": False, "conv": False, "fmin": True, "fmax": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol("x1")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols("x1 x2"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n\nI tried scipy.curve_fit instead of random and it does not work so much. Here is the code:
\ndef fit(self, y, loss_func = mse_loss):\n a_s = []\n b_s = []\n losses = []\n exprs = self.expressions()\n modules = num_modules(self.un_ops, self.bin_ops)\n maxfev = 10000\n \n for expr in exprs:\n a = np.zeros(len(symnet.a))\n b = np.zeros(len(symnet.b))\n \n ab_syms = list(expr.free_symbols - set(self.symbols))\n f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n func = model_func(f)\n \n params = np.zeros(len(ab_syms))\n \n try:\n params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n except RuntimeError as e:\n print(e)\n \n for i in range(0, len(ab_syms)):\n index = int(str(ab_syms[i])[1:])\n \n if (str(ab_syms[i])[0] == "a"):\n a[index] = params[i]\n else:\n b[index] = params[i]\n \n l = loss_func(func(self.X, *params), y)\n \n a_s.append(a)\n b_s.append(b)\n losses.append(l)\n \n losses = np.array(losses)\n losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n losses = np.nan_to_num(losses, neginf = np.max(losses))\n losses = 1 - losses / np.max(losses)\n \n print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n\nAnd the associated output (cos(log) optimization failed):
\n[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]\n\n", "question_id": 45114, "question_license": "CC BY-SA 4.0", "question_score": 0, "question_text": "I wrote a symbolic regression tool (https://github.com/Julien-Livet/SymbolicRegression) in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and correlation approaches, but they don't give good results for two function definitions (2*log(x1)+3*x2-x1*x2+5 and exp(x1)). An approach could be to consider first correlation term, do a regression, remove main component and iterate again but it should not work for cos(log) I think.\nGiven data sampled from a function like y = 3·cos(2·log(4·x+5)+1), how can one recover the involvement of operators like log and cos from input-output data only, ideally without pre-supplying them?\n\n\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.log(x1) + 3 * x2 - x1 * x2 + 5\n#y = np.exp(x1)\n\nunary_operators = {\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n \"abs\": (sympy.Abs, operator.abs),\n \"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n \"sin\": (sympy.sin, np.sin),\n \"exp\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n \"exp\": (sympy.exp, np.exp),\n \"sinh\": (sympy.sinh, np.sinh),\n \"cosh\": (sympy.cosh, np.cosh),\n \"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n \"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor)}\n\nbinary_operators = {\"+\": (operator.add, operator.add),\n \"-\": (operator.sub, operator.sub),\n \"*\": (operator.mul, operator.mul),\n \"/\": (operator.truediv, operator.truediv),\n \"//\": (operator.floordiv, operator.floordiv),\n \"%\": (operator.mod, operator.mod),\n \"**\": (sympy.Pow, operator.pow)}\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False}\nsymbols = sympy.symbols(\"x1 x2\")\nX = [x1, x2]\n\nX_raw = pd.DataFrame()\n \nfor i in range(0, len(symbols)):\n X_raw[str(symbols[i])] = X[i]\n\nfeature_dict = {}\nbase_vars = [str(x) for x in symbols]\nops = {}\n\nfor k, v in unary_operators.items():\n sym_op, num_op = v\n\n for var in symbols:\n feature_dict[str(sym_op(var))] = num_op(X_raw[str(var)])\n ops[str(sym_op(var))] = k\n\nfor k, v in binary_operators.items():\n sym_op, num_op = v\n \n indices1 = list(range(0, len(symbols)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(symbols)))\n\n if (k in list(symmetric_binary_operators.keys())):\n indices2 = list(range(i1 + 1 if v else i1, len(base_vars)))\n \n for i2 in indices2:\n feature_dict[str(sym_op(symbols[i1], symbols[i2]))] = num_op(X_raw[str(symbols[i1])], X_raw[str(symbols[i2])])\n ops[str(sym_op(symbols[i1], symbols[i2]))] = k\n\nX_feat = pd.DataFrame(feature_dict)\nX_feat = X_feat.replace([np.inf, -np.inf, np.nan], 0)\nX_feat = X_feat.loc[:, (X_feat.abs().max() < 1e6)]\n\ncorrelations = X_feat.apply(lambda col: np.corrcoef(col, y)[0, 1])\n\n# Trier par valeur absolue décroissante\ncorrelations_sorted = correlations.abs().sort_values(ascending = False)\n\nprint(\"Top 10 features les plus corrélées (Pearson):\\n\")\nfor name in correlations_sorted.head(10).index:\n print(f\"{name:30} corr: {correlations[name]:+.4f}\")\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_feat_scaled_array = scaler.fit_transform(X_feat)\nX_feat = pd.DataFrame(X_feat_scaled_array, columns=X_feat.columns)\n\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_feat, y, test_size = 0.2, random_state = 0)\n\nmodel = RandomForestRegressor(n_estimators = 200, random_state = 0)#, max_depth = 10)\nmodel.fit(X_train, y_train)\n\nimportances = model.feature_importances_\n\nfeatures_sorted = sorted(zip(X_feat.columns, importances), key = lambda x: x[1], reverse = True)\n\nimp = 0\n\nfor i in range(0, len(features_sorted)):\n features_sorted[i] = list(features_sorted[i])\n x = features_sorted[i]\n imp_ = x[1]\n x.append(abs(x[1] - imp))\n imp = imp_\n\nprint(\"Top 10 features les plus utiles :\\n\")\nfor name, score, r in features_sorted[:10]:\n print(f\"{name:30} importance: {score:.4f} {r:.4f}\")\n\nmin_score = 0.015\nmin_r = 0.05\nun_ops = set()\nbin_ops = set()\n\nfor name, score, r in features_sorted:\n #if (score > min_score):\n if (r > min_r):\n if (ops[name] in unary_operators):\n un_ops.add(ops[name])\n elif (ops[name] in binary_operators):\n bin_ops.add(ops[name]) \n\nprint(\"un_ops\", un_ops)\nprint(\"bin_ops\", bin_ops)\n\n\n\n\n\nThe corresponding output is:\n\n\n\n\nTop 10 features les plus corrélées (Pearson):\n\nx1*x2 corr: -0.9480\nx1 + x2 corr: -0.8527\nneg(x1) corr: +0.8298\nAbs(x1) corr: -0.8298\nceil(x1) corr: -0.8244\nfloor(x1) corr: -0.8244\nsqrt(x1) corr: -0.8170\nlog(x1) corr: -0.7880\ninv_(x1) corr: +0.6826\nsinh(x1) corr: -0.6305\nTop 10 features les plus utiles :\n\nx1*x2 importance: 0.7583 0.7583\nx1 + x2 importance: 0.0850 0.6734\nlog(x1) importance: 0.0192 0.0658\ninv_(x1) importance: 0.0170 0.0022\nsinh(x1) importance: 0.0164 0.0007\nneg(x1) importance: 0.0162 0.0002\nsqrt(x1) importance: 0.0159 0.0003\nexp(x1) importance: 0.0159 0.0001\ncosh(x1) importance: 0.0151 0.0008\nAbs(x1) importance: 0.0137 0.0014\nun_ops {'log'}\nbin_ops {'*', '+'}\n\n\n\n\n\nAnother approach is to consider this: I have as input x1 to xn data vectors, f1 to fm unary operators, g1 to gp binary operators, a1 to aq and b1 to bq real coefficients such that we can realize combinations like aixj+bi giving an Xj, or aifj(Xk)+bi or even ai*gj(Xk, Xl)+bi as new Xj.\n\n\n\n\nThe corresponding code could approach this:\n\n\n\n\nimport numpy as np\nimport operator\nimport random\nimport sympy\n\ndef mse_loss(x, y):\n l = np.sum((x - y) ** 2)\n\n if (np.isnan(l)):\n return np.inf\n\n return l\n\ndef num_modules(unary_ops, binary_ops):\n modules = ['numpy']\n\n for name, op in unary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.Function):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n for name, op in binary_ops.items():\n sym_op, num_op = op\n\n #if (type(sym_op) == sympy.core.function.UndefinedFunction):\n if (name.isidentifier()):\n modules.append({name: num_op})\n\n return modules\n\nclass Node:\n def __init__(self, symnet, name, op, leaf1, sym_x1 = None, num_x1 = None, leaf2 = None, sym_x2 = None, num_x2 = None):\n self.symnet = symnet\n self.index = symnet.add_param()\n self.name = name\n self.op = op\n self.leaf1 = leaf1\n self.leaf2 = leaf2\n self.sym_x1 = sym_x1\n self.num_x1 = num_x1\n self.sym_x2 = sym_x2\n self.num_x2 = num_x2\n\n def evalf(self, modules):\n leaf1 = copy.deepcopy(self.leaf1)\n x = 0\n \n if (isinstance(leaf1, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x1, leaf1, modules = modules)\n x = f(self.num_x1)\n else:\n x = leaf1.evalf(modules)\n\n leaf2 = copy.deepcopy(self.leaf2)\n\n if (leaf2 == None):\n if (self.op):\n return self.symnet.a[self.index] * self.op[1](x) + self.symnet.b[self.index]\n else:\n return x\n \n y = 0\n \n if (isinstance(leaf2, sympy.Symbol)):\n f = sympy.lambdify(self.sym_x2, leaf2, modules = modules)\n y = f(self.num_x2)\n else:\n y = leaf2.evalf(modules)\n \n return self.symnet.a[self.index] * self.op[1](x, y) + self.symnet.b[self.index]\n \n def expr(self):\n a = \"a\" + str(self.index)\n b = \"b\" + str(self.index)\n \n if (isinstance(self.leaf1, sympy.Symbol)):\n return sympy.sympify(a + \"*\" + str(self.leaf1) + \"+\" + b)\n \n if (self.leaf2 == None):\n if (self.op):\n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr())) + \")+\" + b)\n \n return sympy.sympify(a + \"*(\" + str(self.op[0](self.leaf1.expr(), self.leaf2.expr())) + \")+\" + b)\n\nclass SymNet:\n def __init__(self, X, symbols, un_ops, bin_ops, symm_bin_ops):\n self.X = X\n self.symbols = symbols\n self.un_ops = un_ops\n self.bin_ops = bin_ops\n self.un_ops_index = 0\n self.bin_ops_index = 0\n self.symm_bin_ops = symm_bin_ops\n self.a = []\n self.b = []\n self.nodes = []\n \n assert(len(X) == len(symbols))\n \n for i in range(0, len(X)):\n self.nodes.append(Node(self, \"\", None, symbols[i], symbols[i], X[i]))\n\n def add_param(self):\n self.a = np.array(list(self.a) + [0])\n self.b = np.array(list(self.b) + [0])\n \n return len(self.a) - 1\n\n def add_layer(self): \n new_nodes = []\n \n for k, v in self.un_ops.items():\n for n in self.nodes[self.un_ops_index:]:\n new_nodes.append(Node(self, k, v, n))\n\n self.un_ops_index = len(self.nodes)\n self.nodes += new_nodes\n \n new_nodes = []\n nodes = self.nodes#[self.bin_ops_index:]\n \n for k, v in self.bin_ops.items():\n indices1 = list(range(0, len(nodes)))\n\n for i1 in indices1:\n indices2 = list(range(0, len(nodes)))\n\n for key, value in self.symm_bin_ops.items():\n if (k == key):\n indices2 = list(range(i1 + 1 if value else i1, len(nodes)))\n break\n \n for i2 in indices2:\n new_nodes.append(Node(self, k, v, nodes[i1], leaf2 = nodes[i2]))\n\n #self.bin_ops_index = len(self.nodes)\n self.nodes += new_nodes\n\n def compute_outputs(self, a, b):\n assert(len(a) == len(self.a))\n assert(len(b) == len(self.b))\n \n self.a = a\n self.b = b\n \n outputs = []\n modules = num_modules(self.un_ops, self.bin_ops)\n\n for n in self.nodes:\n outputs.append(n.evalf(modules))\n\n return outputs\n\n def expressions(self):\n exprs = []\n \n for n in self.nodes:\n exprs.append(n.expr())\n\n return exprs\n\n def fit(self, y, loss_func = mse_loss, N = 100, bounds = (-10, 10)):\n outputs = None\n\n for i in range(0, N):\n o = np.array(self.compute_outputs(np.random.uniform(bounds[0], bounds[1], size = len(symnet.a)),\n np.random.uniform(bounds[0], bounds[1], size = len(symnet.b))), dtype = np.float64)\n \n if (outputs is None):\n outputs = np.zeros(len(o))\n\n for j in range(0, len(o)):\n outputs[j] += loss_func(o[j], y)\n\n outputs = np.nan_to_num(outputs, nan = max(outputs))\n\n l = sorted(zip(self.nodes, outputs), key = lambda x: x[1])\n \n #print([(x[0].expr(), x[1]) for x in l])\n #print([(x[0].expr(), np.log(x[1])) for x in l])\n \n m = l[-1][1]\n #print([(x[0].expr(), 1 - np.log(x[1]) / np.log(m)) for x in l])\n d = np.array([1 - np.log(x[1]) / np.log(m) for x in l])\n print(0.75 * d[0])\n z = zip([x[0].expr() for x in l], d)\n print(list((x, y) for x, y in z))\n\nunary_operators = {#\"neg\": (lambda x: sympy.sympify(\"neg(\" + str(x) + \")\"), operator.neg),\n #\"abs\": (sympy.Abs, operator.abs),\n #\"inv_\": (lambda x: sympy.sympify(\"inv_(\" + str(x) + \")\"), lambda x: 1 / x),\n \"sqrt\": (sympy.sqrt, np.sqrt),\n \"cos\": (sympy.cos, np.cos),\n #\"sin\": (sympy.sin, np.sin),\n #\"tan\": (sympy.tan, np.tan),\n \"log\": (sympy.log, np.log),\n #\"exp\": (sympy.exp, np.exp),\n #\"sinh\": (sympy.sinh, np.sinh),\n #\"cosh\": (sympy.cosh, np.cosh),\n #\"floor\": (lambda x: sympy.sympify(\"floor(\" + str(x) + \")\"), np.ceil),\n #\"ceil\": (lambda x: sympy.sympify(\"ceil(\" + str(x) + \")\"), np.floor),\n }\n\nbinary_operators = {#\"+\": (operator.add, operator.add),\n #\"-\": (operator.sub, operator.sub),\n #\"*\": (operator.mul, operator.mul),\n #\"/\": (operator.truediv, operator.truediv),\n #\"//\": (operator.floordiv, operator.floordiv),\n #\"%\": (operator.mod, operator.mod),\n #\"**\": (sympy.Pow, operator.pow),\n }\n\nsymmetric_binary_operators = {\"+\": True, \"-\": True, \"*\": False, \"conv\": False, \"fmin\": True, \"fmax\": True}\n\n#np.random.seed(42)\nn = 1000\nx1 = np.random.uniform(1, 10, size = n)\nx2 = np.random.uniform(1, 10, size = n)\ny = 2 * np.cos(3 * np.log(4 * x1 + 5) + 6) + 7\n\nsymnet = SymNet([x1], [sympy.Symbol(\"x1\")], unary_operators, binary_operators, symmetric_binary_operators)\n#symnet = SymNet([x1, x2], sympy.symbols(\"x1 x2\"), unary_operators, binary_operators, symmetric_binary_operators)\nsymnet.add_layer()\nsymnet.add_layer()\nsymnet.fit(y)\n#print(symnet.expressions())\n#print(symnet.compute_outputs(np.random.uniform(-10, 10, size = len(symnet.a)), np.random.uniform(-10, 10, size = len(symnet.b))))\n\n\n\n\n\nI tried scipy.curve_fit instead of random and it does not work so much. Here is the code:\n\n\n\n\ndef fit(self, y, loss_func = mse_loss):\n a_s = []\n b_s = []\n losses = []\n exprs = self.expressions()\n modules = num_modules(self.un_ops, self.bin_ops)\n maxfev = 10000\n \n for expr in exprs:\n a = np.zeros(len(symnet.a))\n b = np.zeros(len(symnet.b))\n \n ab_syms = list(expr.free_symbols - set(self.symbols))\n f = sympy.lambdify(self.symbols + ab_syms, expr, modules = modules)\n func = model_func(f)\n \n params = np.zeros(len(ab_syms))\n \n try:\n params, _ = scipy.optimize.curve_fit(func, self.X, y, p0 = params, maxfev = maxfev)\n except RuntimeError as e:\n print(e)\n \n for i in range(0, len(ab_syms)):\n index = int(str(ab_syms[i])[1:])\n \n if (str(ab_syms[i])[0] == \"a\"):\n a[index] = params[i]\n else:\n b[index] = params[i]\n \n l = loss_func(func(self.X, *params), y)\n \n a_s.append(a)\n b_s.append(b)\n losses.append(l)\n \n losses = np.array(losses)\n losses = np.nan_to_num(losses, nan = -np.inf, posinf = -np.inf)\n losses = np.nan_to_num(losses, neginf = np.max(losses))\n losses = 1 - losses / np.max(losses)\n \n print(list((x, y) for x, y in sorted(zip(losses, exprs), key = lambda x: x[0], reverse = True)))\n\n\n\n\n\nAnd the associated output (cos(log) optimization failed):\n\n\n\n\n[(0.9517541462151708, a1*cos(a0*x1 + b0) + b1), (0.12313238267865056, a0*x1 + b0), (0.0, a2*log(a0*x1 + b0) + b2), (0.0, a3*cos(a1*cos(a0*x1 + b0) + b1) + b3), (0.0, a4*cos(a2*log(a0*x1 + b0) + b2) + b4), (0.0, a5*log(a1*cos(a0*x1 + b0) + b1) + b5), (0.0, a6*log(a2*log(a0*x1 + b0) + b2) + b6)]", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "P'tit Ju", "profile_url": "https://scicomp.stackexchange.com/users/54117/ptit-ju", "user_type": "registered"}, "created_at": "2025-06-15T09:46:23+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "6EC977E1-3082-4152-AE79-21C738DBF959", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6EC977E1-3082-4152-AE79-21C738DBF959/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "P'tit Ju", "profile_url": "https://scicomp.stackexchange.com/users/54117/ptit-ju", "user_type": "registered"}, "created_at": "2025-06-15T17:29:07+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "B4A3E844-33AB-4467-864F-D74942286C5A", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B4A3E844-33AB-4467-864F-D74942286C5A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "P'tit Ju", "profile_url": "https://scicomp.stackexchange.com/users/54117/ptit-ju", "user_type": "registered"}, "created_at": "2025-06-16T18:01:50+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "4E41E649-9940-470F-BD64-37949F9902D3", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/4E41E649-9940-470F-BD64-37949F9902D3/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "P'tit Ju", "profile_url": "https://scicomp.stackexchange.com/users/54117/ptit-ju", "user_type": "registered"}, "created_at": "2025-06-17T08:11:19+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "C61EE61B-3C64-482A-BAC2-3A48B78BE0AE", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C61EE61B-3C64-482A-BAC2-3A48B78BE0AE/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45114/find-necessary-operators-for-symbolic-regression", "split": "train", "split_group": "07c5c062925aee88caf5e7ca1c0a8add39323326adf026634b0bca11257a82ca", "tags": ["python", "regression", "sympy"], "thread_id": "scicomp:45114", "title": "Find necessary operators for symbolic regression"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "from scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45132, "sha256": "daf7c1f5e770a9fe6fe40e7f104e8f930491aaaf3fd354e26756660092fce0d9", "source_url": "https://scicomp.stackexchange.com/a/45132"}], "other_answers": [], "product": "code_qa", "question": "CONTEXT FOR THE QUESTION\n\n\n\n\nI'm porting animations between two video games from the same developer that use mostly the same skeleton and coordinate system. So in general, data can be ported from the source to destination exactly as it is. However, while both games use Euler angles to represent bone rotation data, the source game uses all 3 angles for every bone, but the destination game only allows for 2 angles for some of the bones while the remaining angle is always 0.\n\n\n\n\nFor now I'm specifically interested in character arms that mainly consist of the following bones: shoulder, upper arm, forearm. Shoulder uses 2 angles (pitch, roll), upper arm uses 3 angles (yaw, pitch, roll), forearm uses 2 angles (yaw, pitch). Angle order for all the bones is YXZ (yaw, pitch, roll).\n\n\n\n\nTHE QUESTION\n\n\n\n\nHaving data for all 3 angles for all 3 arm bones from the source game, how do I convert it to the destination game's format by discarding shoulder's yaw data and forearm's roll data but modifying all the remaining data to achieve the best possible visual match to the original animation?\n\n\n\n\nIs it at all possible to calculate something like this? I'm thinking it should be possible since the games share a lot of animations that look the same visually. So the developers must have had some kind of way to discard some of the data and compensate for it by modifying other values.\n\n\n\n\nI have managed to do it manually for one frame by experimenting with different values but obviously it's not viable to do if for every frame in many animations.\n\n\n\n\nFor example, in this frame the original data is (in degrees, the order is yaw, pitch, roll):\n\n\n\n\nShoulder 4.22, -11.25, -105.47\n\n\n\n\nUpper arm -11.25, -29.53, -45.00\n\n\n\n\nForearm 21.09, -30.94, -111.09\n\n\n\n\nMy modified data:\n\n\n\n\nShoulder 0.00, -11.25, -105.47\n\n\n\n\nUpper arm 49.22, -29.53, -45.00\n\n\n\n\nForearm -105.47, -98.44, 0.00\n\n\n\n\nWhat the result looks like (look at the left arm only). Of course, it won't be an exact match but something like this is close enough for me if I can automate the process.\n\n\n\n\nhttps://i.sstatic.net/XWepsVJc.gif (https://i.sstatic.net/XWepsVJc.gif)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45129", "selected_answer": {"answer_html": "What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.
\nOne strategy one could employ here is (constrained) Inverse Kinematics, though in the most typical of such use-cases you optimize just for the endpoint (i.e. the fingers of your arm example), though maybe with a "pole" you could get good results. There are such tools built into Blender, and stand alone libraries like IKPy.
\nOtherwise, you can simply treat this as a standard optimization problem and define a loss function and solve with a general optimization library, like scipy.optimize.minimize
from scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n\nwhere you can also optionally add some bounds for your angles, try different optimization methods.
\nThere is of course no guarantee that the position will be close given the constraints. I'm confused by your example, as your upper arm still uses all 3 angles.
\n", "answer_id": 45132, "answer_text": "What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.\n\n\n\n\nOne strategy one could employ here is (constrained) Inverse Kinematics, though in the most typical of such use-cases you optimize just for the endpoint (i.e. the fingers of your arm example), though maybe with a \"pole\" you could get good results. There are such tools built into Blender, and stand alone libraries like IKPy.\n\n\n\n\nOtherwise, you can simply treat this as a standard optimization problem and define a loss function and solve with a general optimization library, like scipy.optimize.minimize\n\n\n\n\nfrom scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n\n\n\n\n\nwhere you can also optionally add some bounds for your angles, try different optimization methods.\n\n\n\n\nThere is of course no guarantee that the position will be close given the constraints. I'm confused by your example, as your upper arm still uses all 3 angles.", "answer_url": "https://scicomp.stackexchange.com/a/45132", "author": "Mikael Öhman", "author_url": "https://scicomp.stackexchange.com/users/4308/mikael-%c3%96hman", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-21T13:55:43+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": 45129, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Mikael Öhman", "profile_url": "https://scicomp.stackexchange.com/users/4308/mikael-%c3%96hman", "user_type": "registered"}, "created_at": "2025-06-21T13:55:43+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "71AFAA67-7DB9-4B14-A90D-8C508E2041E0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/71AFAA67-7DB9-4B14-A90D-8C508E2041E0/view-source"}], "score": 2, "updated_at": "2025-06-21T13:55:43+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.
\nOne strategy one could employ here is (constrained) Inverse Kinematics, though in the most typical of such use-cases you optimize just for the endpoint (i.e. the fingers of your arm example), though maybe with a "pole" you could get good results. There are such tools built into Blender, and stand alone libraries like IKPy.
\nOtherwise, you can simply treat this as a standard optimization problem and define a loss function and solve with a general optimization library, like scipy.optimize.minimize
from scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n\nwhere you can also optionally add some bounds for your angles, try different optimization methods.
\nThere is of course no guarantee that the position will be close given the constraints. I'm confused by your example, as your upper arm still uses all 3 angles.
\n", "answer_id": 45132, "answer_text": "What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.\n\n\n\n\nOne strategy one could employ here is (constrained) Inverse Kinematics, though in the most typical of such use-cases you optimize just for the endpoint (i.e. the fingers of your arm example), though maybe with a \"pole\" you could get good results. There are such tools built into Blender, and stand alone libraries like IKPy.\n\n\n\n\nOtherwise, you can simply treat this as a standard optimization problem and define a loss function and solve with a general optimization library, like scipy.optimize.minimize\n\n\n\n\nfrom scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the joints\n error = np.lingalg.norm(joints, target)\n return error\n\nfree_axis = ...\nstarting_guess = full_euler_angles[free_axis]\ntarget_positions = compute_old_position(full_euler_angles, skeleton)\n\nres = minimize(\n loss,\n starting_guess,\n args=(skeleton, target_positions),\n)\n\n\n\n\n\nwhere you can also optionally add some bounds for your angles, try different optimization methods.\n\n\n\n\nThere is of course no guarantee that the position will be close given the constraints. I'm confused by your example, as your upper arm still uses all 3 angles.", "answer_url": "https://scicomp.stackexchange.com/a/45132", "author": "Mikael Öhman", "author_url": "https://scicomp.stackexchange.com/users/4308/mikael-%c3%96hman", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-06-21T13:55:43+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": 45129, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Mikael Öhman", "profile_url": "https://scicomp.stackexchange.com/users/4308/mikael-%c3%96hman", "user_type": "registered"}, "created_at": "2025-06-21T13:55:43+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "71AFAA67-7DB9-4B14-A90D-8C508E2041E0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/71AFAA67-7DB9-4B14-A90D-8C508E2041E0/view-source"}], "score": 2, "updated_at": "2025-06-21T13:55:43+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/XWepsVJc.gif"], "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": "Inspired", "question_author_url": "https://scicomp.stackexchange.com/users/54154/inspired", "question_author_user_type": "registered", "question_created_at": "2025-06-20T15:11:42+00:00", "question_html": "CONTEXT FOR THE QUESTION
\nI'm porting animations between two video games from the same developer that use mostly the same skeleton and coordinate system. So in general, data can be ported from the source to destination exactly as it is. However, while both games use Euler angles to represent bone rotation data, the source game uses all 3 angles for every bone, but the destination game only allows for 2 angles for some of the bones while the remaining angle is always 0.
\nFor now I'm specifically interested in character arms that mainly consist of the following bones: shoulder, upper arm, forearm. Shoulder uses 2 angles (pitch, roll), upper arm uses 3 angles (yaw, pitch, roll), forearm uses 2 angles (yaw, pitch). Angle order for all the bones is YXZ (yaw, pitch, roll).
\nTHE QUESTION
\nHaving data for all 3 angles for all 3 arm bones from the source game, how do I convert it to the destination game's format by discarding shoulder's yaw data and forearm's roll data but modifying all the remaining data to achieve the best possible visual match to the original animation?
\nIs it at all possible to calculate something like this? I'm thinking it should be possible since the games share a lot of animations that look the same visually. So the developers must have had some kind of way to discard some of the data and compensate for it by modifying other values.
\nI have managed to do it manually for one frame by experimenting with different values but obviously it's not viable to do if for every frame in many animations.
\nFor example, in this frame the original data is (in degrees, the order is yaw, pitch, roll):
\nShoulder 4.22, -11.25, -105.47
\nUpper arm -11.25, -29.53, -45.00
\nForearm 21.09, -30.94, -111.09
\nMy modified data:
\nShoulder 0.00, -11.25, -105.47
\nUpper arm 49.22, -29.53, -45.00
\nForearm -105.47, -98.44, 0.00
\nWhat the result looks like (look at the left arm only). Of course, it won't be an exact match but something like this is close enough for me if I can automate the process.
\nhttps://i.sstatic.net/XWepsVJc.gif
\n", "question_id": 45129, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "CONTEXT FOR THE QUESTION\n\n\n\n\nI'm porting animations between two video games from the same developer that use mostly the same skeleton and coordinate system. So in general, data can be ported from the source to destination exactly as it is. However, while both games use Euler angles to represent bone rotation data, the source game uses all 3 angles for every bone, but the destination game only allows for 2 angles for some of the bones while the remaining angle is always 0.\n\n\n\n\nFor now I'm specifically interested in character arms that mainly consist of the following bones: shoulder, upper arm, forearm. Shoulder uses 2 angles (pitch, roll), upper arm uses 3 angles (yaw, pitch, roll), forearm uses 2 angles (yaw, pitch). Angle order for all the bones is YXZ (yaw, pitch, roll).\n\n\n\n\nTHE QUESTION\n\n\n\n\nHaving data for all 3 angles for all 3 arm bones from the source game, how do I convert it to the destination game's format by discarding shoulder's yaw data and forearm's roll data but modifying all the remaining data to achieve the best possible visual match to the original animation?\n\n\n\n\nIs it at all possible to calculate something like this? I'm thinking it should be possible since the games share a lot of animations that look the same visually. So the developers must have had some kind of way to discard some of the data and compensate for it by modifying other values.\n\n\n\n\nI have managed to do it manually for one frame by experimenting with different values but obviously it's not viable to do if for every frame in many animations.\n\n\n\n\nFor example, in this frame the original data is (in degrees, the order is yaw, pitch, roll):\n\n\n\n\nShoulder 4.22, -11.25, -105.47\n\n\n\n\nUpper arm -11.25, -29.53, -45.00\n\n\n\n\nForearm 21.09, -30.94, -111.09\n\n\n\n\nMy modified data:\n\n\n\n\nShoulder 0.00, -11.25, -105.47\n\n\n\n\nUpper arm 49.22, -29.53, -45.00\n\n\n\n\nForearm -105.47, -98.44, 0.00\n\n\n\n\nWhat the result looks like (look at the left arm only). Of course, it won't be an exact match but something like this is close enough for me if I can automate the process.\n\n\n\n\nhttps://i.sstatic.net/XWepsVJc.gif (https://i.sstatic.net/XWepsVJc.gif)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Inspired", "profile_url": "https://scicomp.stackexchange.com/users/54154/inspired", "user_type": "registered"}, "created_at": "2025-06-20T15:11:42+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "05E735E6-596D-4C15-8F55-58E74FB44487", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/05E735E6-596D-4C15-8F55-58E74FB44487/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45129/euler-angle-compression", "split": "train", "split_group": "559a48cf38ddb7e085009f562735e87213495f3f4322f83579162ce0b53f8c81", "tags": ["optimization", "numerics", "matrix", "approximation"], "thread_id": "scicomp:45129", "title": "Euler Angle Compression"}} {"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": "\n\nPoincaré section obtained by conditions in the code
\n
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. Leo Stein's Poincaré sections.
\n\n\nThe code can also be improved, so if anyone has any suggestions
\n
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 "improve your Python". For the numerics:
\ng is both wrong and unnecessary; get the correct value from Scipy insteadmath module; stick to Numpyf() 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().solve_ivp produce a very slow solution. Switch to LSODA and go easy on those tolerances.plt.show() once.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\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": "\n\nPoincaré section obtained by conditions in the code
\n
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. Leo Stein's Poincaré sections.
\n\n\nThe code can also be improved, so if anyone has any suggestions
\n
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 "improve your Python". For the numerics:
\ng is both wrong and unnecessary; get the correct value from Scipy insteadmath module; stick to Numpyf() 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().solve_ivp produce a very slow solution. Switch to LSODA and go easy on those tolerances.plt.show() once.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\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": "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!
\nHere is the code: https://github.com/DJopek/chaos/blob/main/double_pendulum.py
\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\nPoincaré section obtained by conditions in the code:\n
EDIT:\nPoincaré section obtained by conditions in the code with labels
I might have found the solution, of which I'm listing the main points/observations here below:
\nOf course, if you have any further comments or observations let me know!
\n", "answer_id": 45186, "answer_text": "I might have found the solution, of which I'm listing the main points/observations here below:\n\n\n\n\n\nthe FFT/IFFT implementation in the code is consistent with the Fourier transform computed as $\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omega t}dt$ and correspondingly $f(t)=\\frac{1}{2\\pi}\\int^{+\\infty}_{-\\infty}\\tilde{F}(\\omega)e^{i\\omega t}dt$: to be sure about this I tried with the simple case of a Gaussian, but the multiplicative constants all turned out to be ok\n\n\n\n\nthe dispersion operator should be written in the form $D_{op}(\\omega)=-\\frac i2 \\beta_2 \\omega^2-\\frac i6 \\beta_3 \\omega^3$ to have the correct chirp sign at the output\n\n\n\n\nSPM should be taken into account with the factor $e^{-i\\gamma \\Delta z I}$ (once again I made sure about this by just considering the SPM term and by computing the instantaneous frequency, which we know how it should look like)\n\n\n\n\na spectral phase term $\\varphi(\\omega)=-\\kappa \\omega^2, \\kappa>0$ corresponds to a positive chirp, meaning that lower frequencies (shorter wavelengths) arrive later (just a note about the convention used, so that all signs are consistent now)\n\n\n\n\n\nOf course, if you have any further comments or observations let me know!", "answer_url": "https://scicomp.stackexchange.com/a/45186", "author": "Lorenzo Iori", "author_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-07-29T14:07:20+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": 45185, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-29T14:07:20+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "163AA634-CBFB-456A-AD54-8FFDF16B1F6A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/163AA634-CBFB-456A-AD54-8FFDF16B1F6A/view-source"}], "score": 3, "updated_at": "2025-07-29T14:07:20+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "I might have found the solution, of which I'm listing the main points/observations here below:
\nOf course, if you have any further comments or observations let me know!
\n", "answer_id": 45186, "answer_text": "I might have found the solution, of which I'm listing the main points/observations here below:\n\n\n\n\n\nthe FFT/IFFT implementation in the code is consistent with the Fourier transform computed as $\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omega t}dt$ and correspondingly $f(t)=\\frac{1}{2\\pi}\\int^{+\\infty}_{-\\infty}\\tilde{F}(\\omega)e^{i\\omega t}dt$: to be sure about this I tried with the simple case of a Gaussian, but the multiplicative constants all turned out to be ok\n\n\n\n\nthe dispersion operator should be written in the form $D_{op}(\\omega)=-\\frac i2 \\beta_2 \\omega^2-\\frac i6 \\beta_3 \\omega^3$ to have the correct chirp sign at the output\n\n\n\n\nSPM should be taken into account with the factor $e^{-i\\gamma \\Delta z I}$ (once again I made sure about this by just considering the SPM term and by computing the instantaneous frequency, which we know how it should look like)\n\n\n\n\na spectral phase term $\\varphi(\\omega)=-\\kappa \\omega^2, \\kappa>0$ corresponds to a positive chirp, meaning that lower frequencies (shorter wavelengths) arrive later (just a note about the convention used, so that all signs are consistent now)\n\n\n\n\n\nOf course, if you have any further comments or observations let me know!", "answer_url": "https://scicomp.stackexchange.com/a/45186", "author": "Lorenzo Iori", "author_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-07-29T14:07:20+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": 45185, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-29T14:07:20+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "163AA634-CBFB-456A-AD54-8FFDF16B1F6A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/163AA634-CBFB-456A-AD54-8FFDF16B1F6A/view-source"}], "score": 3, "updated_at": "2025-07-29T14:07:20+00:00"}], "domain": "computational_science", "external_links": [], "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": "Lorenzo Iori", "question_author_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "question_author_user_type": "registered", "question_created_at": "2025-07-28T09:04:03+00:00", "question_html": "I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.
\nThe issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).
\nMy question basically is if the implementation is correct or if there are any inconsistencies in the code below.
\nHere are the fundamental cells of the notebook:
\n# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n\nMoreover, when introducing GDD<0 with chirped mirrors, I use the convention
\nGDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n\nEdit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...
\n", "question_id": 45185, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in the same order of magnitude, the transform-limited duration of the pulse, the output duration of the pulse (after the non-linear path I am simulating) and the shape of the output spectrum. However, when it comes to analyzing the spectral phase at the output, the values seem completely off (for example: I expect, from the experiments, the pulse to have positive dispersion, so that a negative GDD should compensate it, but the simulations tell me the opposite.\n\n\n\n\nThe issue is that I'm having problems in picking the correct signs for the dispersion and non-linear operator: in fact the shape of the NEE depends on the Fourier transform convention adopted, and there are many factors +/-1, or even +/-i, of which I'm not sure. Also, regarding the factor gamma for SPM: I'm using the formula (omega_0 / c) * (n2 / Aeff), with Aeff = pi w^2 / 2 for a Gaussian beam, and I'm not completely sure about this either (I'm using a 1D model in which, regarding the spatial evolution of the laser pulse, I consider a Gaussian beam with a corrective M^2 factor).\n\n\n\n\nMy question basically is if the implementation is correct or if there are any inconsistencies in the code below.\n\n\n\n\nHere are the fundamental cells of the notebook:\n\n\n\n\n# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_op_fs = - 1j * 0.5 * beta2_fs * w**2 - 1j * (1/6) * beta3_fs * w**3\nAbs_op_fs = np.exp(- 0.5 * alfa_fs * dz_fs)\nD_op_air = - 1j * 0.5 * beta2_air * w**2 - 1j * (1/6) * beta3_air * w**3\n\n\n# Function to propagate pulse by distance dz in SSFM\ndef propagate_pulse(A, D_op, Abs_op, dz, eff_area, n2):\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n gamma = (w0 / c) * n2 / eff_area\n I = abs(A)**2\n # without self-steepening\n A = A * np.exp(- 1j * gamma * dz * I)\n # with self-steepening\n # A = A * np.exp(- 1j * gamma * dz * (I - 1j / w0 * (2*ifft(1j*w*fft(A))*np.conj(A)+ifft(1j*w*fft(np.conj(A)))*A)))\n \n A_w = fft(A)\n A_w = A_w * np.exp(D_op*dz/2) * Abs_op\n A = ifft(A_w)\n \n return A\n\n\n\n\n\nMoreover, when introducing GDD<0 with chirped mirrors, I use the convention\n\n\n\n\nGDD_mirror = -45e-30 # in fs^2\nE_w = fft(E)\nE_w = E_w * np.exp(- 1j * GDD_mirror / 2 * w**2)\nE = ifft(E_w)\n\n\n\n\n\nEdit: I have also included a way to change the GDD and TOD at the input pulse so to match the transform-limited and actual pulse duration, and I have already made many trials in changing the relative signs of dispersion, SPM, GDD, ...", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-28T09:04:03+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "AE3B9EFD-BDF2-4534-A36C-C0D2AB181A60", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AE3B9EFD-BDF2-4534-A36C-C0D2AB181A60/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-28T09:15:52+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "BE26735D-FCBC-47F1-A566-F341DD41F55C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BE26735D-FCBC-47F1-A566-F341DD41F55C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-28T14:07:20+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "67CC67B8-AC93-4C69-9C21-0E6BDBF43102", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/67CC67B8-AC93-4C69-9C21-0E6BDBF43102/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-28T14:32:46+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "3BBDD6A2-8D30-430A-8EAF-A458144119BA", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3BBDD6A2-8D30-430A-8EAF-A458144119BA/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lorenzo Iori", "profile_url": "https://scicomp.stackexchange.com/users/54430/lorenzo-iori", "user_type": "registered"}, "created_at": "2025-07-29T14:04:04+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "B35F7AAE-2953-45D0-AD16-97CC9997095D", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B35F7AAE-2953-45D0-AD16-97CC9997095D/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything", "split": "train", "split_group": "97b6217d7144a5979dec5a03255a67e3c5677a313d0070d017c11d0b2f5ebede", "tags": ["python", "computational-physics", "fourier-transform", "wave-propagation", "operator-splitting"], "thread_id": "scicomp:45185", "title": "Split-step Fourier method for ultrashort pulse propagation predicts everything, but not the spectral phase"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45236, "sha256": "a635a3b792dcc184f0c00b72996f91bef2185154972e2cde57e2134986e16b37", "source_url": "https://scicomp.stackexchange.com/questions/45236/panini-sticker-python-coding-problem-bug-in-my-code-somewhere"}, {"block_index": 0, "code_text": "import operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45249, "sha256": "e4d397e8c08b33a0a68cb32ae1237aaa1b2c1f7aef510dd3dbb955639a59e4c1", "source_url": "https://scicomp.stackexchange.com/a/45249"}], "other_answers": [], "product": "code_qa", "question": "I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf (http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf)\n\n\n\n\nOn page 4 I am trying to turn this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Bod2tUzu.jpg] (https://i.sstatic.net/Bod2tUzu.jpg)\n\n\n\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'\n\n\n\n\nHere is my code, where am I going wrong? Thanks.\n\n\n\n\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45236", "selected_answer": {"answer_html": "The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:
\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n930.8341950323121\n\n", "answer_id": 45249, "answer_text": "The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:\n\n\n\n\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n\n\n\n\n930.8341950323121", "answer_url": "https://scicomp.stackexchange.com/a/45249", "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-05T23:39:31+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": 45236, "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-05T23:39:31+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "75229101-2A2D-4D73-B2A6-80096500FF72", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/75229101-2A2D-4D73-B2A6-80096500FF72/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-05T23:51:10+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "11E4EE0D-659A-4B05-9326-A45AF5CAE292", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/11E4EE0D-659A-4B05-9326-A45AF5CAE292/view-source"}], "score": 3, "updated_at": "2025-10-05T23:51:10+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:
\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n930.8341950323121\n\n", "answer_id": 45249, "answer_text": "The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binomials to put this in strictly integer-numerator, integer-denominator form; reduce some of the products:\n\n\n\n\nimport operator\nfrom fractions import Fraction\nfrom functools import reduce\n\n\ndef Pi(a: int, b: int) -> int:\n return reduce(operator.mul, range(max(1, a), b+1), 1)\n\nP656 = Pi(656, 660)\n\ndef get_term(j: int) -> Fraction:\n sign = 2*(j%2) - 1\n num = Pi(j+1, 660)*P656\n p656j = Pi(656-j, 660-j)\n den = p656j*Pi(1, 655-j)*(P656 - p656j)\n return Fraction(sign*num, den)\n\n\ntotal = sum(get_term(j) for j in range(1, 661))\nprint(float(total))\n\n\n\n\n\n930.8341950323121", "answer_url": "https://scicomp.stackexchange.com/a/45249", "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-05T23:39:31+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": 45236, "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-05T23:39:31+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "75229101-2A2D-4D73-B2A6-80096500FF72", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/75229101-2A2D-4D73-B2A6-80096500FF72/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-05T23:51:10+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "11E4EE0D-659A-4B05-9326-A45AF5CAE292", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/11E4EE0D-659A-4B05-9326-A45AF5CAE292/view-source"}], "score": 3, "updated_at": "2025-10-05T23:51:10+00:00"}], "domain": "computational_science", "external_links": ["http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf", "https://i.sstatic.net/Bod2tUzu.jpg"], "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": "gregb", "question_author_url": "https://scicomp.stackexchange.com/users/54734/gregb", "question_author_user_type": "registered", "question_created_at": "2025-09-15T21:46:02+00:00", "question_html": "I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf
\nOn page 4 I am trying to turn this:
\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'
\nHere is my code, where am I going wrong? Thanks.
\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f"The result of the expression is: {result}")\n\n\n", "question_id": 45236, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf (http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf)\n\n\n\n\nOn page 4 I am trying to turn this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/Bod2tUzu.jpg] (https://i.sstatic.net/Bod2tUzu.jpg)\n\n\n\n\ninto python code but I do not get the correct answer, I have 'The result of the expression is: -1.6979783370560836e+181'\n\n\n\n\nHere is my code, where am I going wrong? Thanks.\n\n\n\n\nimport math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in range(1, n + 1):\n # Calculate the alternating sign term\n alternating_sign = (-1)**(j + 1)\n\n # Calculate the inner binomial coefficient (660 choose j)\n inner_binomial_coefficient = math.comb(n, j)\n\n # Calculate the denominator term\n # The denominator is (660 choose 5) - ((660 - j) choose 5)\n denominator = math.comb(n, k) - math.comb((n - j), k)\n \n # Calculate the term inside the summation\n term = alternating_sign * (inner_binomial_coefficient / denominator)\n \n # Add to the sum\n sum_terms += term\n \n # Calculate the final result by multiplying the outer binomial coefficient with the sum\n final_result = outer_binomial_coefficient * sum_terms\n \n return final_result\n\n# Get the result\nresult = calculate_expression()\nprint(f\"The result of the expression is: {result}\")", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "gregb", "profile_url": "https://scicomp.stackexchange.com/users/54734/gregb", "user_type": "registered"}, "created_at": "2025-09-15T21:46:02+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "67059698-6CDA-4CFD-903D-00B6A505C963", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/67059698-6CDA-4CFD-903D-00B6A505C963/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "gregb", "profile_url": "https://scicomp.stackexchange.com/users/54734/gregb", "user_type": "registered"}, "created_at": "2025-09-15T22:34:16+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "D1E2F3BD-4E46-4D76-9C39-8BDE6F9F73EC", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D1E2F3BD-4E46-4D76-9C39-8BDE6F9F73EC/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "gregb", "profile_url": "https://scicomp.stackexchange.com/users/54734/gregb", "user_type": "registered"}, "created_at": "2025-09-16T10:52:22+00:00", "raw_file": "raw/codex_api_v1/8b02bbba3a1a1a633af4866e7fea0bd6789190b52c4b8380b0538b5c670e7131_1790825346551636200_0.json", "raw_sha256": "33050439b68e1f78cef06bf4c2ce07c0ec45a5fdf656fa1a9efd04691108f5e0", "revision_guid": "9212784D-B74F-41A1-8936-363A81039240", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9212784D-B74F-41A1-8936-363A81039240/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45236/panini-sticker-python-coding-problem-bug-in-my-code-somewhere", "split": "train", "split_group": "76be7f1172db17290960f99d691aca6c9e1556b29863a36dbc96231e4c01a99d", "tags": ["python"], "thread_id": "scicomp:45236", "title": "Panini sticker python coding problem - bug in my code somewhere"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45246, "sha256": "8be5b8d21acaa3124f11278e9e1956344bcf0077a81fcffd51aa290ed3d02098", "source_url": "https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation"}, {"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45250, "sha256": "e4c81797aebb0183f7ae202e8f40018f8a8f8af8534cea97bd44225f2587483d", "source_url": "https://scicomp.stackexchange.com/a/45250"}], "other_answers": [], "product": "code_qa", "question": "I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.\n\n\n\n\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.\n\n\n\n\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.\n\n\n\n\nCould you please give me some guidance on how to solve this problem please?\n\n\n\n\nI will include my current code and figure below for reference.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n[image: Results; source: https://i.sstatic.net/pB2ZlSLf.png] (https://i.sstatic.net/pB2ZlSLf.png)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45246", "selected_answer": {"answer_html": "Dear Lutz Lehmann and community,
\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.
\nFor reference, here is the corresponding code.
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label="Velocity (m/s) at pipe center")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity at the middle of the pipe (m/s)")\nplt.title("Velocity evolution at the middle of the pipe")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f"t = {temps_selectionnes[i]:.1f} s")\nplt.xlabel("Position x (m)")\nplt.ylabel("Velocity (m/s)")\nplt.title("Velocity profile along the pipe at different times")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\nBest regards,\nRaphaël
\n", "answer_id": 45250, "answer_text": "Dear Lutz Lehmann and community,\n\n\n\n\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.\n\n\n\n\nFor reference, here is the corresponding code.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\n\n\n\n\nBest regards,\nRaphaël", "answer_url": "https://scicomp.stackexchange.com/a/45250", "author": "Ev0Cation", "author_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-07T14:19:16+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": 45246, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ev0Cation", "profile_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "user_type": "registered"}, "created_at": "2025-10-07T14:19:16+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C3CA863F-650C-4C2D-BD76-4C6863DC85E0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}], "score": 2, "updated_at": "2025-10-07T14:19:16+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Dear Lutz Lehmann and community,
\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.
\nFor reference, here is the corresponding code.
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label="Velocity (m/s) at pipe center")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity at the middle of the pipe (m/s)")\nplt.title("Velocity evolution at the middle of the pipe")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f"t = {temps_selectionnes[i]:.1f} s")\nplt.xlabel("Position x (m)")\nplt.ylabel("Velocity (m/s)")\nplt.title("Velocity profile along the pipe at different times")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\nBest regards,\nRaphaël
\n", "answer_id": 45250, "answer_text": "Dear Lutz Lehmann and community,\n\n\n\n\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.\n\n\n\n\nFor reference, here is the corresponding code.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\n\n\n\n\nBest regards,\nRaphaël", "answer_url": "https://scicomp.stackexchange.com/a/45250", "author": "Ev0Cation", "author_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-07T14:19:16+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": 45246, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ev0Cation", "profile_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "user_type": "registered"}, "created_at": "2025-10-07T14:19:16+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C3CA863F-650C-4C2D-BD76-4C6863DC85E0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}], "score": 2, "updated_at": "2025-10-07T14:19:16+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/pB2ZlSLf.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": "Ev0Cation", "question_author_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "question_author_user_type": "registered", "question_created_at": "2025-10-03T16:37:31+00:00", "question_html": "I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.
\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.
\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.
\nCould you please give me some guidance on how to solve this problem please?
\nI will include my current code and figure below for reference.
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label="Velocity (m/s)")\nplt.xlabel("Time (s)")\nplt.ylabel("Velocity")\nplt.title("Velocity evolution")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n", "question_id": 45246, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.\n\n\n\n\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.\n\n\n\n\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.\n\n\n\n\nCould you please give me some guidance on how to solve this problem please?\n\n\n\n\nI will include my current code and figure below for reference.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n[image: Results; source: https://i.sstatic.net/pB2ZlSLf.png] (https://i.sstatic.net/pB2ZlSLf.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ev0Cation", "profile_url": "https://scicomp.stackexchange.com/users/54820/ev0cation", "user_type": "registered"}, "created_at": "2025-10-03T16:37:31+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "10D2B924-C266-46E3-844E-A857A83DB2A0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/10D2B924-C266-46E3-844E-A857A83DB2A0/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation", "split": "train", "split_group": "9ebe77aea8994080981623ecf3e0fcdc2cc1b6fdd3111e5329a42df53e338196", "tags": ["python", "fluid-dynamics", "boundary-conditions", "navier-stokes"], "thread_id": "scicomp:45246", "title": "Oscillations in 1D compressible Navier–Stokes simulation"}}
{"accepted_answer": null, "code_blocks": [{"block_index": 1, "code_text": "#include The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.
\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.
\n", "answer_id": 45279, "answer_text": "The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.\n\n\n\n\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.", "answer_url": "https://scicomp.stackexchange.com/a/45279", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-11T08:18:46+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": 45261, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-11T08:18:46+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-11T08:58:34+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A797FC73-4FE4-442D-9FE9-D187BC73817D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A797FC73-4FE4-442D-9FE9-D187BC73817D/view-source"}], "score": 2, "updated_at": "2025-11-11T08:58:34+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.
\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.
\n", "answer_id": 45279, "answer_text": "The fastest way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These helper functions may then be tested with a test() function called early in your main() where you call them with some dummy data where you know the answer analytically. In my personal experience this works out faster than staring at the problem for days.\n\n\n\n\nThis builds confidence in the parts which do perform as you want them, and point you the parts which do not work as you expect.", "answer_url": "https://scicomp.stackexchange.com/a/45279", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-11T08:18:46+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": 45261, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-11T08:18:46+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A09EACDD-CC71-4D78-BFBA-7DC2D1F4F0CB/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-11T08:58:34+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A797FC73-4FE4-442D-9FE9-D187BC73817D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A797FC73-4FE4-442D-9FE9-D187BC73817D/view-source"}], "score": 2, "updated_at": "2025-11-11T08:58:34+00:00"}], "domain": "computational_science", "external_links": ["https://arxiv.org/pdf/quant-ph/9511042"], "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": "Peter", "question_author_url": "https://scicomp.stackexchange.com/users/46677/peter", "question_author_user_type": "registered", "question_created_at": "2025-10-19T14:49:08+00:00", "question_html": "I'm trying to code the path integral simulation described in this article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?
\nIn my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.
\nNow, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:
\nx_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n\nAs you can see the matrix elements match the propagator at first time step.
\nHere i my code written in C.
\n#include <stdio.h>\n#include <complex.h>\n#include <math.h>\nconst int size = 16;\nconst double m = 1.0;\nconst double dt = 0.1;\nconst double xmax = 2.0;\nconst double dx = 2*xmax/size;\nvoid mult(complex A[size][size], complex B[size][size], double x_a, double x_b, int n) {\n for (int i = 0; i < size; ++i) {\n for (int j = 0; j < size; ++j) {\n B[i][j] = 0.0+I*0.0;\n for (int k = 0; k < size; ++k) {\n B[i][j] += A[i][k]*A[k][j];\n }\n B[i][j] *= pow(dx,n+1);\n }\n }\n printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",(n+2)*dt,creal(B[0][6]),creal(csqrt(m/(2*M_PI*I*(n+2)*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*(n+2)*dt))));\n}\nint main() {\n complex A[size][size];\n complex B[size][size];\n double x_a = 0;\n double x_b = 0;\n for (int i = 0; i < size; ++i) {\n double xi = -xmax+i*dx;\n for (int j = 0; j < size; ++j) {\n double xj = -xmax+j*dx;\n A[i][j] = cpow(m/(2*M_PI*I*dt),1.0/2.0)*cexp(I*dt*m*pow((xj-xi)/dt,2)/2);\n if (i == 0 && j == 6) {\n x_a = xi;\n x_b = xj;\n printf("x_a = %f, x_b = %f\\n",xi,xj);\n }\n }\n }\n printf("step = %f, K(x_a,x_b,t) = %f, K(x_a,x_b,t)_exact = %f\\n",1*dt,creal(A[0][6]),creal(csqrt(m/(2*M_PI*I*1*dt))*cexp(-m*pow(x_a-x_b,2)/(2*I*1*dt))));\n for (int n = 0; n < 4; ++n) {\n if (n % 2 == 0) {\n mult(A,B,x_a,x_b,n);\n }\n else {\n mult(B,A,x_a,x_b,n);\n }\n }\n}\n\n\n", "question_id": 45261, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I'm trying to code the path integral simulation described in this (https://arxiv.org/pdf/quant-ph/9511042) article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?\n\n\n\n\nIn my code, I first construct the short-time propagator matrix as described in equation 4, using a Lagrangian for a free particle\n$$L(\\dot{x})=\\frac{m}{2}\\dot{x}^2$$\n, then I raise the matrix to the nth power by multiplying them by themselves as described in equation 5.\n\n\n\n\nNow, at each time step i print matrix elements and i expect this sequence of numbers to match a free particle propagator\n$$K(x,x',t)=\\sqrt\\frac{m}{2\\pi{i}t}e^{-\\frac{m(x-x')^2}{2it}}$$\n, but i get following output:\n\n\n\n\nx_a = -2.000000, x_b = -0.500000\nstep = 0.100000, K(x_a,x_b,t) = -0.638822, K(x_a,x_b,t)_exact = -0.638822\nstep = 0.200000, K(x_a,x_b,t) = -0.136152, K(x_a,x_b,t)_exact = 0.113176\nstep = 0.300000, K(x_a,x_b,t) = 0.671848, K(x_a,x_b,t)_exact = -0.716987\nstep = 0.400000, K(x_a,x_b,t) = 0.193327, K(x_a,x_b,t)_exact = -0.277945\nstep = 0.500000, K(x_a,x_b,t) = -0.000890, K(x_a,x_b,t)_exact = 0.059801\n\n\n\n\n\n\nAs you can see the matrix elements match the propagator at first time step.\n\n\n\n\nHere i my code written in C.\n\n\n\n\n#include The issue turned out to be a normalisation mismatch between how the multipoles were defined and how the potential and translations were evaluated.
\nIn the original code, the factor
\n$$\n\\frac{4\\pi}{2n+1}\n$$
\nwas included entirely in the multipole moments.
\nHowever, SciPy’s sph_harm already uses fully normalised spherical harmonics, so this extra factor caused inconsistent scaling between the P2M, M2M, and evaluation steps — which only became apparent at higher orders.
The fix is to split the factor symmetrically:
\nmultiply both the P2M and the potential evaluation and the M2M by
$$\n\\sqrt{\\frac{4\\pi}{2n+1}} .\n$$
\nWith this consistent normalisation, the translated multipoles now reproduce the direct moments even for high orders and small translation distances.
\nBelow are the corrected routines for reference (using SciPy’s sph_harm_y):
def P_moment(M, x_tgt):\n r = x_tgt[...,0]; theta = x_tgt[...,1]; phi = x_tgt[...,2]\n P = np.zeros(x_tgt.shape[0], dtype=np.complex128)\n p = int(np.sqrt(M.shape[0])) - 1\n idx = 0\n for n in range(p+1):\n c = np.sqrt(4.0 * np.pi / (2*n + 1))\n rinv = r**(-(n+1))\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n P += M[idx] * rinv * Y * c\n idx += 1\n return np.real(P)\n\n\ndef P2M(X, q, p=4):\n r = X[...,0]; theta = X[...,1]; phi = X[...,2]\n M = np.zeros(((p+1)**2,), dtype=np.complex128)\n idx = 0\n for n in range(p+1):\n c = np.sqrt(4.0 * np.pi / (2*n + 1))\n rpow = r**n if n > 0 else np.ones_like(r)\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n M[idx] = c * np.sum(q * rpow * np.conj(Y))\n idx += 1\n return M\n\n\ndef M2M(M, x0, x1):\n """\n Translate multipole moments M about x0 to moments about x1.\n M is flattened with index n^2 + n + m order.\n """\n p = int(np.sqrt(M.shape[0])) - 1\n x_diff = x0 - x1\n rho, alpha, beta = cart_to_sphe(x_diff.reshape(1,3)).flatten()\n M_trans = np.zeros_like(M)\n for j in range(p+1):\n for k in range(-j, j+1):\n acc = 0.0 + 0.0j\n for n in range(0, j+1):\n jn = j - n\n norm_factor = np.sqrt(4.0 * np.pi / (2*n + 1))\n for m in range(-n, n+1):\n km = k - m\n if abs(km) > jn:\n continue\n O = M[lm_index(jn, km)]\n phase = 1j**(abs(k) - abs(m) - abs(km))\n coeff = (phase * A(jn, km) * A(n, m) / A(j, k)) \\\n * (rho**n) * norm_factor\n acc += O * coeff * np.conj(sph_harm_y(n, m, alpha, beta))\n M_trans[lm_index(j, k)] = acc\n return M_trans\n\nThis ensures consistent spherical-harmonic scaling across all steps, and the M2M translation now matches the directly recomputed moments to machine precision for small shifts.
\nEDIT:\nAlternatively, you may want to rewrite the spherical harmonics calculation exactly as in the original article. When moving on to the M2L and L2L, I ran into more trouble with normalisation. Replacing the scipy.special.sphe_harm (or sphe_harm_y) function call with the below code snippet should avoid these normalisation issues.
\nfrom scipy.special import lpmv\nfrom math import factorial as fac\n\ndef sph_harm_dir(n, m, theta, phi):\n Pnm = lpmv(abs(m), n, np.cos(theta))\n sqrt_fac = np.sqrt( fac(n - abs(m)) / fac(n + abs(m)) )\n return sqrt_fac * Pnm * np.exp(1j * m * phi)\n\n", "answer_id": 45268, "answer_text": "The issue turned out to be a normalisation mismatch between how the multipoles were defined and how the potential and translations were evaluated.\n\n\n\n\nIn the original code, the factor\n\n$$\n\\frac{4\\pi}{2n+1}\n$$\n\nwas included entirely in the multipole moments.\n\nHowever, SciPy’s sph_harm already uses fully normalised spherical harmonics, so this extra factor caused inconsistent scaling between the P2M, M2M, and evaluation steps — which only became apparent at higher orders.\n\n\n\n\nThe fix is to split the factor symmetrically:\n\nmultiply both the P2M and the potential evaluation and the M2M by\n\n\n\n\n$$\n\\sqrt{\\frac{4\\pi}{2n+1}} .\n$$\n\n\n\n\nWith this consistent normalisation, the translated multipoles now reproduce the direct moments even for high orders and small translation distances.\n\n\n\n\nBelow are the corrected routines for reference (using SciPy’s sph_harm_y):\n\n\n\n\ndef P_moment(M, x_tgt):\n r = x_tgt[...,0]; theta = x_tgt[...,1]; phi = x_tgt[...,2]\n P = np.zeros(x_tgt.shape[0], dtype=np.complex128)\n p = int(np.sqrt(M.shape[0])) - 1\n idx = 0\n for n in range(p+1):\n c = np.sqrt(4.0 * np.pi / (2*n + 1))\n rinv = r**(-(n+1))\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n P += M[idx] * rinv * Y * c\n idx += 1\n return np.real(P)\n\n\ndef P2M(X, q, p=4):\n r = X[...,0]; theta = X[...,1]; phi = X[...,2]\n M = np.zeros(((p+1)**2,), dtype=np.complex128)\n idx = 0\n for n in range(p+1):\n c = np.sqrt(4.0 * np.pi / (2*n + 1))\n rpow = r**n if n > 0 else np.ones_like(r)\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n M[idx] = c * np.sum(q * rpow * np.conj(Y))\n idx += 1\n return M\n\n\ndef M2M(M, x0, x1):\n \"\"\"\n Translate multipole moments M about x0 to moments about x1.\n M is flattened with index n^2 + n + m order.\n \"\"\"\n p = int(np.sqrt(M.shape[0])) - 1\n x_diff = x0 - x1\n rho, alpha, beta = cart_to_sphe(x_diff.reshape(1,3)).flatten()\n M_trans = np.zeros_like(M)\n for j in range(p+1):\n for k in range(-j, j+1):\n acc = 0.0 + 0.0j\n for n in range(0, j+1):\n jn = j - n\n norm_factor = np.sqrt(4.0 * np.pi / (2*n + 1))\n for m in range(-n, n+1):\n km = k - m\n if abs(km) > jn:\n continue\n O = M[lm_index(jn, km)]\n phase = 1j**(abs(k) - abs(m) - abs(km))\n coeff = (phase * A(jn, km) * A(n, m) / A(j, k)) \\\n * (rho**n) * norm_factor\n acc += O * coeff * np.conj(sph_harm_y(n, m, alpha, beta))\n M_trans[lm_index(j, k)] = acc\n return M_trans\n\n\n\n\n\nThis ensures consistent spherical-harmonic scaling across all steps, and the M2M translation now matches the directly recomputed moments to machine precision for small shifts.\n\n\n\n\nEDIT:\nAlternatively, you may want to rewrite the spherical harmonics calculation exactly as in the original article. When moving on to the M2L and L2L, I ran into more trouble with normalisation. Replacing the scipy.special.sphe_harm (or sphe_harm_y) function call with the below code snippet should avoid these normalisation issues.\n\n\n\n\nfrom scipy.special import lpmv\nfrom math import factorial as fac\n\ndef sph_harm_dir(n, m, theta, phi):\n Pnm = lpmv(abs(m), n, np.cos(theta))\n sqrt_fac = np.sqrt( fac(n - abs(m)) / fac(n + abs(m)) )\n return sqrt_fac * Pnm * np.exp(1j * m * phi)", "answer_url": "https://scicomp.stackexchange.com/a/45268", "author": "Michael Haahr", "author_url": "https://scicomp.stackexchange.com/users/54898/michael-haahr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-27T09:17:11+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": 45262, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael Haahr", "profile_url": "https://scicomp.stackexchange.com/users/54898/michael-haahr", "user_type": "registered"}, "created_at": "2025-10-27T09:17:11+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "69F370F6-3286-4D6F-A98D-EF7457BE75B8", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/69F370F6-3286-4D6F-A98D-EF7457BE75B8/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael Haahr", "profile_url": "https://scicomp.stackexchange.com/users/54898/michael-haahr", "user_type": "registered"}, "created_at": "2025-10-29T18:20:30+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A2C28833-E8F4-4B97-8D1E-62704775D3DF", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A2C28833-E8F4-4B97-8D1E-62704775D3DF/view-source"}], "score": 4, "updated_at": "2025-10-29T18:20:30+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The issue turned out to be a normalisation mismatch between how the multipoles were defined and how the potential and translations were evaluated.
\nIn the original code, the factor
\n$$\n\\frac{4\\pi}{2n+1}\n$$
\nwas included entirely in the multipole moments.
\nHowever, SciPy’s sph_harm already uses fully normalised spherical harmonics, so this extra factor caused inconsistent scaling between the P2M, M2M, and evaluation steps — which only became apparent at higher orders.
The fix is to split the factor symmetrically:
\nmultiply both the P2M and the potential evaluation and the M2M by
$$\n\\sqrt{\\frac{4\\pi}{2n+1}} .\n$$
\nWith this consistent normalisation, the translated multipoles now reproduce the direct moments even for high orders and small translation distances.
\nBelow are the corrected routines for reference (using SciPy’s sph_harm_y):
def P_moment(M, x_tgt):\n r = x_tgt[...,0]; theta = x_tgt[...,1]; phi = x_tgt[...,2]\n P = np.zeros(x_tgt.shape[0], dtype=np.complex128)\n p = int(np.sqrt(M.shape[0])) - 1\n idx = 0\n for n in range(p+1):\n c = np.sqrt(4.0 * np.pi / (2*n + 1))\n rinv = r**(-(n+1))\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n P += M[idx] * rinv * Y * c\n idx += 1\n return np.real(P)\n\n\ndef P2M(X, q, p=4):\n r = X[...,0]; theta = X[...,1]; phi = X[...,2]\n M = np.zeros(((p+1)**2,), dtype=np.complex128)\n idx = 0\n for n in range(p+1):\n c = np.sqrt(4.0 * np.pi / (2*n + 1))\n rpow = r**n if n > 0 else np.ones_like(r)\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n M[idx] = c * np.sum(q * rpow * np.conj(Y))\n idx += 1\n return M\n\n\ndef M2M(M, x0, x1):\n """\n Translate multipole moments M about x0 to moments about x1.\n M is flattened with index n^2 + n + m order.\n """\n p = int(np.sqrt(M.shape[0])) - 1\n x_diff = x0 - x1\n rho, alpha, beta = cart_to_sphe(x_diff.reshape(1,3)).flatten()\n M_trans = np.zeros_like(M)\n for j in range(p+1):\n for k in range(-j, j+1):\n acc = 0.0 + 0.0j\n for n in range(0, j+1):\n jn = j - n\n norm_factor = np.sqrt(4.0 * np.pi / (2*n + 1))\n for m in range(-n, n+1):\n km = k - m\n if abs(km) > jn:\n continue\n O = M[lm_index(jn, km)]\n phase = 1j**(abs(k) - abs(m) - abs(km))\n coeff = (phase * A(jn, km) * A(n, m) / A(j, k)) \\\n * (rho**n) * norm_factor\n acc += O * coeff * np.conj(sph_harm_y(n, m, alpha, beta))\n M_trans[lm_index(j, k)] = acc\n return M_trans\n\nThis ensures consistent spherical-harmonic scaling across all steps, and the M2M translation now matches the directly recomputed moments to machine precision for small shifts.
\nEDIT:\nAlternatively, you may want to rewrite the spherical harmonics calculation exactly as in the original article. When moving on to the M2L and L2L, I ran into more trouble with normalisation. Replacing the scipy.special.sphe_harm (or sphe_harm_y) function call with the below code snippet should avoid these normalisation issues.
\nfrom scipy.special import lpmv\nfrom math import factorial as fac\n\ndef sph_harm_dir(n, m, theta, phi):\n Pnm = lpmv(abs(m), n, np.cos(theta))\n sqrt_fac = np.sqrt( fac(n - abs(m)) / fac(n + abs(m)) )\n return sqrt_fac * Pnm * np.exp(1j * m * phi)\n\n", "answer_id": 45268, "answer_text": "The issue turned out to be a normalisation mismatch between how the multipoles were defined and how the potential and translations were evaluated.\n\n\n\n\nIn the original code, the factor\n\n$$\n\\frac{4\\pi}{2n+1}\n$$\n\nwas included entirely in the multipole moments.\n\nHowever, SciPy’s sph_harm already uses fully normalised spherical harmonics, so this extra factor caused inconsistent scaling between the P2M, M2M, and evaluation steps — which only became apparent at higher orders.\n\n\n\n\nThe fix is to split the factor symmetrically:\n\nmultiply both the P2M and the potential evaluation and the M2M by\n\n\n\n\n$$\n\\sqrt{\\frac{4\\pi}{2n+1}} .\n$$\n\n\n\n\nWith this consistent normalisation, the translated multipoles now reproduce the direct moments even for high orders and small translation distances.\n\n\n\n\nBelow are the corrected routines for reference (using SciPy’s sph_harm_y):\n\n\n\n\ndef P_moment(M, x_tgt):\n r = x_tgt[...,0]; theta = x_tgt[...,1]; phi = x_tgt[...,2]\n P = np.zeros(x_tgt.shape[0], dtype=np.complex128)\n p = int(np.sqrt(M.shape[0])) - 1\n idx = 0\n for n in range(p+1):\n c = np.sqrt(4.0 * np.pi / (2*n + 1))\n rinv = r**(-(n+1))\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n P += M[idx] * rinv * Y * c\n idx += 1\n return np.real(P)\n\n\ndef P2M(X, q, p=4):\n r = X[...,0]; theta = X[...,1]; phi = X[...,2]\n M = np.zeros(((p+1)**2,), dtype=np.complex128)\n idx = 0\n for n in range(p+1):\n c = np.sqrt(4.0 * np.pi / (2*n + 1))\n rpow = r**n if n > 0 else np.ones_like(r)\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n M[idx] = c * np.sum(q * rpow * np.conj(Y))\n idx += 1\n return M\n\n\ndef M2M(M, x0, x1):\n \"\"\"\n Translate multipole moments M about x0 to moments about x1.\n M is flattened with index n^2 + n + m order.\n \"\"\"\n p = int(np.sqrt(M.shape[0])) - 1\n x_diff = x0 - x1\n rho, alpha, beta = cart_to_sphe(x_diff.reshape(1,3)).flatten()\n M_trans = np.zeros_like(M)\n for j in range(p+1):\n for k in range(-j, j+1):\n acc = 0.0 + 0.0j\n for n in range(0, j+1):\n jn = j - n\n norm_factor = np.sqrt(4.0 * np.pi / (2*n + 1))\n for m in range(-n, n+1):\n km = k - m\n if abs(km) > jn:\n continue\n O = M[lm_index(jn, km)]\n phase = 1j**(abs(k) - abs(m) - abs(km))\n coeff = (phase * A(jn, km) * A(n, m) / A(j, k)) \\\n * (rho**n) * norm_factor\n acc += O * coeff * np.conj(sph_harm_y(n, m, alpha, beta))\n M_trans[lm_index(j, k)] = acc\n return M_trans\n\n\n\n\n\nThis ensures consistent spherical-harmonic scaling across all steps, and the M2M translation now matches the directly recomputed moments to machine precision for small shifts.\n\n\n\n\nEDIT:\nAlternatively, you may want to rewrite the spherical harmonics calculation exactly as in the original article. When moving on to the M2L and L2L, I ran into more trouble with normalisation. Replacing the scipy.special.sphe_harm (or sphe_harm_y) function call with the below code snippet should avoid these normalisation issues.\n\n\n\n\nfrom scipy.special import lpmv\nfrom math import factorial as fac\n\ndef sph_harm_dir(n, m, theta, phi):\n Pnm = lpmv(abs(m), n, np.cos(theta))\n sqrt_fac = np.sqrt( fac(n - abs(m)) / fac(n + abs(m)) )\n return sqrt_fac * Pnm * np.exp(1j * m * phi)", "answer_url": "https://scicomp.stackexchange.com/a/45268", "author": "Michael Haahr", "author_url": "https://scicomp.stackexchange.com/users/54898/michael-haahr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-27T09:17:11+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": 45262, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael Haahr", "profile_url": "https://scicomp.stackexchange.com/users/54898/michael-haahr", "user_type": "registered"}, "created_at": "2025-10-27T09:17:11+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "69F370F6-3286-4D6F-A98D-EF7457BE75B8", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/69F370F6-3286-4D6F-A98D-EF7457BE75B8/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael Haahr", "profile_url": "https://scicomp.stackexchange.com/users/54898/michael-haahr", "user_type": "registered"}, "created_at": "2025-10-29T18:20:30+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "A2C28833-E8F4-4B97-8D1E-62704775D3DF", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A2C28833-E8F4-4B97-8D1E-62704775D3DF/view-source"}], "score": 4, "updated_at": "2025-10-29T18:20:30+00:00"}], "domain": "computational_science", "external_links": ["https://home.cscamm.umd.edu/programs/fam04/dg_lecture6.pdf"], "medical_sensitive": true, "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": "Michael Haahr", "question_author_url": "https://scicomp.stackexchange.com/users/54898/michael-haahr", "question_author_user_type": "registered", "question_created_at": "2025-10-24T12:50:37+00:00", "question_html": "I’m implementing a 3D Laplace Fast Multipole Method in Python and I’m trying to validate my P2M, potential evaluation, and M2M steps against direct summation. P2M + evaluation agree with direct potential within the expected truncation error, but M2M shows a discrepancy at higher orders. A prefactor $ \\sqrt{4\\pi}/(2n+1) $ seems to “fix” $ n=0,1 $ but not $ n\\ge2 $. I cannot justify this factor from the derivation.
\nI’d really appreciate help clarifying:
\n$$\nG(\\mathbf{x},\\mathbf{y}) = \\frac{1}{\\lVert \\mathbf{x} - \\mathbf{y} \\rVert}\n$$
\nsph_harm_y(n, m, theta, phi) withdef cart_to_sphe(X, eps=1e-12):\n """\n Convert Cartesian coordinates to spherical coordinates.\n Input:\n X : array of shape (N, 3) representing N points in Cartesian coordinates (x, y, z)\n eps : small threshold to avoid division by zero\n Output:\n res : array of shape (N, 3) representing N points in spherical coordinates (r, theta, phi)\n r is the radial distance\n theta is the polar angle\n phi is the azimuthal angle\n """\n #-------- view of input array ----------------\n x = X[..., 0]\n y = X[..., 1]\n z = X[..., 2]\n #--------------------------------------------\n #-------- allocate output array -------------\n res = np.empty_like(X)\n #--------------------------------------------\n #---------- compute spherical coordinates -------------\n res[:,0] = np.sqrt(x**2 + y**2 + z**2) # radial distance\n res[:,1] = np.arccos( z / res[:,0] ) # polar angle\n res[:,2] = np.mod(np.arctan2( y, x ), 2*np.pi) # azimuthal angle\n #res[:,2] = np.sign(y) * np.arccos(x / np.sqrt(x**2 + y**2)) # azimuthal angle\n #------------------------------------------------------\n #------- handle small r case to avoid NaNs ----------------\n mask = res[:,0] < eps\n res[mask,1] = 0.0 # define polar angle at origin to be 0\n res[mask,2] = 0.0 # define azimuthal angle at origin to be 0\n #----------------------------------------------------------\n return res\n\ndef generate_points_in_sphere(n_points, radius, r_min=0.0, center=None, spherical=False, eps=1e-12):\n """\n Generate random points uniformly distributed inside a sphere (or shell).\n\n Parameters\n ----------\n n_points : int\n Number of points to generate.\n radius : float\n Outer radius of the sphere (> 0).\n r_min : float, optional\n Inner radius (>= 0). Use r_min > 0 for a hollow shell. Default: 0.0\n center : array-like of shape (3,), optional\n Cartesian coordinates of the sphere centre. If None, assume origin.\n Only used when returning Cartesian coordinates.\n spherical : bool, optional\n If True, return spherical coordinates (r, theta, phi) about the sphere's centre.\n If False, return Cartesian (x, y, z).\n eps : float, optional\n Small guard for numerical stability.\n\n Returns\n -------\n points : (n_points, 3) ndarray\n If spherical=False: Cartesian points (x, y, z).\n If spherical=True : Spherical points (r, theta, phi) relative to the sphere centre.\n """\n if radius <= 0:\n raise ValueError("radius must be > 0")\n if r_min < 0 or r_min > radius:\n raise ValueError("r_min must satisfy 0 <= r_min <= radius")\n\n r = np.cbrt(np.random.uniform( low=r_min**3, high=radius**3, size=n_points))\n theta = np.arccos( np.random.uniform(-1,1,n_points) )\n phi = np.random.uniform(0,2*np.pi,n_points)\n\n #------------ if spherical and center is None, return directly -------------\n if spherical and center is None:\n pts = np.column_stack((r, theta, phi))\n #---------------------------------------------------------------------------\n #------------ otherwise convert to cartesian --------------------\n else:\n pts_cart = sphe_to_cart( np.column_stack((r, theta, phi)), eps=eps )\n if spherical:\n pts_cart += np.asarray(center).reshape(1,3)\n pts = cart_to_sphe(pts_cart, eps=eps)\n else:\n if center is not None:\n pts_cart += np.asarray(center).reshape(1,3)\n pts = pts_cart\n return pts\n\n\ndef P2M(X_sphe, q, p=4):\n # X_sphe: (N,3) with columns [r, theta(azimuth), phi(polar)]\n r = X_sphe[:, 0]; theta = X_sphe[:, 1]; phi = X_sphe[:, 2]\n M = np.zeros(((p+1)**2,), dtype=np.complex128)\n idx = 0\n for n in range(p+1):\n c = 4.0 * np.pi / (2*n + 1) # from Laplace addition theorem\n rpow = r**n if n > 0 else np.ones_like(r)\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n M[idx] = c * np.sum(q * rpow * np.conj(Y))\n idx += 1\n return M\n\ndef P_moment(M, x_tgt_sphe):\n r = x_tgt_sphe[:, 0]; theta = x_tgt_sphe[:, 1]; phi = x_tgt_sphe[:, 2]\n P = np.zeros_like(r, dtype=np.complex128)\n p = int(np.sqrt(M.shape[0])) - 1\n idx = 0\n for n in range(p+1):\n rinv = r**(-(n+1))\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n P += M[idx] * rinv * Y\n idx += 1\n return np.real(P)\n\ndef P_direct_cart_vec(X_cart, q, x_tgt_cart, eps=1e-10):\n diff = x_tgt_cart[:, None, :] - X_cart[None, :, :]\n r = np.linalg.norm(diff, axis=2)\n if eps != 0.0:\n r = np.sqrt(r*r + eps*eps)\n return (q / r).sum(axis=1)\n\nP2M + evaluation matches P_direct_cart_vec within truncation error, so I’m reasonably confident these two pieces are consistent.
I attempt to translate moments about $ \\mathbf{x}_0 $ to moments about $ \\mathbf{x}_1 $.
\nLet $ (\\rho, \\alpha, \\beta) $ be the spherical coordinates of $ \\mathbf{d} = \\mathbf{x}_0 - \\mathbf{x}_1 $.
def lm_index(n, m): return n*n + n + m\n\ndef A(n, m):\n # A_n^m = (-1)^n / sqrt((n-m)!(n+m)!)\n return ((-1)**n) / np.sqrt(fac(n-m) * fac(n+m))\n\ndef M2M(M, x0, x1):\n p = int(np.sqrt(M.shape[0])) - 1\n d = x0 - x1\n rho, alpha, beta = cart_to_sphe(d.reshape(1,3)).flatten()\n M_out = np.zeros_like(M)\n for j in range(p+1):\n for k in range(-j, j+1):\n acc = 0.0 + 0.0j\n for n in range(0, j+1):\n jn = j - n\n # --- the questionable factor ---\n norm_factor = np.sqrt(4.0 * np.pi) / (2*n + 1)\n for m in range(-n, n+1):\n km = k - m\n if abs(km) > jn:\n continue\n O = M[lm_index(jn, km)]\n phase = 1j**(abs(k) - abs(m) - abs(km))\n coeff = (phase * A(jn, km) * A(n, m) / A(j, k)) * (rho**n) * norm_factor\n acc += O * coeff * np.conj(sph_harm_y(n, m, alpha, beta))\n M_out[lm_index(j, k)] = acc\n return M_out\n\nWith this norm_factor = sqrt(4π)/(2n+1), the translated $ n=0 $ and $ n=1 $ moments match the reference (computed by P2M around $ x_1 $).
\nHowever, $ n \\ge 2 $ moments diverge even for small $ |\\mathbf{x}_0 - \\mathbf{x}_1| $.
I’ve derived this step from Beatson & Greengard (1997, A short course on fast multipole methods) and cross-checked slides such as this lecture note.
\nI also found similar unresolved questions:
Pointers to a fully worked M2M translation using the same normalisation as SciPy would be ideal.
\nReferences consulted:
\nBeatson & Greengard (1997) – A short course on fast multipole methods
\nDan Gremse’s CSCAMM FMM lecture notes (linked above)
\nThe two related Q&As linked above
Happy to provide additional diagnostic data (per-degree matrices, Gaunt coefficients, etc.).
\nMy goal is to make the M2M step numerically consistent with the P2M/evaluation pair under the same spherical-harmonic conventions.
\nnp.random.seed(42)\nN = 10000 # number of points\nq = np.ones(N) # source strengths all positive 1\nsource_area_size = 1.0\np = 4\n#--------- generate a number of source points inside box ----------\nLLC = np.array([ -1.0, -1.0, -1.0 ]) * source_area_size # Lower Left Corner\nURC = np.array([ 1.0, 1.0, 1.0 ]) * source_area_size # Upper Right Corner\nX = np.random.rand(N, 3) # uniform in [0,1)\nX = LLC + (URC - LLC) * X # uniform in [LLC, URC]\nx_polar = cart_to_sphe(X)\n#------------------------------------------------------------------------\n\nx1 = np.array([0.0,0.0, 0.0])\nM2M_dist = 0.5 * source_area_size\nx0 = np.array([1.0,1.0,1.0]) * M2M_dist\n\n\n#--------- define target point outside box ----------\nNtgt = N\ndist = 10 * source_area_size\ncenter = np.array([1.0, 1.0, 1.0]) * dist\ncenter_sphe = cart_to_sphe(center.reshape(1,3))\n\ncenter_rel_x0 = center - x0\ncenter_rel_x0_sphe = cart_to_sphe(center_rel_x0.reshape(1,3))\n#------------------------------------------------------\n\nP_direct = P_direct_cart_vec(X, q, np.array([center]))[0]\n\nM_origin = P2M(x_polar, q, p=p)\n\nx_rel = X - x0\nx_rel_polar = cart_to_sphe(x_rel)\nM_x0 = P2M(x_rel_polar, q, p=p)\nM_tran = M2M(M_x0, x0, x1)\n\nP_mom_ori = P_moment(M_origin, center_sphe)[0]\nP_mom_x0 = P_moment(M_x0, center_rel_x0_sphe)[0]\nP_mom_tran = P_moment(M_tran, center_sphe )[0]\n\nprint("Direct eval: ", P_direct)\nprint("Moment at origin: ", P_mom_ori)\nprint("Moment at x0 ", P_mom_x0)\nprint("Moment at x0 then M2M: ", P_mom_tran)\n\nprints:
\nDirect eval: 577.3045267385877\nMoment at origin: 577.3045187005426\nMoment at x0 577.305073670786\nMoment at x0 then M2M: 578.038378949856\n\nwhen normalisation factor is included in M2M and:
\nMoment at x0 then M2M: 179.81604418879266\n\nwithout
\n", "question_id": 45262, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I’m implementing a 3D Laplace Fast Multipole Method in Python and I’m trying to validate my P2M, potential evaluation, and M2M steps against direct summation. P2M + evaluation agree with direct potential within the expected truncation error, but M2M shows a discrepancy at higher orders. A prefactor $ \\sqrt{4\\pi}/(2n+1) $ seems to “fix” $ n=0,1 $ but not $ n\\ge2 $. I cannot justify this factor from the derivation.\n\n\n\n\nI’d really appreciate help clarifying:\n\n\n\n\n\nExactly where this factor comes from (if at all), and\n\n\n\n\nWhy it fails for higher orders in my implementation.\n\n\n\n\n\n\n\n\nConventions\n\n\n\n\n\nKernel / Green’s function:\n\n\n\n\n\n$$\nG(\\mathbf{x},\\mathbf{y}) = \\frac{1}{\\lVert \\mathbf{x} - \\mathbf{y} \\rVert}\n$$\n\n\n\n\n\nSpherical harmonics: SciPy’s sph_harm_y(n, m, theta, phi) with\n\ntheta = polar $(0, 2\\pi]$, phi = azimuth $[0, \\pi]$;\n\nCondon–Shortley phase included.\n\n\n\n\nFlattened index: $ lm_{index}(n,m) = n^2 + n + m $ (degree-major ordering).\n\n\n\n\nMultipole coefficients $ M_n^m $ use the fully normalised $ Y_n^m $ (same normalisation as SciPy).\n\n\n\n\n\n\n\n\nHelper functions\n\n\n\n\ndef cart_to_sphe(X, eps=1e-12):\n \"\"\"\n Convert Cartesian coordinates to spherical coordinates.\n Input:\n X : array of shape (N, 3) representing N points in Cartesian coordinates (x, y, z)\n eps : small threshold to avoid division by zero\n Output:\n res : array of shape (N, 3) representing N points in spherical coordinates (r, theta, phi)\n r is the radial distance\n theta is the polar angle\n phi is the azimuthal angle\n \"\"\"\n #-------- view of input array ----------------\n x = X[..., 0]\n y = X[..., 1]\n z = X[..., 2]\n #--------------------------------------------\n #-------- allocate output array -------------\n res = np.empty_like(X)\n #--------------------------------------------\n #---------- compute spherical coordinates -------------\n res[:,0] = np.sqrt(x**2 + y**2 + z**2) # radial distance\n res[:,1] = np.arccos( z / res[:,0] ) # polar angle\n res[:,2] = np.mod(np.arctan2( y, x ), 2*np.pi) # azimuthal angle\n #res[:,2] = np.sign(y) * np.arccos(x / np.sqrt(x**2 + y**2)) # azimuthal angle\n #------------------------------------------------------\n #------- handle small r case to avoid NaNs ----------------\n mask = res[:,0] < eps\n res[mask,1] = 0.0 # define polar angle at origin to be 0\n res[mask,2] = 0.0 # define azimuthal angle at origin to be 0\n #----------------------------------------------------------\n return res\n\ndef generate_points_in_sphere(n_points, radius, r_min=0.0, center=None, spherical=False, eps=1e-12):\n \"\"\"\n Generate random points uniformly distributed inside a sphere (or shell).\n\n Parameters\n ----------\n n_points : int\n Number of points to generate.\n radius : float\n Outer radius of the sphere (> 0).\n r_min : float, optional\n Inner radius (>= 0). Use r_min > 0 for a hollow shell. Default: 0.0\n center : array-like of shape (3,), optional\n Cartesian coordinates of the sphere centre. If None, assume origin.\n Only used when returning Cartesian coordinates.\n spherical : bool, optional\n If True, return spherical coordinates (r, theta, phi) about the sphere's centre.\n If False, return Cartesian (x, y, z).\n eps : float, optional\n Small guard for numerical stability.\n\n Returns\n -------\n points : (n_points, 3) ndarray\n If spherical=False: Cartesian points (x, y, z).\n If spherical=True : Spherical points (r, theta, phi) relative to the sphere centre.\n \"\"\"\n if radius <= 0:\n raise ValueError(\"radius must be > 0\")\n if r_min < 0 or r_min > radius:\n raise ValueError(\"r_min must satisfy 0 <= r_min <= radius\")\n\n r = np.cbrt(np.random.uniform( low=r_min**3, high=radius**3, size=n_points))\n theta = np.arccos( np.random.uniform(-1,1,n_points) )\n phi = np.random.uniform(0,2*np.pi,n_points)\n\n #------------ if spherical and center is None, return directly -------------\n if spherical and center is None:\n pts = np.column_stack((r, theta, phi))\n #---------------------------------------------------------------------------\n #------------ otherwise convert to cartesian --------------------\n else:\n pts_cart = sphe_to_cart( np.column_stack((r, theta, phi)), eps=eps )\n if spherical:\n pts_cart += np.asarray(center).reshape(1,3)\n pts = cart_to_sphe(pts_cart, eps=eps)\n else:\n if center is not None:\n pts_cart += np.asarray(center).reshape(1,3)\n pts = pts_cart\n return pts\n\n\n\n\n\n\n\n\n\nP2M (works)\n\n\n\n\ndef P2M(X_sphe, q, p=4):\n # X_sphe: (N,3) with columns [r, theta(azimuth), phi(polar)]\n r = X_sphe[:, 0]; theta = X_sphe[:, 1]; phi = X_sphe[:, 2]\n M = np.zeros(((p+1)**2,), dtype=np.complex128)\n idx = 0\n for n in range(p+1):\n c = 4.0 * np.pi / (2*n + 1) # from Laplace addition theorem\n rpow = r**n if n > 0 else np.ones_like(r)\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n M[idx] = c * np.sum(q * rpow * np.conj(Y))\n idx += 1\n return M\n\n\n\n\n\n\n\n\nPotential from multipoles (works)\n\n\n\n\ndef P_moment(M, x_tgt_sphe):\n r = x_tgt_sphe[:, 0]; theta = x_tgt_sphe[:, 1]; phi = x_tgt_sphe[:, 2]\n P = np.zeros_like(r, dtype=np.complex128)\n p = int(np.sqrt(M.shape[0])) - 1\n idx = 0\n for n in range(p+1):\n rinv = r**(-(n+1))\n for m in range(-n, n+1):\n Y = sph_harm_y(n, m, theta, phi)\n P += M[idx] * rinv * Y\n idx += 1\n return np.real(P)\n\n\n\n\n\n\n\n\nDirect potential (reference)\n\n\n\n\ndef P_direct_cart_vec(X_cart, q, x_tgt_cart, eps=1e-10):\n diff = x_tgt_cart[:, None, :] - X_cart[None, :, :]\n r = np.linalg.norm(diff, axis=2)\n if eps != 0.0:\n r = np.sqrt(r*r + eps*eps)\n return (q / r).sum(axis=1)\n\n\n\n\n\nP2M + evaluation matches P_direct_cart_vec within truncation error, so I’m reasonably confident these two pieces are consistent.\n\n\n\n\n\n\n\nM2M (problematic part)\n\n\n\n\nI attempt to translate moments about $ \\mathbf{x}_0 $ to moments about $ \\mathbf{x}_1 $.\n\nLet $ (\\rho, \\alpha, \\beta) $ be the spherical coordinates of $ \\mathbf{d} = \\mathbf{x}_0 - \\mathbf{x}_1 $.\n\n\n\n\ndef lm_index(n, m): return n*n + n + m\n\ndef A(n, m):\n # A_n^m = (-1)^n / sqrt((n-m)!(n+m)!)\n return ((-1)**n) / np.sqrt(fac(n-m) * fac(n+m))\n\ndef M2M(M, x0, x1):\n p = int(np.sqrt(M.shape[0])) - 1\n d = x0 - x1\n rho, alpha, beta = cart_to_sphe(d.reshape(1,3)).flatten()\n M_out = np.zeros_like(M)\n for j in range(p+1):\n for k in range(-j, j+1):\n acc = 0.0 + 0.0j\n for n in range(0, j+1):\n jn = j - n\n # --- the questionable factor ---\n norm_factor = np.sqrt(4.0 * np.pi) / (2*n + 1)\n for m in range(-n, n+1):\n km = k - m\n if abs(km) > jn:\n continue\n O = M[lm_index(jn, km)]\n phase = 1j**(abs(k) - abs(m) - abs(km))\n coeff = (phase * A(jn, km) * A(n, m) / A(j, k)) * (rho**n) * norm_factor\n acc += O * coeff * np.conj(sph_harm_y(n, m, alpha, beta))\n M_out[lm_index(j, k)] = acc\n return M_out\n\n\n\n\n\nWith this norm_factor = sqrt(4π)/(2n+1), the translated $ n=0 $ and $ n=1 $ moments match the reference (computed by P2M around $ x_1 $).\n\nHowever, $ n \\ge 2 $ moments diverge even for small $ |\\mathbf{x}_0 - \\mathbf{x}_1| $.\n\n\n\n\nI’ve derived this step from Beatson & Greengard (1997, A short course on fast multipole methods) and cross-checked slides such as this lecture note (https://home.cscamm.umd.edu/programs/fam04/dg_lecture6.pdf).\n\nI also found similar unresolved questions:\n\n\n\n\n\nhttps://stackoverflow.com/questions/79718604/fmm-m2m-translation-discrepancy-greengards-short-course-with-scipy-spherical (https://stackoverflow.com/questions/79718604/fmm-m2m-translation-discrepancy-greengards-short-course-with-scipy-spherical)\n\n\n\n\nA python code for the translation of a multipole expansion (https://scicomp.stackexchange.com/questions/45189/a-python-code-for-the-translation-of-a-multipole-expansion)\n\n\n\n\n\n\n\n\nWhat I’m looking for\n\n\n\n\n\nA precise derivation that pins down the correct prefactor(s) for M2M under SciPy’s normalised $ Y_n^m $.\n\n\n\n\n\nPointers to a fully worked M2M translation using the same normalisation as SciPy would be ideal.\n\n\n\n\nReferences consulted:\n\nBeatson & Greengard (1997) – A short course on fast multipole methods\n\nDan Gremse’s CSCAMM FMM lecture notes (linked above)\n\nThe two related Q&As linked above\n\n\n\n\n\n\n\nHappy to provide additional diagnostic data (per-degree matrices, Gaunt coefficients, etc.).\n\nMy goal is to make the M2M step numerically consistent with the P2M/evaluation pair under the same spherical-harmonic conventions.\n\n\n\n\n\n\n\nSmall python code to test to test\n\n\n\n\n\nnp.random.seed(42)\nN = 10000 # number of points\nq = np.ones(N) # source strengths all positive 1\nsource_area_size = 1.0\np = 4\n#--------- generate a number of source points inside box ----------\nLLC = np.array([ -1.0, -1.0, -1.0 ]) * source_area_size # Lower Left Corner\nURC = np.array([ 1.0, 1.0, 1.0 ]) * source_area_size # Upper Right Corner\nX = np.random.rand(N, 3) # uniform in [0,1)\nX = LLC + (URC - LLC) * X # uniform in [LLC, URC]\nx_polar = cart_to_sphe(X)\n#------------------------------------------------------------------------\n\nx1 = np.array([0.0,0.0, 0.0])\nM2M_dist = 0.5 * source_area_size\nx0 = np.array([1.0,1.0,1.0]) * M2M_dist\n\n\n#--------- define target point outside box ----------\nNtgt = N\ndist = 10 * source_area_size\ncenter = np.array([1.0, 1.0, 1.0]) * dist\ncenter_sphe = cart_to_sphe(center.reshape(1,3))\n\ncenter_rel_x0 = center - x0\ncenter_rel_x0_sphe = cart_to_sphe(center_rel_x0.reshape(1,3))\n#------------------------------------------------------\n\nP_direct = P_direct_cart_vec(X, q, np.array([center]))[0]\n\nM_origin = P2M(x_polar, q, p=p)\n\nx_rel = X - x0\nx_rel_polar = cart_to_sphe(x_rel)\nM_x0 = P2M(x_rel_polar, q, p=p)\nM_tran = M2M(M_x0, x0, x1)\n\nP_mom_ori = P_moment(M_origin, center_sphe)[0]\nP_mom_x0 = P_moment(M_x0, center_rel_x0_sphe)[0]\nP_mom_tran = P_moment(M_tran, center_sphe )[0]\n\nprint(\"Direct eval: \", P_direct)\nprint(\"Moment at origin: \", P_mom_ori)\nprint(\"Moment at x0 \", P_mom_x0)\nprint(\"Moment at x0 then M2M: \", P_mom_tran)\n\n\n\n\n\nprints:\n\n\n\n\nDirect eval: 577.3045267385877\nMoment at origin: 577.3045187005426\nMoment at x0 577.305073670786\nMoment at x0 then M2M: 578.038378949856\n\n\n\n\n\nwhen normalisation factor is included in M2M and:\n\n\n\n\nMoment at x0 then M2M: 179.81604418879266\n\n\n\n\n\nwithout", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Michael Haahr", "profile_url": "https://scicomp.stackexchange.com/users/54898/michael-haahr", "user_type": "registered"}, "created_at": "2025-10-24T12:50:37+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C64F91DF-8B27-42BD-8352-457666F01A7D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C64F91DF-8B27-42BD-8352-457666F01A7D/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45262/m2m-in-python-using-scipy-sph-harm-y", "split": "holdout", "split_group": "54b95b63eb8e0909a0216cb5d132086e6488245fe23e1aa50189e50794a17c4a", "tags": ["python", "scipy", "spherical-harmonics", "fast-multipoles"], "thread_id": "scicomp:45262", "title": "M2M in python using SciPy.sph_harm_y"}} {"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": "The Dykstra Projection Algorithm is basically the ADMM Framework.
\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 in part 3.4.
Assuming the matrix $\\boldsymbol{A}$ is dense:
\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\nRemark: I'd be happy to see an efficient case of the Sparse case.
\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": "Read (if you're lucky, from your university's library)\nTrust Region Methods, Conn, Gould, and Toint [SIAM (2000)] and its associated implementation in scipy.optimize.minimize(method='trust-constr'). 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.
\nSet:
\nsparse_jacobian = Truefactorization_method = 'AugmentedSystem'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.bounds by your $l$ and $u$constraints to a LinearConstraint by your $A$ and using a scipy sparse arrayx0 to a sensible initial estimateIn 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", "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": "The Dykstra Projection Algorithm is basically the ADMM Framework.
\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 in part 3.4.
Assuming the matrix $\\boldsymbol{A}$ is dense:
\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\nRemark: I'd be happy to see an efficient case of the Sparse case.
\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": "Read (if you're lucky, from your university's library)\nTrust Region Methods, Conn, Gould, and Toint [SIAM (2000)] and its associated implementation in scipy.optimize.minimize(method='trust-constr'). 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.
\nSet:
\nsparse_jacobian = Truefactorization_method = 'AugmentedSystem'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.bounds by your $l$ and $u$constraints to a LinearConstraint by your $A$ and using a scipy sparse arrayx0 to a sensible initial estimateIn 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", "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": "Solve the following problem:
\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$$
\nWhere $\\boldsymbol{A} \\in \\mathbb{R}^{m \\times n}, \\; n \\gg m$ with independent rows.
\nI want to solve it for the cases:
\nIn most efficient way without using high level solvers.
\nBut just Use MATLAB / Python / Julia with their own Linear Algebra / Sparse libraries.
Currently my approach is to use Dykstra Projection Algorithm.
\nI wonder if there are some acceleration tricks.
In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.
Here is the fixed code:
\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == "complex" or str(a.dtype).startswith("complex"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n\nI hope this implementation ends up being useful to someone else.
\n", "answer_id": 45271, "answer_text": "In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.\n\n\n\n\nHere is the fixed code:\n\n\n\n\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n\n\n\n\n\nI hope this implementation ends up being useful to someone else.", "answer_url": "https://scicomp.stackexchange.com/a/45271", "author": "DMDemon", "author_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-29T14:17:07+00:00", "is_accepted": true, "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": 45269, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DMDemon", "profile_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "user_type": "registered"}, "created_at": "2025-10-29T14:17:07+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "6DF5DE67-1926-4793-AE81-11365490B04C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6DF5DE67-1926-4793-AE81-11365490B04C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DMDemon", "profile_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "user_type": "registered"}, "created_at": "2025-10-29T14:44:53+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "523EE8E6-85AA-4379-AC21-CD84C363A498", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/523EE8E6-85AA-4379-AC21-CD84C363A498/view-source"}], "score": 2, "updated_at": "2025-10-29T14:44:53+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "from math import pi, inf\n\nfrom typing import Literal\n\nfrom keras import KerasTensor as Tensor\nfrom keras import ops\n\ntype OutputType = Literal[\"real\", \"complex\"]\n\ndef quasi_triu(a: Tensor) -> Tensor:\n mod_idxs = ops.stack([\n ops.arange(1, len(a), 2),\n ops.arange(1, len(a), 2) - 1\n ], axis=1)\n return ops.scatter_update(ops.triu(a), mod_idxs, a[*mod_idxs.T])\n\ndef schur(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n a0, a1, z, cnt = None, a, ops.eye(a.shape[0]), 0\n while cnt < num_iters:\n a0, cnt = a1, cnt + 1\n q, r = ops.qr(a0)\n a1 = r @ q\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(a1), z\n else:\n return quasi_triu(a1), z\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45269, "sha256": "291468312e2229f4836baf338c916aee498dcdae95d01a6230f4c2d80ff4c8aa", "source_url": "https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"}, {"block_index": 1, "code_text": "def hessenberg(a: Tensor) -> tuple[Tensor, Tensor]:\n a = ops.convert_to_tensor(a)\n n = a.shape[0]\n u = ops.eye(n)\n\n for k in range(n - 2):\n aux_coeff = ops.where(\n a[k + 1, k] == 0,\n -1,\n a[k + 1, k] / ops.abs(a[k + 1, k])\n )\n\n w = ops.norm(\n a[k + 1:, k], 2\n ) * ops.eye(n - (k + 1), 1) + aux_coeff * a[k + 1:, k:k + 1]\n\n v_householder = ops.eye(\n n - (k + 1)\n ) - 2 * w @ ops.conj(ops.transpose(w)) / ops.norm(w, 2)**2\n u_k = ops.slice_update(\n ops.eye(n, dtype=v_householder.dtype),\n (k + 1, k + 1),\n v_householder\n )\n\n a = conj_transpose(u_k) @ a @ u_k # Necessary due to single precision\n u = u @ u_k\n\n assert np.allclose(np.eye(n), conj_transpose(u) @ u, atol=1e-6)\n\n return a, u\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45269, "sha256": "0bdcbf88c1c2d64d4086c0191fc71f52af820620bb0ca546cf33a2659b059f99", "source_url": "https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"}, {"block_index": 2, "code_text": "def schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n h, q = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n))\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q @ z\n else:\n return quasi_triu(h), q @ z\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45269, "sha256": "3c453ecb8764caf83c0a5c66b6e147a8ccdb6e91faca3869f7a2b99b40480e2e", "source_url": "https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"}, {"block_index": 3, "code_text": "test_matrix = np.random.random((5, 5))\nt0, z0 = schur_hessenberg(test_matrix, \"real\", 100000)\nt1, z1 = schur(test_matrix, \"real\", 100000)\n\nprint(np.abs(test_matrix - z0 @ t0 @ conj_transpose(z0)))\nprint(np.abs(test_matrix - z1 @ t1 @ conj_transpose(z1)))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45269, "sha256": "797aa53ef8db34d58cd42cb9469f4c1d5ec921c011caff56be4a075f234f49bf", "source_url": "https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api"}, {"block_index": 0, "code_text": "def schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45271, "sha256": "db75e4470031d50ac0978f0be16e45c7272de2bec10b784552cdc41c74d9ff97", "source_url": "https://scicomp.stackexchange.com/a/45271"}], "other_answers": [], "product": "code_qa", "question": "I am trying to implement the Complex and Real Schur Decompositions using only the Keras Ops API, so I can utilize it to impose some eigenvalue constraints on a weight matrix. I am also using the JAX backend, which further limits what I can actually do with the input matrix:\n\n\n\n\n\nAll operations are done using single-precision floating-point operations, and no in-place modifications are allowed.\n\n\n\n\nThe stopping criterion has to be static (e.g., an argument of the decomposition function, as I am currently doing) or a function of the input shape (similar to the max-iteration heuristic used by the LAPACK implementation (https://www.netlib.org/lapack/explore-html/d8/df4/group__lahqr_ga797fe3b28e02bea7dd5762dbaa28277e.html#ga797fe3b28e02bea7dd5762dbaa28277e)), as the execution graph is pre-compiled using a traced array.\n\n\n\nThis also means that conversion to a numpy ndarray is not allowed.\n\n\n\n\n\n\n\n\nI could, in theory, use JAX-specific functions, since the Keras tensors are just JAX arrays in disguise. However, I want to keep the code backend-agnostic if possible.\n\n\n\nIt is worth noting that JAX currently has a CPU-only implementation (https://docs.jax.dev/en/latest/_autosummary/jax.scipy.linalg.schur.html) of the Schur algorithm; however, my code requires GPU execution, so I cannot use it.\n\n\n\n\n\n\n\n\n\nWith that being said, I've already made some progress using these (https://people.inf.ethz.ch/arbenz/ewp/Lnotes/chapter4.pdf) lecture notes from ETH Zürich. More specifically, I got algorithm 4.1 (Basic QR algorithm) working (variable-naming conventions from Scipy (https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.schur.html)):\n\n\n\n\nfrom math import pi, inf\n\nfrom typing import Literal\n\nfrom keras import KerasTensor as Tensor\nfrom keras import ops\n\ntype OutputType = Literal[\"real\", \"complex\"]\n\ndef quasi_triu(a: Tensor) -> Tensor:\n mod_idxs = ops.stack([\n ops.arange(1, len(a), 2),\n ops.arange(1, len(a), 2) - 1\n ], axis=1)\n return ops.scatter_update(ops.triu(a), mod_idxs, a[*mod_idxs.T])\n\ndef schur(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n a0, a1, z, cnt = None, a, ops.eye(a.shape[0]), 0\n while cnt < num_iters:\n a0, cnt = a1, cnt + 1\n q, r = ops.qr(a0)\n a1 = r @ q\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(a1), z\n else:\n return quasi_triu(a1), z\n\n\n\n\n\nHowever, as expected, the convergence rate is so low that I have to choose between preemptively setting an absurd number of iterations or risking instability due to non-convergence. Thus, I'm now trying to get algorithm 4.4 (Hessenberg QR algorithm with Rayleigh quotient shift) to work. So far, I have implemented the reduction to the Hessenberg matrix through Householder transformations following the theory in Wikipedia (https://en.wikipedia.org/wiki/Hessenberg_matrix#Householder_transformations), with some modifications to preserve compatibility with the Scipy (https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.hessenberg.html) version ($A = QHQ^*$ instead of $H = QAQ^*$):\n\n\n\n\ndef hessenberg(a: Tensor) -> tuple[Tensor, Tensor]:\n a = ops.convert_to_tensor(a)\n n = a.shape[0]\n u = ops.eye(n)\n\n for k in range(n - 2):\n aux_coeff = ops.where(\n a[k + 1, k] == 0,\n -1,\n a[k + 1, k] / ops.abs(a[k + 1, k])\n )\n\n w = ops.norm(\n a[k + 1:, k], 2\n ) * ops.eye(n - (k + 1), 1) + aux_coeff * a[k + 1:, k:k + 1]\n\n v_householder = ops.eye(\n n - (k + 1)\n ) - 2 * w @ ops.conj(ops.transpose(w)) / ops.norm(w, 2)**2\n u_k = ops.slice_update(\n ops.eye(n, dtype=v_householder.dtype),\n (k + 1, k + 1),\n v_householder\n )\n\n a = conj_transpose(u_k) @ a @ u_k # Necessary due to single precision\n u = u @ u_k\n\n assert np.allclose(np.eye(n), conj_transpose(u) @ u, atol=1e-6)\n\n return a, u\n\n\n\n\n\nHowever, I haven't been able to get the actual algorithm working. So far, I have the following function:\n\n\n\n\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n h, q = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n))\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q @ z\n else:\n return quasi_triu(h), q @ z\n\n\n\n\n\nHowever, when I test both methods using a random real matrix (similar results for the complex case) and measure the matrix reconstruction absolute error as\n\n\n\n\ntest_matrix = np.random.random((5, 5))\nt0, z0 = schur_hessenberg(test_matrix, \"real\", 100000)\nt1, z1 = schur(test_matrix, \"real\", 100000)\n\nprint(np.abs(test_matrix - z0 @ t0 @ conj_transpose(z0)))\nprint(np.abs(test_matrix - z1 @ t1 @ conj_transpose(z1)))\n\n\n\n\n\nI get the following results:\n\n\n\n\n[[0.02052921 0.62834513 1.0401626 0.08546968 0.50802547]\n [1.2145011 0.47686994 0.14543009 0.77371585 0.44549757]\n [1.7762737 0.04462999 0.84596455 0.12113664 0.42194515]\n [0.6079759 0.8015515 0.0135076 0.07646421 0.00241762]\n [0.12112255 0.72910243 0.5631428 0.03763434 1.2257423 ]]\n\n[[6.2525272e-05 4.6223402e-05 5.9843063e-05 6.6056848e-05 1.8805265e-05]\n [2.8496981e-04 1.1801720e-05 1.1438131e-04 3.2186508e-06 2.9633939e-04]\n [8.8214874e-06 2.5629997e-05 1.8000603e-05 3.6358833e-05 2.2232533e-05]\n [1.5932322e-04 3.5166740e-05 2.1210406e-05 9.1180205e-05 1.7516315e-04]\n [2.7435273e-04 5.5968761e-05 3.5285950e-05 8.4638596e-06 1.6790628e-04]]\n\n\n\n\n\nClearly, the decomposition is not properly implemented. I already checked the Hessenberg decomposition reconstruction error and, numerical precision aside, it seems to be working. Furthermore, the $H$ matrix generated by the Hessenberg QR iterations seems to be (at least) quasi-upper triangular. Thus, I have either a) incorrectly implemented the Hessenberg QR iterations, or b) failed to properly combine the Hessenberg and Schur factors.\n\n\n\n\nI've already gone over the code and reference material several times, but I cannot spot where I'm screwing up, so I'd really appreciate any pointers.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45269", "selected_answer": {"answer_html": "In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.
Here is the fixed code:
\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == "complex" or str(a.dtype).startswith("complex"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n\nI hope this implementation ends up being useful to someone else.
\n", "answer_id": 45271, "answer_text": "In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.\n\n\n\n\nHere is the fixed code:\n\n\n\n\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n\n\n\n\n\nI hope this implementation ends up being useful to someone else.", "answer_url": "https://scicomp.stackexchange.com/a/45271", "author": "DMDemon", "author_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-29T14:17:07+00:00", "is_accepted": true, "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": 45269, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DMDemon", "profile_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "user_type": "registered"}, "created_at": "2025-10-29T14:17:07+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "6DF5DE67-1926-4793-AE81-11365490B04C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6DF5DE67-1926-4793-AE81-11365490B04C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DMDemon", "profile_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "user_type": "registered"}, "created_at": "2025-10-29T14:44:53+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "523EE8E6-85AA-4379-AC21-CD84C363A498", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/523EE8E6-85AA-4379-AC21-CD84C363A498/view-source"}], "score": 2, "updated_at": "2025-10-29T14:44:53+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": 45271, "answers": [{"answer_html": "In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.
Here is the fixed code:
\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == "complex" or str(a.dtype).startswith("complex"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n\nI hope this implementation ends up being useful to someone else.
\n", "answer_id": 45271, "answer_text": "In the end, it was a variable shadowing bug: during the QR iterations, I was overwriting q when calling ops.qr.\n\n\n\n\nHere is the fixed code:\n\n\n\n\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n # Before: h, q = hessenberg(a)\n h, q_hess = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n)) # Shadowing occurs here\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q_hess @ z\n else:\n return quasi_triu(h), q_hess @ z\n\n\n\n\n\nI hope this implementation ends up being useful to someone else.", "answer_url": "https://scicomp.stackexchange.com/a/45271", "author": "DMDemon", "author_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-10-29T14:17:07+00:00", "is_accepted": true, "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": 45269, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DMDemon", "profile_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "user_type": "registered"}, "created_at": "2025-10-29T14:17:07+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "6DF5DE67-1926-4793-AE81-11365490B04C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6DF5DE67-1926-4793-AE81-11365490B04C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DMDemon", "profile_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "user_type": "registered"}, "created_at": "2025-10-29T14:44:53+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "523EE8E6-85AA-4379-AC21-CD84C363A498", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/523EE8E6-85AA-4379-AC21-CD84C363A498/view-source"}], "score": 2, "updated_at": "2025-10-29T14:44:53+00:00"}], "domain": "computational_science", "external_links": ["https://docs.jax.dev/en/latest/_autosummary/jax.scipy.linalg.schur.html", "https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.hessenberg.html", "https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.schur.html", "https://en.wikipedia.org/wiki/Hessenberg_matrix#Householder_transformations", "https://people.inf.ethz.ch/arbenz/ewp/Lnotes/chapter4.pdf", "https://www.netlib.org/lapack/explore-html/d8/df4/group__lahqr_ga797fe3b28e02bea7dd5762dbaa28277e.html#ga797fe3b28e02bea7dd5762dbaa28277e"], "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": "DMDemon", "question_author_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "question_author_user_type": "registered", "question_created_at": "2025-10-28T18:12:37+00:00", "question_html": "I am trying to implement the Complex and Real Schur Decompositions using only the Keras Ops API, so I can utilize it to impose some eigenvalue constraints on a weight matrix. I am also using the JAX backend, which further limits what I can actually do with the input matrix:
\nWith that being said, I've already made some progress using these lecture notes from ETH Zürich. More specifically, I got algorithm 4.1 (Basic QR algorithm) working (variable-naming conventions from Scipy):
\nfrom math import pi, inf\n\nfrom typing import Literal\n\nfrom keras import KerasTensor as Tensor\nfrom keras import ops\n\ntype OutputType = Literal["real", "complex"]\n\ndef quasi_triu(a: Tensor) -> Tensor:\n mod_idxs = ops.stack([\n ops.arange(1, len(a), 2),\n ops.arange(1, len(a), 2) - 1\n ], axis=1)\n return ops.scatter_update(ops.triu(a), mod_idxs, a[*mod_idxs.T])\n\ndef schur(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n a0, a1, z, cnt = None, a, ops.eye(a.shape[0]), 0\n while cnt < num_iters:\n a0, cnt = a1, cnt + 1\n q, r = ops.qr(a0)\n a1 = r @ q\n z = z @ q\n\n if output == "complex" or str(a.dtype).startswith("complex"):\n return ops.triu(a1), z\n else:\n return quasi_triu(a1), z\n\nHowever, as expected, the convergence rate is so low that I have to choose between preemptively setting an absurd number of iterations or risking instability due to non-convergence. Thus, I'm now trying to get algorithm 4.4 (Hessenberg QR algorithm with Rayleigh quotient shift) to work. So far, I have implemented the reduction to the Hessenberg matrix through Householder transformations following the theory in Wikipedia, with some modifications to preserve compatibility with the Scipy version ($A = QHQ^*$ instead of $H = QAQ^*$):
\ndef hessenberg(a: Tensor) -> tuple[Tensor, Tensor]:\n a = ops.convert_to_tensor(a)\n n = a.shape[0]\n u = ops.eye(n)\n\n for k in range(n - 2):\n aux_coeff = ops.where(\n a[k + 1, k] == 0,\n -1,\n a[k + 1, k] / ops.abs(a[k + 1, k])\n )\n\n w = ops.norm(\n a[k + 1:, k], 2\n ) * ops.eye(n - (k + 1), 1) + aux_coeff * a[k + 1:, k:k + 1]\n\n v_householder = ops.eye(\n n - (k + 1)\n ) - 2 * w @ ops.conj(ops.transpose(w)) / ops.norm(w, 2)**2\n u_k = ops.slice_update(\n ops.eye(n, dtype=v_householder.dtype),\n (k + 1, k + 1),\n v_householder\n )\n\n a = conj_transpose(u_k) @ a @ u_k # Necessary due to single precision\n u = u @ u_k\n\n assert np.allclose(np.eye(n), conj_transpose(u) @ u, atol=1e-6)\n\n return a, u\n\nHowever, I haven't been able to get the actual algorithm working. So far, I have the following function:
\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n h, q = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n))\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == "complex" or str(a.dtype).startswith("complex"):\n return ops.triu(h), q @ z\n else:\n return quasi_triu(h), q @ z\n\nHowever, when I test both methods using a random real matrix (similar results for the complex case) and measure the matrix reconstruction absolute error as
\ntest_matrix = np.random.random((5, 5))\nt0, z0 = schur_hessenberg(test_matrix, "real", 100000)\nt1, z1 = schur(test_matrix, "real", 100000)\n\nprint(np.abs(test_matrix - z0 @ t0 @ conj_transpose(z0)))\nprint(np.abs(test_matrix - z1 @ t1 @ conj_transpose(z1)))\n\nI get the following results:
\n[[0.02052921 0.62834513 1.0401626 0.08546968 0.50802547]\n [1.2145011 0.47686994 0.14543009 0.77371585 0.44549757]\n [1.7762737 0.04462999 0.84596455 0.12113664 0.42194515]\n [0.6079759 0.8015515 0.0135076 0.07646421 0.00241762]\n [0.12112255 0.72910243 0.5631428 0.03763434 1.2257423 ]]\n\n[[6.2525272e-05 4.6223402e-05 5.9843063e-05 6.6056848e-05 1.8805265e-05]\n [2.8496981e-04 1.1801720e-05 1.1438131e-04 3.2186508e-06 2.9633939e-04]\n [8.8214874e-06 2.5629997e-05 1.8000603e-05 3.6358833e-05 2.2232533e-05]\n [1.5932322e-04 3.5166740e-05 2.1210406e-05 9.1180205e-05 1.7516315e-04]\n [2.7435273e-04 5.5968761e-05 3.5285950e-05 8.4638596e-06 1.6790628e-04]]\n\nClearly, the decomposition is not properly implemented. I already checked the Hessenberg decomposition reconstruction error and, numerical precision aside, it seems to be working. Furthermore, the $H$ matrix generated by the Hessenberg QR iterations seems to be (at least) quasi-upper triangular. Thus, I have either a) incorrectly implemented the Hessenberg QR iterations, or b) failed to properly combine the Hessenberg and Schur factors.
\nI've already gone over the code and reference material several times, but I cannot spot where I'm screwing up, so I'd really appreciate any pointers.
\n", "question_id": 45269, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I am trying to implement the Complex and Real Schur Decompositions using only the Keras Ops API, so I can utilize it to impose some eigenvalue constraints on a weight matrix. I am also using the JAX backend, which further limits what I can actually do with the input matrix:\n\n\n\n\n\nAll operations are done using single-precision floating-point operations, and no in-place modifications are allowed.\n\n\n\n\nThe stopping criterion has to be static (e.g., an argument of the decomposition function, as I am currently doing) or a function of the input shape (similar to the max-iteration heuristic used by the LAPACK implementation (https://www.netlib.org/lapack/explore-html/d8/df4/group__lahqr_ga797fe3b28e02bea7dd5762dbaa28277e.html#ga797fe3b28e02bea7dd5762dbaa28277e)), as the execution graph is pre-compiled using a traced array.\n\n\n\nThis also means that conversion to a numpy ndarray is not allowed.\n\n\n\n\n\n\n\n\nI could, in theory, use JAX-specific functions, since the Keras tensors are just JAX arrays in disguise. However, I want to keep the code backend-agnostic if possible.\n\n\n\nIt is worth noting that JAX currently has a CPU-only implementation (https://docs.jax.dev/en/latest/_autosummary/jax.scipy.linalg.schur.html) of the Schur algorithm; however, my code requires GPU execution, so I cannot use it.\n\n\n\n\n\n\n\n\n\nWith that being said, I've already made some progress using these (https://people.inf.ethz.ch/arbenz/ewp/Lnotes/chapter4.pdf) lecture notes from ETH Zürich. More specifically, I got algorithm 4.1 (Basic QR algorithm) working (variable-naming conventions from Scipy (https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.schur.html)):\n\n\n\n\nfrom math import pi, inf\n\nfrom typing import Literal\n\nfrom keras import KerasTensor as Tensor\nfrom keras import ops\n\ntype OutputType = Literal[\"real\", \"complex\"]\n\ndef quasi_triu(a: Tensor) -> Tensor:\n mod_idxs = ops.stack([\n ops.arange(1, len(a), 2),\n ops.arange(1, len(a), 2) - 1\n ], axis=1)\n return ops.scatter_update(ops.triu(a), mod_idxs, a[*mod_idxs.T])\n\ndef schur(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n a0, a1, z, cnt = None, a, ops.eye(a.shape[0]), 0\n while cnt < num_iters:\n a0, cnt = a1, cnt + 1\n q, r = ops.qr(a0)\n a1 = r @ q\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(a1), z\n else:\n return quasi_triu(a1), z\n\n\n\n\n\nHowever, as expected, the convergence rate is so low that I have to choose between preemptively setting an absurd number of iterations or risking instability due to non-convergence. Thus, I'm now trying to get algorithm 4.4 (Hessenberg QR algorithm with Rayleigh quotient shift) to work. So far, I have implemented the reduction to the Hessenberg matrix through Householder transformations following the theory in Wikipedia (https://en.wikipedia.org/wiki/Hessenberg_matrix#Householder_transformations), with some modifications to preserve compatibility with the Scipy (https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.hessenberg.html) version ($A = QHQ^*$ instead of $H = QAQ^*$):\n\n\n\n\ndef hessenberg(a: Tensor) -> tuple[Tensor, Tensor]:\n a = ops.convert_to_tensor(a)\n n = a.shape[0]\n u = ops.eye(n)\n\n for k in range(n - 2):\n aux_coeff = ops.where(\n a[k + 1, k] == 0,\n -1,\n a[k + 1, k] / ops.abs(a[k + 1, k])\n )\n\n w = ops.norm(\n a[k + 1:, k], 2\n ) * ops.eye(n - (k + 1), 1) + aux_coeff * a[k + 1:, k:k + 1]\n\n v_householder = ops.eye(\n n - (k + 1)\n ) - 2 * w @ ops.conj(ops.transpose(w)) / ops.norm(w, 2)**2\n u_k = ops.slice_update(\n ops.eye(n, dtype=v_householder.dtype),\n (k + 1, k + 1),\n v_householder\n )\n\n a = conj_transpose(u_k) @ a @ u_k # Necessary due to single precision\n u = u @ u_k\n\n assert np.allclose(np.eye(n), conj_transpose(u) @ u, atol=1e-6)\n\n return a, u\n\n\n\n\n\nHowever, I haven't been able to get the actual algorithm working. So far, I have the following function:\n\n\n\n\ndef schur_hessenberg(a: Tensor, output: OutputType,\n num_iters: int) -> tuple[Tensor, Tensor]:\n n = a.shape[0]\n\n h, q = hessenberg(a)\n\n z = ops.eye(n)\n for m in range(n - 1, 0, -1):\n for _ in range(num_iters):\n sigma = h[m, m]\n q, r = ops.qr(h - sigma * ops.eye(n))\n h = r @ q + sigma * ops.eye(n)\n z = z @ q\n\n if output == \"complex\" or str(a.dtype).startswith(\"complex\"):\n return ops.triu(h), q @ z\n else:\n return quasi_triu(h), q @ z\n\n\n\n\n\nHowever, when I test both methods using a random real matrix (similar results for the complex case) and measure the matrix reconstruction absolute error as\n\n\n\n\ntest_matrix = np.random.random((5, 5))\nt0, z0 = schur_hessenberg(test_matrix, \"real\", 100000)\nt1, z1 = schur(test_matrix, \"real\", 100000)\n\nprint(np.abs(test_matrix - z0 @ t0 @ conj_transpose(z0)))\nprint(np.abs(test_matrix - z1 @ t1 @ conj_transpose(z1)))\n\n\n\n\n\nI get the following results:\n\n\n\n\n[[0.02052921 0.62834513 1.0401626 0.08546968 0.50802547]\n [1.2145011 0.47686994 0.14543009 0.77371585 0.44549757]\n [1.7762737 0.04462999 0.84596455 0.12113664 0.42194515]\n [0.6079759 0.8015515 0.0135076 0.07646421 0.00241762]\n [0.12112255 0.72910243 0.5631428 0.03763434 1.2257423 ]]\n\n[[6.2525272e-05 4.6223402e-05 5.9843063e-05 6.6056848e-05 1.8805265e-05]\n [2.8496981e-04 1.1801720e-05 1.1438131e-04 3.2186508e-06 2.9633939e-04]\n [8.8214874e-06 2.5629997e-05 1.8000603e-05 3.6358833e-05 2.2232533e-05]\n [1.5932322e-04 3.5166740e-05 2.1210406e-05 9.1180205e-05 1.7516315e-04]\n [2.7435273e-04 5.5968761e-05 3.5285950e-05 8.4638596e-06 1.6790628e-04]]\n\n\n\n\n\nClearly, the decomposition is not properly implemented. I already checked the Hessenberg decomposition reconstruction error and, numerical precision aside, it seems to be working. Furthermore, the $H$ matrix generated by the Hessenberg QR iterations seems to be (at least) quasi-upper triangular. Thus, I have either a) incorrectly implemented the Hessenberg QR iterations, or b) failed to properly combine the Hessenberg and Schur factors.\n\n\n\n\nI've already gone over the code and reference material several times, but I cannot spot where I'm screwing up, so I'd really appreciate any pointers.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "DMDemon", "profile_url": "https://scicomp.stackexchange.com/users/55920/dmdemon", "user_type": "registered"}, "created_at": "2025-10-28T18:12:37+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "28BA02D1-48B0-4A5E-B0C4-2D9EB5079696", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/28BA02D1-48B0-4A5E-B0C4-2D9EB5079696/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45269/help-implementing-the-hessenberg-qr-algorithm-using-the-keras-ops-api", "split": "holdout", "split_group": "89253ec60f0a14ca9afcf79dacb38e6abe75b5d7666fc3928404bea668328849", "tags": ["linear-algebra", "python", "qr"], "thread_id": "scicomp:45269", "title": "Help implementing the Hessenberg QR algorithm using the Keras Ops API"}} {"accepted_answer": {"answer_html": "The integral is incorrect. It should be:
\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$
\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$
\n", "answer_id": 45287, "answer_text": "The integral is incorrect. It should be:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$\n\n\n\n\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$", "answer_url": "https://scicomp.stackexchange.com/a/45287", "author": "Makogan", "author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:39:36+00:00", "is_accepted": true, "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": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Makogan", "profile_url": "https://scicomp.stackexchange.com/users/38908/makogan", "user_type": "registered"}, "created_at": "2025-11-21T06:39:36+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFA52975-239F-441C-8A99-5359D4A5D377", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFA52975-239F-441C-8A99-5359D4A5D377/view-source"}], "score": 2, "updated_at": "2025-11-21T06:39:36+00:00"}, "code_blocks": [{"block_index": 1, "code_text": "fn fourier_projectionThe fourier transform assumes that the domain is infinite. In a finite domain the periodicity is only given for the symmetric cosine part of the base. The cosine function is symmetric around 0. The sine function is only for certain frequencies!
\nIf you want to create a usefull base in a finite cell, then maybe the cosine transform is the way to go and not the fourier base. cosine transform
\nedit:\nI think I was wrong on this. It might be possible although i am not sure about the continuities at the borders of the cell.
\n", "answer_id": 45286, "answer_text": "The fourier transform assumes that the domain is infinite. In a finite domain the periodicity is only given for the symmetric cosine part of the base. The cosine function is symmetric around 0. The sine function is only for certain frequencies!\n\n\n\n\nIf you want to create a usefull base in a finite cell, then maybe the cosine transform is the way to go and not the fourier base. cosine transform (https://en.wikipedia.org/wiki/Discrete_cosine_transform)\n\n\n\n\nedit:\nI think I was wrong on this. It might be possible although i am not sure about the continuities at the borders of the cell.", "answer_url": "https://scicomp.stackexchange.com/a/45286", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:31:22+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": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-21T06:31:22+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "CBEFF318-897B-4078-914B-16A6943BCDC5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/CBEFF318-897B-4078-914B-16A6943BCDC5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-21T10:25:12+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "64E18437-B71C-4033-8D9E-EBECF3C94E96", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/64E18437-B71C-4033-8D9E-EBECF3C94E96/view-source"}], "score": 1, "updated_at": "2025-11-21T10:25:12+00:00"}], "product": "code_qa", "question": "Math preamble\n\n\n\n\nI am trying to create a functional basis for $[-1, 1]^3$ in $\\mathbb{R}^3$. To this effect I take the real expression of the fourier basis and index it with an integer such that\n\n\n\n\n$$\\phi_i(x) = \\cos(\\pi n/2 x)$$\n\n\n\n\nif $i$ is even and\n\n\n\n\n$$\\phi_i(x) = \\sin(\\pi [(n/2) + 1] x)$$\n\n\n\n\nif $i$ is odd.\n\n\n\n\nThen I normalize them, so for simplicity of writing, assume $\\phi_i$ is the normalized version of the function.\n\n\n\n\nWith that definition I create the basis through the tensor product.\n\n\n\n\n$$\\Phi_{i,j,k}(x, y, z) = \\phi_i(x) \\phi_j(y) \\phi_k(z)$$\n\n\n\n\nAlgorithm\n\n\n\n\nNow to render the above basis computable I am only dealing with triplets such that $i + j + k \\leq N$ for some integer $N$.\n\n\n\n\nI am using the trapezoidal rule (also extended through the tensor product) in order to compute integrals, so\n\n\n\n\n$$\\int_\\Omega f(X) \\Phi_{i, j, k}(X) dV \\approx \\sum w_l w_m w_n f(X_{l, m, n})) \\Phi_{i, j, k}(X_{l, m, n}) \\Delta x \\Delta y \\Delta z$$\n\n\n\n\nwhere $w_i$ refer to the weights from the trapezoidal rule. 0.5 at the margins and 1 in the interior.\n\n\n\n\nUsing the above I am projecting different functions onto the discretized basis and then reconstructing them to see the accuracy.\n\n\n\n\nExperiments\n\n\n\n\nI am testing my code and I am noticing discrepancies, for example. I am trying to project $f(x, y, z) = \\cos(\\pi x)$ onto $\\Phi_{2, 0, 0}$\n\n\n\n\nFrom the original definition you will notice that $\\Phi_{2, 0, 0}$ should be $\\cos(\\pi x) / \\sqrt{2}$\n\n\n\n\nSo my expectation is that I am computing:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{\\sqrt{2}} dx dy dz \\approx 2.83$$\n\n\n\n\nHowever, what I am getting is\n\n\n\n\n1.9999999999967393\n\n\n\n\n\nThis is my code (written in rust):\n\n\n\n\nfn fourier_projectionThe integral is incorrect. It should be:
\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$
\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$
\n", "answer_id": 45287, "answer_text": "The integral is incorrect. It should be:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$\n\n\n\n\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$", "answer_url": "https://scicomp.stackexchange.com/a/45287", "author": "Makogan", "author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:39:36+00:00", "is_accepted": true, "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": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Makogan", "profile_url": "https://scicomp.stackexchange.com/users/38908/makogan", "user_type": "registered"}, "created_at": "2025-11-21T06:39:36+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFA52975-239F-441C-8A99-5359D4A5D377", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFA52975-239F-441C-8A99-5359D4A5D377/view-source"}], "score": 2, "updated_at": "2025-11-21T06:39:36+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": 45287, "answers": [{"answer_html": "The fourier transform assumes that the domain is infinite. In a finite domain the periodicity is only given for the symmetric cosine part of the base. The cosine function is symmetric around 0. The sine function is only for certain frequencies!
\nIf you want to create a usefull base in a finite cell, then maybe the cosine transform is the way to go and not the fourier base. cosine transform
\nedit:\nI think I was wrong on this. It might be possible although i am not sure about the continuities at the borders of the cell.
\n", "answer_id": 45286, "answer_text": "The fourier transform assumes that the domain is infinite. In a finite domain the periodicity is only given for the symmetric cosine part of the base. The cosine function is symmetric around 0. The sine function is only for certain frequencies!\n\n\n\n\nIf you want to create a usefull base in a finite cell, then maybe the cosine transform is the way to go and not the fourier base. cosine transform (https://en.wikipedia.org/wiki/Discrete_cosine_transform)\n\n\n\n\nedit:\nI think I was wrong on this. It might be possible although i am not sure about the continuities at the borders of the cell.", "answer_url": "https://scicomp.stackexchange.com/a/45286", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:31:22+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": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-21T06:31:22+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "CBEFF318-897B-4078-914B-16A6943BCDC5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/CBEFF318-897B-4078-914B-16A6943BCDC5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-21T10:25:12+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "64E18437-B71C-4033-8D9E-EBECF3C94E96", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/64E18437-B71C-4033-8D9E-EBECF3C94E96/view-source"}], "score": 1, "updated_at": "2025-11-21T10:25:12+00:00"}, {"answer_html": "The integral is incorrect. It should be:
\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$
\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$
\n", "answer_id": 45287, "answer_text": "The integral is incorrect. It should be:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{2} dx dy dz = 2$$\n\n\n\n\nThe reason is that $[2, 0, 0]$ maps to two level 0 cosines each with norm $\\sqrt{2}$", "answer_url": "https://scicomp.stackexchange.com/a/45287", "author": "Makogan", "author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-21T06:39:36+00:00", "is_accepted": true, "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": 45285, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Makogan", "profile_url": "https://scicomp.stackexchange.com/users/38908/makogan", "user_type": "registered"}, "created_at": "2025-11-21T06:39:36+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFA52975-239F-441C-8A99-5359D4A5D377", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFA52975-239F-441C-8A99-5359D4A5D377/view-source"}], "score": 2, "updated_at": "2025-11-21T06:39:36+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Discrete_cosine_transform"], "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": "Makogan", "question_author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "question_author_user_type": "registered", "question_created_at": "2025-11-21T02:24:58+00:00", "question_html": "I am trying to create a functional basis for $[-1, 1]^3$ in $\\mathbb{R}^3$. To this effect I take the real expression of the fourier basis and index it with an integer such that
\n$$\\phi_i(x) = \\cos(\\pi n/2 x)$$
\nif $i$ is even and
\n$$\\phi_i(x) = \\sin(\\pi [(n/2) + 1] x)$$
\nif $i$ is odd.
\nThen I normalize them, so for simplicity of writing, assume $\\phi_i$ is the normalized version of the function.
\nWith that definition I create the basis through the tensor product.
\n$$\\Phi_{i,j,k}(x, y, z) = \\phi_i(x) \\phi_j(y) \\phi_k(z)$$
\nNow to render the above basis computable I am only dealing with triplets such that $i + j + k \\leq N$ for some integer $N$.
\nI am using the trapezoidal rule (also extended through the tensor product) in order to compute integrals, so
\n$$\\int_\\Omega f(X) \\Phi_{i, j, k}(X) dV \\approx \\sum w_l w_m w_n f(X_{l, m, n})) \\Phi_{i, j, k}(X_{l, m, n}) \\Delta x \\Delta y \\Delta z$$
\nwhere $w_i$ refer to the weights from the trapezoidal rule. 0.5 at the margins and 1 in the interior.
\nUsing the above I am projecting different functions onto the discretized basis and then reconstructing them to see the accuracy.
\nI am testing my code and I am noticing discrepancies, for example. I am trying to project $f(x, y, z) = \\cos(\\pi x)$ onto $\\Phi_{2, 0, 0}$
\nFrom the original definition you will notice that $\\Phi_{2, 0, 0}$ should be $\\cos(\\pi x) / \\sqrt{2}$
\nSo my expectation is that I am computing:
\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{\\sqrt{2}} dx dy dz \\approx 2.83$$
\nHowever, what I am getting is
\n1.9999999999967393\n\nThis is my code (written in rust):
\nfn fourier_projection<F, S: RealField, const DIM: usize>(\n mut function: F,\n interval: [[S; 2]; DIM],\n basis_index: [usize; DIM],\n resolution: usize,\n) -> S\nwhere\n F: FnMut([S; DIM]) -> S,\n{\n let trapezoidal_weight = |i: usize| {\n if i == 0 || i == resolution - 1\n {\n S::from(0.5).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n };\n\n let mut res = S::default();\n\n for xi in IterDimensions::new([resolution; DIM])\n {\n let mut point = [S::default(); DIM];\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let x = t * range + interval[d][0];\n\n point[d] = x;\n }\n\n let mut val = function(point);\n for d in 0..DIM\n {\n let range = interval[d][1] - interval[d][0];\n let dx = range / S::from(resolution - 1).unwrap();\n let t = S::from(xi[d]).unwrap() / S::from(resolution - 1).unwrap();\n let xp = t * S::from(2).unwrap() - S::from(1).unwrap();\n\n val *= fourier_basis(xp, basis_index[d]) * trapezoidal_weight(xi[d]) * dx\n / fourier_norm_on_standard_interval(basis_index[d]);\n }\n\n res += val\n }\n\n res\n}\n\npub fn fourier_norm_on_standard_interval<S: RealField>(basis_index: usize) -> S\n{\n // Only for the very first function (constant) is the norm different.\n if basis_index == 0\n {\n S::from(f64::sqrt(2.)).unwrap()\n }\n else\n {\n S::from(1).unwrap()\n }\n}\n\npub fn fourier_basis<S: RealField>(t: S, basis_index: usize) -> S\n{\n let pi = S::from(PI).unwrap();\n\n let n = basis_index / 2;\n if basis_index % 2 == 0\n {\n ((t * pi) * S::from(n).unwrap()).cos()\n }\n else\n {\n ((t * pi) * S::from(n + 1).unwrap()).sin()\n }\n}\n\n// test\n let test = fourier_projection(\n |[x, y, z]| (PI * x).cos(),\n [[-1., 1.]; 3],\n [2, 0, 0],\n 100,\n );\n\nI was hoping someone could point out where I made a mistake.
\n", "question_id": 45285, "question_license": "CC BY-SA 4.0", "question_score": 0, "question_text": "Math preamble\n\n\n\n\nI am trying to create a functional basis for $[-1, 1]^3$ in $\\mathbb{R}^3$. To this effect I take the real expression of the fourier basis and index it with an integer such that\n\n\n\n\n$$\\phi_i(x) = \\cos(\\pi n/2 x)$$\n\n\n\n\nif $i$ is even and\n\n\n\n\n$$\\phi_i(x) = \\sin(\\pi [(n/2) + 1] x)$$\n\n\n\n\nif $i$ is odd.\n\n\n\n\nThen I normalize them, so for simplicity of writing, assume $\\phi_i$ is the normalized version of the function.\n\n\n\n\nWith that definition I create the basis through the tensor product.\n\n\n\n\n$$\\Phi_{i,j,k}(x, y, z) = \\phi_i(x) \\phi_j(y) \\phi_k(z)$$\n\n\n\n\nAlgorithm\n\n\n\n\nNow to render the above basis computable I am only dealing with triplets such that $i + j + k \\leq N$ for some integer $N$.\n\n\n\n\nI am using the trapezoidal rule (also extended through the tensor product) in order to compute integrals, so\n\n\n\n\n$$\\int_\\Omega f(X) \\Phi_{i, j, k}(X) dV \\approx \\sum w_l w_m w_n f(X_{l, m, n})) \\Phi_{i, j, k}(X_{l, m, n}) \\Delta x \\Delta y \\Delta z$$\n\n\n\n\nwhere $w_i$ refer to the weights from the trapezoidal rule. 0.5 at the margins and 1 in the interior.\n\n\n\n\nUsing the above I am projecting different functions onto the discretized basis and then reconstructing them to see the accuracy.\n\n\n\n\nExperiments\n\n\n\n\nI am testing my code and I am noticing discrepancies, for example. I am trying to project $f(x, y, z) = \\cos(\\pi x)$ onto $\\Phi_{2, 0, 0}$\n\n\n\n\nFrom the original definition you will notice that $\\Phi_{2, 0, 0}$ should be $\\cos(\\pi x) / \\sqrt{2}$\n\n\n\n\nSo my expectation is that I am computing:\n\n\n\n\n$$\\int^1_{-1}\\int^1_{-1}\\int^1_{-1} \\frac{\\cos^2(\\pi x)}{\\sqrt{2}} dx dy dz \\approx 2.83$$\n\n\n\n\nHowever, what I am getting is\n\n\n\n\n1.9999999999967393\n\n\n\n\n\nThis is my code (written in rust):\n\n\n\n\nfn fourier_projectionAn efficient way to compute $\\sin(kx)$ in the context of iteration over $k$ is to make use of the recursive formula $\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$.
\nHowever, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some quick experiments indicate that this would be the case here.
\nThe issue of subtractive cancellation can be largely mitigated by the use of a fused multiply-add operation, or FMA. This operation first computes the full, unrounded, product $ab$ before applying the addition of $c$, finally returning the final result $ab+c$ with a single rounding. This operation is supported in many programming environments as a function fma() for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.
However, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to approximately emulate it by computing $ab+c$ at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.
\nWith FMA support, one computes $\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$.
\n", "answer_id": 45293, "answer_text": "An efficient way to compute $\\sin(kx)$ in the context of iteration over $k$ is to make use of the recursive formula $\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$.\n\n\n\n\nHowever, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some quick experiments indicate that this would be the case here.\n\n\n\n\nThe issue of subtractive cancellation can be largely mitigated by the use of a fused multiply-add operation, or FMA. This operation first computes the full, unrounded, product $ab$ before applying the addition of $c$, finally returning the final result $ab+c$ with a single rounding. This operation is supported in many programming environments as a function fma() for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.\n\n\n\n\nHowever, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to approximately emulate it by computing $ab+c$ at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.\n\n\n\n\nWith FMA support, one computes $\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$.", "answer_url": "https://scicomp.stackexchange.com/a/45293", "author": "njuffa", "author_url": "https://scicomp.stackexchange.com/users/20458/njuffa", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-26T23:33:21+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": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "njuffa", "profile_url": "https://scicomp.stackexchange.com/users/20458/njuffa", "user_type": "registered"}, "created_at": "2025-11-26T23:33:21+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "B6ACA9A9-61E5-4827-8876-77505A1EE621", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B6ACA9A9-61E5-4827-8876-77505A1EE621/view-source"}], "score": 4, "updated_at": "2025-11-26T23:33:21+00:00"}, {"answer_html": "One idea would be to use part of the series expansion of $sin(x)$ for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.
\nThat way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of $sin(x)$ as before.
\n\\begin{align}\n\\sin(x) &= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}
\nNote that the expansion looses precision the further away you are from 0.
\n", "answer_id": 45294, "answer_text": "One idea would be to use part of the series expansion of $sin(x)$ for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.\n\n\n\n\nThat way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of $sin(x)$ as before.\n\n\n\n\n\\begin{align}\n\\sin(x) &= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}\n\n\n\n\nNote that the expansion looses precision the further away you are from 0.", "answer_url": "https://scicomp.stackexchange.com/a/45294", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-27T07:31:18+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": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-27T07:31:18+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "968C67F8-16E6-40D8-80A4-8E5335D3FC2C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/968C67F8-16E6-40D8-80A4-8E5335D3FC2C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-27T07:36:23+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "1885B799-B6E4-4653-BEFB-37E50B86F7E6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/1885B799-B6E4-4653-BEFB-37E50B86F7E6/view-source"}], "score": 2, "updated_at": "2025-11-27T07:36:23+00:00"}], "product": "code_qa", "question": "I have this recurrence formula for $\\pi$ with convergence order $2m+1$:\n\n\n\n\n$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$\n\n\n\n\nFor example, let $m=2$. The recurrence is:\n$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$\n\n\n\n\nAfter four iterations, $\\pi$ is accurate to $761$ digits:\n\n\n\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi:\", mp.nstr(x, 1000))\nprint(f\"Time Taken: {end - start:.6f} seconds\")\n\n\n\n\n\nHowever, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.\n\n\n\n\nQuestion\n\n\n\n\nAre there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?\n\n\n\n\nUpdate\n\n\n\n\nBased on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of $\\sin$, one of $\\cos$, and a polynomial\nevaluation:\n\n\n\n\n$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$\n\n\n\n\nThanks!", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45291", "selected_answer": {"answer_html": "Given the recurrence\n$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$
\nWe can use the Chebyshev polynomial of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$
\nPlugging $n = k-1$ into this definition gives\n$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$
\nTherefore, the iteration can be written equivalently as\n$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$\nwith\n$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$
\nand
\n$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$
\nTherefore, the new iteration can be written as\n$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$
\nwhere $P_m$ is the polynomial\n$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$
\nSo instead of computing $\\sin(k x_n)$ for every $k$, we can:
\nWe start from the Chebyshev representation for $m=5$:\n$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$\nwith\n$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$\nand\n$$\n\\begin{aligned}\nU_0(t) &= 1,\\\\\nU_1(t) &= 2t,\\\\\nU_2(t) &= 4t^2 - 1,\\\\\nU_3(t) &= 8t^3 - 4t,\\\\\nU_4(t) &= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$
\nThus\n$$\n\\begin{aligned}\nP_5(t)\n&= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$
\nSimplifying each term:\n$$\n\\begin{aligned}\nP_5(t)\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$
\nNow collect like powers of $t$.
\n$t^4$ term:\n$$\n\\frac{8}{315}t^4.\n$$
\n$t^3$ term:\n$$\n\\frac{10}{63}t^3.\n$$
\n$t^2$ term:\n$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$
\n$t^1$ term:\n$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$
\nConstant term:\n$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$
\nSo we obtain\n$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$
\nFactoring out $\\frac{1}{315}$ gives the compact form\n$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$
\nFor $m = 5$ we have\n$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$\nand the iteration\n$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$
\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n """\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n """\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint("Approximate pi (m=5):")\nprint(mp.nstr(x, 1000))\nprint(f"\\nTime Taken: {end - start:.6f} seconds")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint("\\nError x - pi:")\nprint(mp.nstr(err, 5))\n\nApproximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199
\nTime Taken: 0.001180 seconds
\nError x - pi:\n0.0
\n", "answer_id": 45295, "answer_text": "Given the recurrence\n$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$\n\n\n\n\nWe can use the Chebyshev polynomial (https://en.wikipedia.org/wiki/Chebyshev_polynomials) of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$\n\n\n\n\nPlugging $n = k-1$ into this definition gives\n$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$\n\n\n\n\nTherefore, the iteration can be written equivalently as\n$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$\nwith\n$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$\n\n\n\n\nand\n\n\n\n\n$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nTherefore, the new iteration can be written as\n$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$\n\n\n\n\nwhere $P_m$ is the polynomial\n$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nSo instead of computing $\\sin(k x_n)$ for every $k$, we can:\n\n\n\n\n\nCompute $s = \\sin(x_n)$ once,\n\n\n\n\nCompute $c = \\cos(x_n)$ once,\n\n\n\n\nEvaluate the polynomial $P_m(c)$.\n\n\n\n\n\nExample\n\n\n\n\nWe start from the Chebyshev representation for $m=5$:\n$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$\nwith\n$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$\nand\n$$\n\\begin{aligned}\nU_0(t) &= 1,\\\\\nU_1(t) &= 2t,\\\\\nU_2(t) &= 4t^2 - 1,\\\\\nU_3(t) &= 8t^3 - 4t,\\\\\nU_4(t) &= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$\n\n\n\n\nThus\n$$\n\\begin{aligned}\nP_5(t)\n&= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$\n\n\n\n\nSimplifying each term:\n$$\n\\begin{aligned}\nP_5(t)\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$\n\n\n\n\nNow collect like powers of $t$.\n\n\n\n\n$t^4$ term:\n$$\n\\frac{8}{315}t^4.\n$$\n\n\n\n\n$t^3$ term:\n$$\n\\frac{10}{63}t^3.\n$$\n\n\n\n\n$t^2$ term:\n$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$\n\n\n\n\n$t^1$ term:\n$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$\n\n\n\n\nConstant term:\n$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$\n\n\n\n\nSo we obtain\n$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$\n\n\n\n\nFactoring out $\\frac{1}{315}$ gives the compact form\n$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$\n\n\n\n\nTest Case\n\n\n\n\nFor $m = 5$ we have\n$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$\nand the iteration\n$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n \"\"\"\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n \"\"\"\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi (m=5):\")\nprint(mp.nstr(x, 1000))\nprint(f\"\\nTime Taken: {end - start:.6f} seconds\")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(\"\\nError x - pi:\")\nprint(mp.nstr(err, 5))\n\n\n\n\n\n\n\n\nApproximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199\n\n\n\n\nTime Taken: 0.001180 seconds\n\n\n\n\nError x - pi:\n0.0", "answer_url": "https://scicomp.stackexchange.com/a/45295", "author": "vengy", "author_url": "https://scicomp.stackexchange.com/users/56070/vengy", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-27T16:01:03+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": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T16:01:03+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "12F528C5-3339-4BD9-82C4-1F98C0E30ABD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F528C5-3339-4BD9-82C4-1F98C0E30ABD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T16:46:02+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "94F6BA8F-8639-48FE-844B-374EC8092EC7", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/94F6BA8F-8639-48FE-844B-374EC8092EC7/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T17:19:25+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C72508F8-E2C5-4479-B135-70BE30A2F07C", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C72508F8-E2C5-4479-B135-70BE30A2F07C/view-source"}], "score": 7, "updated_at": "2025-11-27T17:19:25+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "test", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "An efficient way to compute $\\sin(kx)$ in the context of iteration over $k$ is to make use of the recursive formula $\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$.
\nHowever, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some quick experiments indicate that this would be the case here.
\nThe issue of subtractive cancellation can be largely mitigated by the use of a fused multiply-add operation, or FMA. This operation first computes the full, unrounded, product $ab$ before applying the addition of $c$, finally returning the final result $ab+c$ with a single rounding. This operation is supported in many programming environments as a function fma() for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.
However, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to approximately emulate it by computing $ab+c$ at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.
\nWith FMA support, one computes $\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$.
\n", "answer_id": 45293, "answer_text": "An efficient way to compute $\\sin(kx)$ in the context of iteration over $k$ is to make use of the recursive formula $\\sin(kx) = 2 \\cos x \\sin((k-1)x) - \\sin((k-2)x)$.\n\n\n\n\nHowever, when performing this computation in fixed-precision floating-point arithmetic there is a caveat, in that accuracy can be lost due to subtractive cancellation. Some quick experiments indicate that this would be the case here.\n\n\n\n\nThe issue of subtractive cancellation can be largely mitigated by the use of a fused multiply-add operation, or FMA. This operation first computes the full, unrounded, product $ab$ before applying the addition of $c$, finally returning the final result $ab+c$ with a single rounding. This operation is supported in many programming environments as a function fma() for precisions defined by IEEE-754, and as such is supported in hardware for most modern processor architectures such as x86-64 and ARM64.\n\n\n\n\nHowever, I am not personally aware of an arbitrary-precision library with support for FMA. One could try to approximately emulate it by computing $ab+c$ at twice the current working precision and then rounding to working precision. This would still leave an issue of double rounding, which could likely be tolerated in the given context.\n\n\n\n\nWith FMA support, one computes $\\sin(kx)=\\mathrm{fma}(2\\cos x,\\sin((k-1)x),-\\sin((k-2)x))$.", "answer_url": "https://scicomp.stackexchange.com/a/45293", "author": "njuffa", "author_url": "https://scicomp.stackexchange.com/users/20458/njuffa", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-26T23:33:21+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": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "njuffa", "profile_url": "https://scicomp.stackexchange.com/users/20458/njuffa", "user_type": "registered"}, "created_at": "2025-11-26T23:33:21+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "B6ACA9A9-61E5-4827-8876-77505A1EE621", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B6ACA9A9-61E5-4827-8876-77505A1EE621/view-source"}], "score": 4, "updated_at": "2025-11-26T23:33:21+00:00"}, {"answer_html": "One idea would be to use part of the series expansion of $sin(x)$ for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.
\nThat way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of $sin(x)$ as before.
\n\\begin{align}\n\\sin(x) &= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}
\nNote that the expansion looses precision the further away you are from 0.
\n", "answer_id": 45294, "answer_text": "One idea would be to use part of the series expansion of $sin(x)$ for the first couple of iterations. That is what the computer does internally anyway, but there you can control the order of approximation (how many terms of the expansion you consider and therefore how much compute you use). In iterative methods the first iterations often only have to put your solution in the general vicinity of the solution, being refined in the later stages.\n\n\n\n\nThat way you spent less compute on the rough parts, and only when you are close to convergence you use the costly full-precision approximation of $sin(x)$ as before.\n\n\n\n\n\\begin{align}\n\\sin(x) &= x - \\frac{x^3}{3!} + \\frac{x^5}{5!} - \\frac{x^7}{7!} + \\cdots \\\\\n &= \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n+1)!}x^{2n+1}\n\\end{align}\n\n\n\n\nNote that the expansion looses precision the further away you are from 0.", "answer_url": "https://scicomp.stackexchange.com/a/45294", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-27T07:31:18+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": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-27T07:31:18+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "968C67F8-16E6-40D8-80A4-8E5335D3FC2C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/968C67F8-16E6-40D8-80A4-8E5335D3FC2C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2025-11-27T07:36:23+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "1885B799-B6E4-4653-BEFB-37E50B86F7E6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/1885B799-B6E4-4653-BEFB-37E50B86F7E6/view-source"}], "score": 2, "updated_at": "2025-11-27T07:36:23+00:00"}, {"answer_html": "Given the recurrence\n$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$
\nWe can use the Chebyshev polynomial of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$
\nPlugging $n = k-1$ into this definition gives\n$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$
\nTherefore, the iteration can be written equivalently as\n$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$\nwith\n$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$
\nand
\n$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$
\nTherefore, the new iteration can be written as\n$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$
\nwhere $P_m$ is the polynomial\n$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$
\nSo instead of computing $\\sin(k x_n)$ for every $k$, we can:
\nWe start from the Chebyshev representation for $m=5$:\n$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$\nwith\n$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$\nand\n$$\n\\begin{aligned}\nU_0(t) &= 1,\\\\\nU_1(t) &= 2t,\\\\\nU_2(t) &= 4t^2 - 1,\\\\\nU_3(t) &= 8t^3 - 4t,\\\\\nU_4(t) &= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$
\nThus\n$$\n\\begin{aligned}\nP_5(t)\n&= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$
\nSimplifying each term:\n$$\n\\begin{aligned}\nP_5(t)\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$
\nNow collect like powers of $t$.
\n$t^4$ term:\n$$\n\\frac{8}{315}t^4.\n$$
\n$t^3$ term:\n$$\n\\frac{10}{63}t^3.\n$$
\n$t^2$ term:\n$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$
\n$t^1$ term:\n$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$
\nConstant term:\n$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$
\nSo we obtain\n$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$
\nFactoring out $\\frac{1}{315}$ gives the compact form\n$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$
\nFor $m = 5$ we have\n$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$\nand the iteration\n$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$
\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n """\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n """\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint("Approximate pi (m=5):")\nprint(mp.nstr(x, 1000))\nprint(f"\\nTime Taken: {end - start:.6f} seconds")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint("\\nError x - pi:")\nprint(mp.nstr(err, 5))\n\nApproximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199
\nTime Taken: 0.001180 seconds
\nError x - pi:\n0.0
\n", "answer_id": 45295, "answer_text": "Given the recurrence\n$$\nx_{n+1}\n= x_n + \\sum_{k=1}^{m} a_k \\,\\sin(k x_n),\n\\qquad\na_k := (-1)^{m+k}\\,\\frac{1}{k}\\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m}\n\\frac{j^{2}}{k^{2} - j^{2}}.\n$$\n\n\n\n\nWe can use the Chebyshev polynomial (https://en.wikipedia.org/wiki/Chebyshev_polynomials) of the second kind:\n$$\nU_n(\\cos x) = \\frac{\\sin\\bigl((n+1)x\\bigr)}{\\sin x}.\n$$\n\n\n\n\nPlugging $n = k-1$ into this definition gives\n$$\nU_{k-1}(\\cos x)= \\frac{\\sin(kx)}{\\sin x}\\;\\Longrightarrow\\;\n\\sin(kx) = \\sin x \\, U_{k-1}(\\cos x).\n$$\n\n\n\n\nTherefore, the iteration can be written equivalently as\n$$\n\\sum_{k=1}^{m} a_k \\sin(kx)\n= \\sin x \\sum_{k=1}^{m} a_k U_{k-1}(\\cos x)\n= \\sin x \\, P_m(\\cos x),\n$$\nwith\n$$\nP_m(c) := \\sum_{k=1}^{m} a_k \\, U_{k-1}(c),\n$$\n\n\n\n\nand\n\n\n\n\n$$\nU_{k-1}(c)\n= \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nTherefore, the new iteration can be written as\n$$\nx_{n+1}\n= x_n + \\sin(x_n)\\,P_m\\big(\\cos(x_n)\\big),\n$$\n\n\n\n\nwhere $P_m$ is the polynomial\n$$\nP_m(c)\n := \\sum_{k=1}^{m} a_k\n \\sum_{r=0}^{\\left\\lfloor (k-1)/2 \\right\\rfloor}\n (-1)^r\n \\binom{k-1-r}{r}\\,\n (2c)^{\\,k-1-2r}.\n$$\n\n\n\n\nSo instead of computing $\\sin(k x_n)$ for every $k$, we can:\n\n\n\n\n\nCompute $s = \\sin(x_n)$ once,\n\n\n\n\nCompute $c = \\cos(x_n)$ once,\n\n\n\n\nEvaluate the polynomial $P_m(c)$.\n\n\n\n\n\nExample\n\n\n\n\nWe start from the Chebyshev representation for $m=5$:\n$$\nP_5(t) = \\sum_{k=1}^5 a_k\\,U_{k-1}(t),\n$$\nwith\n$$\na_1 = \\frac{5}{3},\\quad\na_2 = \\frac{10}{21},\\quad\na_3 = \\frac{5}{42},\\quad\na_4 = \\frac{5}{252},\\quad\na_5 = \\frac{1}{630},\n$$\nand\n$$\n\\begin{aligned}\nU_0(t) &= 1,\\\\\nU_1(t) &= 2t,\\\\\nU_2(t) &= 4t^2 - 1,\\\\\nU_3(t) &= 8t^3 - 4t,\\\\\nU_4(t) &= 16t^4 - 12t^2 + 1.\n\\end{aligned}\n$$\n\n\n\n\nThus\n$$\n\\begin{aligned}\nP_5(t)\n&= a_1 U_0(t) + a_2 U_1(t) + a_3 U_2(t) + a_4 U_3(t) + a_5 U_4(t)\\\\[4pt]\n&= \\frac{5}{3}\\cdot 1\n + \\frac{10}{21}\\cdot (2t)\n + \\frac{5}{42}\\cdot (4t^2 - 1)\n + \\frac{5}{252}\\cdot (8t^3 - 4t)\n + \\frac{1}{630}\\cdot (16t^4 - 12t^2 + 1).\n\\end{aligned}\n$$\n\n\n\n\nSimplifying each term:\n$$\n\\begin{aligned}\nP_5(t)\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{20}{42}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{40}{252}t^3 - \\frac{20}{252}t\\right)\n + \\left(\\frac{16}{630}t^4 - \\frac{12}{630}t^2 + \\frac{1}{630}\\right)\\\\[4pt]\n&= \\frac{5}{3}\n + \\frac{20}{21}t\n + \\left(\\frac{10}{21}t^2 - \\frac{5}{42}\\right)\n + \\left(\\frac{10}{63}t^3 - \\frac{5}{63}t\\right)\n + \\left(\\frac{8}{315}t^4 - \\frac{2}{105}t^2 + \\frac{1}{630}\\right).\n\\end{aligned}\n$$\n\n\n\n\nNow collect like powers of $t$.\n\n\n\n\n$t^4$ term:\n$$\n\\frac{8}{315}t^4.\n$$\n\n\n\n\n$t^3$ term:\n$$\n\\frac{10}{63}t^3.\n$$\n\n\n\n\n$t^2$ term:\n$$\n\\frac{10}{21}t^2 - \\frac{2}{105}t^2\n= \\left(\\frac{10}{21} - \\frac{2}{105}\\right)t^2\n= \\left(\\frac{50}{105} - \\frac{2}{105}\\right)t^2\n= \\frac{48}{105}t^2\n= \\frac{16}{35}t^2.\n$$\n\n\n\n\n$t^1$ term:\n$$\n\\frac{20}{21}t - \\frac{5}{63}t\n= \\left(\\frac{20}{21} - \\frac{5}{63}\\right)t\n= \\left(\\frac{60}{63} - \\frac{5}{63}\\right)t\n= \\frac{55}{63}t.\n$$\n\n\n\n\nConstant term:\n$$\n\\frac{5}{3} - \\frac{5}{42} + \\frac{1}{630}\n= \\frac{1050}{630} - \\frac{75}{630} + \\frac{1}{630}\n= \\frac{976}{630}\n= \\frac{488}{315}.\n$$\n\n\n\n\nSo we obtain\n$$\nP_5(t)\n= \\frac{8}{315}t^4\n+ \\frac{10}{63}t^3\n+ \\frac{16}{35}t^2\n+ \\frac{55}{63}t\n+ \\frac{488}{315}.\n$$\n\n\n\n\nFactoring out $\\frac{1}{315}$ gives the compact form\n$$\nP_5(t)\n= \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr).\n$$\n\n\n\n\nTest Case\n\n\n\n\nFor $m = 5$ we have\n$$\nP_5(t) = \\frac{1}{315}\\bigl(8t^4 + 50t^3 + 144t^2 + 275t + 488\\bigr),\n$$\nand the iteration\n$$\nx_{n+1} = x_n + \\sin(x_n)\\,P_5(\\cos x_n).\n$$\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000 # 1000 digits of precision\n\n# m = 5 polynomial:\n# P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488)\n\ndef step_m5(x):\n \"\"\"\n m = 5 iteration:\n x_{n+1} = x_n + sin(x_n) * P5(cos(x_n))\n\n where\n P5(t) = (1/315) * (8 t^4 + 50 t^3 + 144 t^2 + 275 t + 488).\n \"\"\"\n s = mp.sin(x)\n c = mp.cos(x)\n P5 = (mp.mpf(1) / 315) * (8*c**4 + 50*c**3 + 144*c**2 + 275*c + 488)\n return x + s * P5\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 4): # a few iterations are enough because order = 11\n x = step_m5(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi (m=5):\")\nprint(mp.nstr(x, 1000))\nprint(f\"\\nTime Taken: {end - start:.6f} seconds\")\n\n# Show how close we are to the true mp.pi\nerr = x - mp.pi\nprint(\"\\nError x - pi:\")\nprint(mp.nstr(err, 5))\n\n\n\n\n\n\n\n\nApproximate pi (m=5):\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420199\n\n\n\n\nTime Taken: 0.001180 seconds\n\n\n\n\nError x - pi:\n0.0", "answer_url": "https://scicomp.stackexchange.com/a/45295", "author": "vengy", "author_url": "https://scicomp.stackexchange.com/users/56070/vengy", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-11-27T16:01:03+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": 45291, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T16:01:03+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "12F528C5-3339-4BD9-82C4-1F98C0E30ABD", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F528C5-3339-4BD9-82C4-1F98C0E30ABD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T16:46:02+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "94F6BA8F-8639-48FE-844B-374EC8092EC7", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/94F6BA8F-8639-48FE-844B-374EC8092EC7/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-27T17:19:25+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "C72508F8-E2C5-4479-B135-70BE30A2F07C", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C72508F8-E2C5-4479-B135-70BE30A2F07C/view-source"}], "score": 7, "updated_at": "2025-11-27T17:19:25+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Chebyshev_polynomials"], "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": "vengy", "question_author_url": "https://scicomp.stackexchange.com/users/56070/vengy", "question_author_user_type": "registered", "question_created_at": "2025-11-26T20:12:50+00:00", "question_html": "I have this recurrence formula for $\\pi$ with convergence order $2m+1$:
\n$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$
\nFor example, let $m=2$. The recurrence is:\n$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$
\nAfter four iterations, $\\pi$ is accurate to $761$ digits:
\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131
\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint("Approximate pi:", mp.nstr(x, 1000))\nprint(f"Time Taken: {end - start:.6f} seconds")\n\nHowever, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.
\nAre there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?
\nBased on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of $\\sin$, one of $\\cos$, and a polynomial\nevaluation:
\n$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$
\nThanks!
\n", "question_id": 45291, "question_license": "CC BY-SA 4.0", "question_score": 6, "question_text": "I have this recurrence formula for $\\pi$ with convergence order $2m+1$:\n\n\n\n\n$$\nx_{n+1} = x_n + \\sum_{k=1}^{m} \\left[ (-1)^{m+k} \\cdot \\frac{1}{k} \\prod_{\\substack{j=1 \\\\ j \\ne k}}^{m} \\frac{j^{2}}{k^{2} - j^{2}} \\right] \\sin(k x_n).\n$$\n\n\n\n\nFor example, let $m=2$. The recurrence is:\n$$\nx_{n+1}=x_n+ \\frac{4}{3}\\,\\sin(x_n)+ \\frac{1}{6}\\,\\sin(2x_n).\n$$\n\n\n\n\nAfter four iterations, $\\pi$ is accurate to $761$ digits:\n\n\n\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211343082259728864581849972469526130405086109419964771039095301381998678247215175696280484782896433126351623817501296615376345723979560286352234586232286130523901015245593954685898250839054728621411070507501722658851574741380974002315574736131\n\n\n\n\nfrom mpmath import mp\nimport time\n\nmp.dps = 1000\n\nc21 = mp.mpf(4) / 3\nc22 = mp.mpf(1) / 6\n\ndef step_m2(x):\n return x + c21 * mp.sin(x) + c22 * mp.sin(2*x)\n\n# initial value x0 = 3\nx = mp.mpf(3)\n\nstart = time.perf_counter()\nfor n in range(1, 5):\n x = step_m2(x)\nend = time.perf_counter()\n\nprint(\"Approximate pi:\", mp.nstr(x, 1000))\nprint(f\"Time Taken: {end - start:.6f} seconds\")\n\n\n\n\n\nHowever, evaluating $\\sin(k x_n)$ at high precision becomes very slow, especially for large $m$.\n\n\n\n\nQuestion\n\n\n\n\nAre there efficient approximations or methods for computing $\\sin(k x_n)$ in iterative algorithms?\n\n\n\n\nUpdate\n\n\n\n\nBased on the answers, the iteration has been optimized so that each step\nrequires only one evaluation of $\\sin$, one of $\\cos$, and a polynomial\nevaluation:\n\n\n\n\n$$\nx_{n+1}\n= x_n\n+ \\sin(x_n)\\,\n \\sum_{r=0}^{m-1} \\frac{r!}{(2r+1)!!}\\,(\\cos x_n + 1)^r.\n$$\n\n\n\n\nThanks!", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-26T20:12:50+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "E62E0A8C-8E01-4C14-B7C2-285A89EF1CC1", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E62E0A8C-8E01-4C14-B7C2-285A89EF1CC1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vengy", "profile_url": "https://scicomp.stackexchange.com/users/56070/vengy", "user_type": "registered"}, "created_at": "2025-11-28T14:23:44+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "38B727A1-9571-4258-B34C-572EA2A4CA69", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/38B727A1-9571-4258-B34C-572EA2A4CA69/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-12-27T13:30:00+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "26017B5A-7A85-4984-8B51-2083CED200D4", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/26017B5A-7A85-4984-8B51-2083CED200D4/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45291/efficient-computation-of-sink-x-n-in-iterative-algorithms", "split": "test", "split_group": "1bfd52fa7b070e0b5559d8e3ecd78760d9854e9302a5ee1988f94d4b3224295f", "tags": ["optimization", "numerics"], "thread_id": "scicomp:45291", "title": "Efficient computation of $\\sin(k x_n)$ in iterative algorithms"}} {"accepted_answer": {"answer_html": "The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.
At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.
\n", "answer_id": 45312, "answer_text": "Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.", "answer_url": "https://scicomp.stackexchange.com/a/45312", "author": "Federico Poloni", "author_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-12-13T10:03:37+00:00", "is_accepted": true, "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": 45311, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-13T10:03:37+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFC0D245-EF3B-4C7B-9150-73518AFD2D2A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-18T09:34:32+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "74B8DDDA-9B0B-40CA-BE67-18501D69153F", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}], "score": 6, "updated_at": "2025-12-18T09:34:32+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45311, "sha256": "ad56fe2c0260b1f75acb06603952a687d5a2487cdcb7f14fa35ca2ddbe95dbe9", "source_url": "https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different"}, {"block_index": 1, "code_text": "U_, s_, Vt_ = np.linalg.svd(A)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45311, "sha256": "c8237ba622cf113feb706a6dd46de44c41ac2edd5ac548cd0e9562bf82e74fa5", "source_url": "https://scicomp.stackexchange.com/questions/45311/computing-the-svd-manually-and-using-python-why-are-the-signs-different"}], "other_answers": [], "product": "code_qa", "question": "Recently, I have been learning singular value decomposition (SVD). I want to compute SVD manually with NumPy . Here is my code\n\n\n\n\nimport numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n\n\n\n\n\nI am validating my code with the svd method that comes with numpy\n\n\n\n\nU_, s_, Vt_ = np.linalg.svd(A)\n\n\n\n\n\nwhen I compare it, s_ = M, Vt_ = Vt but for U it does not equal to U_. See the result for U (my code), where I get:\n\n\n\n\narray([[-0.17259857, -0.89640564, 0.40824829],\n [-0.50818671, -0.27400657, -0.81649658],\n [-0.84377485, 0.3483925 , 0.40824829]])\n\n\n\n\n\nbut for U_ (numpy code) it gives\n\n\n\n\narray([[-0.17259857, 0.89640564, 0.40824829],\n [-0.50818671, 0.27400657, -0.81649658],\n [-0.84377485, -0.3483925 , 0.40824829]])\n\n\n\n\n\nthe second column of the U and U_ are not same. What did I wrong in my code?", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45311", "selected_answer": {"answer_html": "The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.
At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.
\n", "answer_id": 45312, "answer_text": "Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.", "answer_url": "https://scicomp.stackexchange.com/a/45312", "author": "Federico Poloni", "author_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-12-13T10:03:37+00:00", "is_accepted": true, "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": 45311, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-13T10:03:37+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFC0D245-EF3B-4C7B-9150-73518AFD2D2A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-18T09:34:32+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "74B8DDDA-9B0B-40CA-BE67-18501D69153F", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}], "score": 6, "updated_at": "2025-12-18T09:34:32+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45312, "answers": [{"answer_html": "The standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.
At the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.
\n", "answer_id": 45312, "answer_text": "Eigenvector matrices are not unique.\n\n\n\n\nThe standard computation $AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$ tells you that $U$ is an eigenvector matrix of $AA^*$. np.linalg.eig computes an eigenvector matrix of $AA^*$. Those two matrices do not have to be the same, even after reordering the eigenvalues.\n\n\n\n\nAt the very least you have a sign ambiguity, as you already discovered; but if there are multiple eigenvalues there could be even more degrees of freedom. For instance, take a $n\\times n$ orthogonal as $A$: then $U=V=I$ are valid eigenvector matrices for $AA^*=I$ and $A^*A=I$, but (apart from the very special case $A=I$) $U \\cdot I \\cdot V^*$ is not an SVD of $A$. So you cannot recover an SVD by computing $U$ and $V$ from the two eigenvalue problems with $AA^*$ and $A^*A$.", "answer_url": "https://scicomp.stackexchange.com/a/45312", "author": "Federico Poloni", "author_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2025-12-13T10:03:37+00:00", "is_accepted": true, "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": 45311, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-13T10:03:37+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "BFC0D245-EF3B-4C7B-9150-73518AFD2D2A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BFC0D245-EF3B-4C7B-9150-73518AFD2D2A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Federico Poloni", "profile_url": "https://scicomp.stackexchange.com/users/4405/federico-poloni", "user_type": "registered"}, "created_at": "2025-12-18T09:34:32+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "74B8DDDA-9B0B-40CA-BE67-18501D69153F", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/74B8DDDA-9B0B-40CA-BE67-18501D69153F/view-source"}], "score": 6, "updated_at": "2025-12-18T09:34:32+00:00"}], "domain": "computational_science", "external_links": [], "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": "Argha Nilanjon Nondi", "question_author_url": "https://scicomp.stackexchange.com/users/56165/argha-nilanjon-nondi", "question_author_user_type": "registered", "question_created_at": "2025-12-12T11:42:59+00:00", "question_html": "Recently, I have been learning singular value decomposition (SVD). I want to compute SVD manually with NumPy . Here is my code
\nimport numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.argsort()[::-1]\nsorted_eigenvalues_AAt = eigenvalues_AAt[idx_descending]\nsorted_eigenvectors_AAt = eigenvectors_AAt[:, idx_descending]\n\nU=sorted_eigenvectors_AAt\n\nidx_descending = eigenvalues_AtA.argsort()[::-1]\nsorted_eigenvalues_AtA = eigenvalues_AtA[idx_descending]\nsorted_eigenvectors_AtA = eigenvectors_AtA[:, idx_descending]\n\nVt=sorted_eigenvectors_AtA.T\n\nsingular_values_AtA = np.sqrt(np.flip(np.sort(eigenvalues_AtA)))\nM = np.zeros(A.shape)\nmin_dim = min(A.shape)\nM[:min_dim, :min_dim] = np.diag(singular_values_AtA)\nsvd=np.matmul(U,np.matmul(M,Vt))\n\nI am validating my code with the svd method that comes with numpy
\nU_, s_, Vt_ = np.linalg.svd(A)\n\nwhen I compare it, s_ = M, Vt_ = Vt but for U it does not equal to U_. See the result for U (my code), where I get:
array([[-0.17259857, -0.89640564, 0.40824829],\n [-0.50818671, -0.27400657, -0.81649658],\n [-0.84377485, 0.3483925 , 0.40824829]])\n\nbut for U_ (numpy code) it gives
\narray([[-0.17259857, 0.89640564, 0.40824829],\n [-0.50818671, 0.27400657, -0.81649658],\n [-0.84377485, -0.3483925 , 0.40824829]])\n\nthe second column of the U and U_ are not same. What did I wrong in my code?
This implementation of the trust region method is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp which fits your situation closely.
\nIt accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.
\nfrom functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n with 4167 stored elements and shape (350, 300)>]\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-3.314e+02, 4.310e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791156981\n constr_violation: 6.350475700855895e-14\n execution_time: 0.10921216011047363\n tr_radius: 4.682990630409006e-09\n constr_penalty: 19.590428780507548\n niter: 15\n\nYou may be able to do better if you warm-start the optimizer with a feasible solution. This can be found through a sparse Moore-Penrose-like solver:
\n (\n x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var,\n ) = sp.linalg.lsqr(A, b)\n\n result = minimize(\n method='trust-constr', x0=x,\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.86556221833825\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 11\n nfev: 3\n njev: 2\n nhev: 2\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n with 4167 stored elements and shape (350, 300)>]\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-1.682e+03, 4.026e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791155749\n constr_violation: 7.860379014346108e-14\n execution_time: 0.047506093978881836\n tr_radius: 1.0000000000000005e-09\n constr_penalty: 29.017471116474994\n niter: 11\n\n", "answer_id": 45314, "answer_text": "This implementation of the trust region method (https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html) is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp (https://github.com/scipy/scipy/blob/8b0782d06d69b568b9a6db1a488dc52f93c0a066/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py#L17) which fits your situation closely.\n\n\n\n\nIt accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.\n\n\n\n\nfrom functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [This implementation of the trust region method is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp which fits your situation closely.
\nIt accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.
\nfrom functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n with 4167 stored elements and shape (350, 300)>]\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-3.314e+02, 4.310e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791156981\n constr_violation: 6.350475700855895e-14\n execution_time: 0.10921216011047363\n tr_radius: 4.682990630409006e-09\n constr_penalty: 19.590428780507548\n niter: 15\n\nYou may be able to do better if you warm-start the optimizer with a feasible solution. This can be found through a sparse Moore-Penrose-like solver:
\n (\n x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var,\n ) = sp.linalg.lsqr(A, b)\n\n result = minimize(\n method='trust-constr', x0=x,\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.86556221833825\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 11\n nfev: 3\n njev: 2\n nhev: 2\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n with 4167 stored elements and shape (350, 300)>]\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-1.682e+03, 4.026e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791155749\n constr_violation: 7.860379014346108e-14\n execution_time: 0.047506093978881836\n tr_radius: 1.0000000000000005e-09\n constr_penalty: 29.017471116474994\n niter: 11\n\n", "answer_id": 45314, "answer_text": "This implementation of the trust region method (https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html) is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp (https://github.com/scipy/scipy/blob/8b0782d06d69b568b9a6db1a488dc52f93c0a066/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py#L17) which fits your situation closely.\n\n\n\n\nIt accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.\n\n\n\n\nfrom functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [This implementation of the trust region method is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp which fits your situation closely.
\nIt accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.
\nfrom functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n with 4167 stored elements and shape (350, 300)>]\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-3.314e+02, 4.310e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791156981\n constr_violation: 6.350475700855895e-14\n execution_time: 0.10921216011047363\n tr_radius: 4.682990630409006e-09\n constr_penalty: 19.590428780507548\n niter: 15\n\nYou may be able to do better if you warm-start the optimizer with a feasible solution. This can be found through a sparse Moore-Penrose-like solver:
\n (\n x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var,\n ) = sp.linalg.lsqr(A, b)\n\n result = minimize(\n method='trust-constr', x0=x,\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.86556221833825\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 11\n nfev: 3\n njev: 2\n nhev: 2\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [<Compressed Sparse Row sparse array of dtype 'float64'\n with 4167 stored elements and shape (350, 300)>]\n constr_nfev: [0]\n constr_njev: [0]\n constr_nhev: [0]\n v: [array([-1.682e+03, 4.026e+02, ..., -9.438e-01,\n 8.593e+00], shape=(350,))]\n method: equality_constrained_sqp\n optimality: 2.220613791155749\n constr_violation: 7.860379014346108e-14\n execution_time: 0.047506093978881836\n tr_radius: 1.0000000000000005e-09\n constr_penalty: 29.017471116474994\n niter: 11\n\n", "answer_id": 45314, "answer_text": "This implementation of the trust region method (https://docs.scipy.org/doc/scipy/reference/optimize.minimize-trustconstr.html) is suitable, at least for the first sizes you quote. Its inner method is equality_constrained_sqp (https://github.com/scipy/scipy/blob/8b0782d06d69b568b9a6db1a488dc52f93c0a066/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py#L17) which fits your situation closely.\n\n\n\n\nIt accepts sparse constraints. The constraints containing linear dependence don't seem to matter. Note the analytic Jacobian is dense but the Hessian is sparse and constant. Convergence in 6 cost function calls isn't bad.\n\n\n\n\nfrom functools import partial\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import minimize, LinearConstraint, check_grad\n\n\ndef sample_data(\n rand: np.random.Generator,\n m: int = 350, m_independent: int = 280, n: int = 300, nnz: int = 10,\n) -> tuple[\n sp.sparray, # Q\n sp.sparray, # A\n np.ndarray, # b\n]:\n # x is an unknown n-vector\n x_hidden = rand.random(size=n)\n\n # Q is a known (n,n) sparse positive semi-definite matrix\n data = rand.random(size=n*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(n)\n ], dtype=np.int32)\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + n*nnz, nnz, dtype=np.int32)\n Q = sp.csr_array((data, indices.ravel(), indptr), shape=(n, n))\n\n data = rand.random(size=m_independent*nnz)\n indices = np.array([\n rand.choice(a=n, size=nnz, replace=False, shuffle=False)\n for _ in range(m_independent)\n ])\n indices.sort(axis=1)\n indptr = np.arange(0, 1 + m_independent*nnz, nnz, dtype=np.int32)\n A_independent = sp.csr_array((data, indices.ravel(), indptr), shape=(m_independent, n))\n\n coefs = sp.csr_array(rand.random(size=(m - m_independent, 2)))\n A_blocks = [\n row @ A_independent[\n rand.integers(low=0, high=m_independent, size=2), :,\n ]\n for row in coefs\n ]\n A_blocks.append(A_independent)\n A = sp.vstack(A_blocks)\n b = A @ x_hidden\n\n return Q, A, b\n\n\ndef cost(x: np.ndarray, Q: sp.sparray) -> float:\n return x @ Q @ x # Scalar\n\n\ndef jacobian(x: np.ndarray, QQT: sp.sparray) -> np.ndarray:\n return x@QQT # dense n-vector\n\n\ndef hessian(x: np.ndarray, QQT: sp.sparray) -> sp.sparray:\n return QQT # n,n sparse matrix\n\n\ndef solve(Q: sp.sparray, A: sp.sparray, b: np.ndarray) -> None:\n QQT = Q + Q.T\n fun = partial(cost, Q=Q)\n jac = partial(jacobian, QQT=QQT)\n hess = partial(hessian, QQT=QQT)\n\n m, n = A.shape\n err = check_grad(fun, jac, np.ones(n))\n assert err < 1e-3\n err = check_grad(jac, hess, np.ones(n))\n assert err < 1e-5\n\n result = minimize(\n method='trust-constr', x0=np.zeros(n),\n fun=fun, jac=jac, hess=hess,\n constraints=LinearConstraint(A=A, lb=b, ub=b),\n options={'factorization_method': 'AugmentedSystem'},\n )\n if not result.success:\n raise ValueError(result.message)\n print(result)\n return result.x\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n Q, A, b = sample_data(rand=rand)\n solve(Q, A, b)\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\n message: `xtol` termination condition is satisfied.\n success: True\n status: 2\n fun: 420.8655622183405\n x: [ 5.530e-01 3.104e-01 ... 6.516e-01 6.497e-01]\n nit: 15\n nfev: 6\n njev: 5\n nhev: 5\n cg_niter: 0\n cg_stop_cond: 1\n grad: [ 7.940e+00 4.136e+00 ... 7.226e+00 7.271e+00]\n lagrangian_grad: [ 2.711e-01 2.216e-01 ... -1.650e-01 6.675e-01]\n constr: [array([ 2.573e+00, 3.197e+00, ..., 2.866e+00,\n 3.016e+00], shape=(350,))]\n jac: [I have a quadratic programming problem\n$$\n\\begin{matrix}\n\\textrm{minimise} & x^TQx \\\\\n\\textrm{subject to} & Ax = b\n\\end{matrix}\n$$\nwhere $x$ is a vector of unknowns, $Q$ is a positive semi-definite matrix, $A$ is a matrix of constraint coefficients, and $b$ is a vector of constraint rhs values. The constraints represented by $Ax=b$ are linearly dependent. To give an idea of the extent of linear dependency, $A$ could be something $350 \\times 300$, so 350 constraints with 300 unknowns, but this reduces to 280 linearly independent constraints. It can be safely assumed that the constraints are consistent and $\\textrm{null}(Q)\\cap\\textrm{null}(A)=\\{0\\}$ such that the problem has a unique solution. I would like to find a way to solve this problem for large and sparse $Q$ and $A$. I have attempted the following.
\nFirst, I tried reducing $A$ to only have linearly independent rows, denoted $A_R$, and solving the KKT system\n$$\n\\begin{bmatrix}\nQ & A_R^T \\\\\nA_R & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nI reduced $A$ to linearly independent rows by performing a sparse rank-revealing QR decomposition on $A^T$ to get the linearly independent columns of $A^T$. If this succeeded, I solved the KKT system using a sparse LU decomposition. Solving the KKT system didn't have any issues, however the sparse rank-revealing QR decomposition on $A^T$ was quite fragile and failed on larger systems. I used the C++ library Eigen with Eigen::SparseQR to perform the decomposition. In the Eigen documentation it says "The numerical pivoting strategy and default threshold are the same as in SuiteSparse QR ... even though it is qualified as "rank-revealing", this strategy might fail for some rank deficient problems.".
\nSecond, I tried solving the KKT system directly without reducing $A$\n$$\n\\begin{bmatrix}\nQ & A^T \\\\\nA & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nThis is a singular system, so I tried solving it with MINRES. Again I used the Eigen library (Eigen::MINRES). The convergence was extremely poor and solutions usually had a large error. I didn't use a preconditioner as I wasn't sure how to form one for this scenario.
\nThird, I tried using nonlinear optimiser Ipopt. This did not work at all since Ipopt immediately exits with error Not_Enough_Degrees_Of_Freedom. There is an option in Ipopt to detect and remove linearly dependent constraints but in the docs it says "This is experimental and does not work well.", so I'm assuming this will have the same issues as the first approach.
So, what approaches could I use to solve this problem for large and sparse $Q$ and $A$?. Simply converting everything to dense matrices is not feasible as I need to solve this sort of system for millions of unknowns and constraints.
\n", "question_id": 45313, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "I have a quadratic programming problem\n$$\n\\begin{matrix}\n\\textrm{minimise} & x^TQx \\\\\n\\textrm{subject to} & Ax = b\n\\end{matrix}\n$$\nwhere $x$ is a vector of unknowns, $Q$ is a positive semi-definite matrix, $A$ is a matrix of constraint coefficients, and $b$ is a vector of constraint rhs values. The constraints represented by $Ax=b$ are linearly dependent. To give an idea of the extent of linear dependency, $A$ could be something $350 \\times 300$, so 350 constraints with 300 unknowns, but this reduces to 280 linearly independent constraints. It can be safely assumed that the constraints are consistent and $\\textrm{null}(Q)\\cap\\textrm{null}(A)=\\{0\\}$ such that the problem has a unique solution. I would like to find a way to solve this problem for large and sparse $Q$ and $A$. I have attempted the following.\n\n\n\n\nFirst, I tried reducing $A$ to only have linearly independent rows, denoted $A_R$, and solving the KKT system\n$$\n\\begin{bmatrix}\nQ & A_R^T \\\\\nA_R & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nI reduced $A$ to linearly independent rows by performing a sparse rank-revealing QR decomposition on $A^T$ to get the linearly independent columns of $A^T$. If this succeeded, I solved the KKT system using a sparse LU decomposition. Solving the KKT system didn't have any issues, however the sparse rank-revealing QR decomposition on $A^T$ was quite fragile and failed on larger systems. I used the C++ library Eigen with Eigen::SparseQR to perform the decomposition. In the Eigen documentation it says \"The numerical pivoting strategy and default threshold are the same as in SuiteSparse QR ... even though it is qualified as \"rank-revealing\", this strategy might fail for some rank deficient problems.\".\n\n\n\n\nSecond, I tried solving the KKT system directly without reducing $A$\n$$\n\\begin{bmatrix}\nQ & A^T \\\\\nA & 0\n\\end{bmatrix}\n\\begin{bmatrix}\nx \\\\ \\lambda\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 \\\\ b\n\\end{bmatrix}\n$$\nThis is a singular system, so I tried solving it with MINRES. Again I used the Eigen library (Eigen::MINRES). The convergence was extremely poor and solutions usually had a large error. I didn't use a preconditioner as I wasn't sure how to form one for this scenario.\n\n\n\n\nThird, I tried using nonlinear optimiser Ipopt. This did not work at all since Ipopt immediately exits with error Not_Enough_Degrees_Of_Freedom. There is an option in Ipopt to detect and remove linearly dependent constraints but in the docs it says \"This is experimental and does not work well.\", so I'm assuming this will have the same issues as the first approach.\n\n\n\n\nSo, what approaches could I use to solve this problem for large and sparse $Q$ and $A$?. Simply converting everything to dense matrices is not feasible as I need to solve this sort of system for millions of unknowns and constraints.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "BenPol", "profile_url": "https://scicomp.stackexchange.com/users/56185/benpol", "user_type": "registered"}, "created_at": "2025-12-16T01:29:04+00:00", "raw_file": "raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json", "raw_sha256": "646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac", "revision_guid": "52AB4280-FF49-4A54-8177-8AFB5BBE2030", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/52AB4280-FF49-4A54-8177-8AFB5BBE2030/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45313/quadratic-programming-with-linearly-dependent-equality-constraints", "split": "holdout", "split_group": "f29c2eea44584929d6603a13be886a695004bef2f3dccb4e0efbfe042fcc5b84", "tags": ["constrained-optimization", "convex-optimization", "quadratic-programming"], "thread_id": "scicomp:45313", "title": "Quadratic programming with linearly dependent equality constraints"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "double get_intersecting_line_density(\n const long long unsigned int n,\n const double emitter_radius,\n const double receiver_distance,\n const double receiver_distance_plus,\n const double receiver_radius)\n{\n double count = 0;\n double count_plus = 0;\n\n generator.seed(static_castThe first answer fails to mention that there is a purely quantum method (labeled C)) -- the cosine weighting is only a classical approximation (labeled B)). The following is the important part of the C++ code (which uses standard multi-threading):
\nvoid worker_thread(\n long long unsigned int start_idx,\n long long unsigned int end_idx,\n unsigned int thread_seed,\n const real_type emitter_radius,\n const real_type receiver_distance,\n const real_type receiver_distance_plus,\n const real_type receiver_radius,\n real_type& result_count,\n real_type& result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distribution<real_type> local_dis(0.0, 1.0);\n\n real_type local_count = 0;\n real_type local_count_plus = 0;\n\n // Update progress every N iterations to reduce atomic overhead\n const long long unsigned int progress_update_interval = 10000;\n long long unsigned int local_progress = 0;\n\n for (long long unsigned int i = start_idx; i < end_idx; i++)\n {\n vector_3 location = random_unit_vector(local_gen, local_dis);\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n\n // A) Newtonian gravitation\n //vector_3 normal =\n // surface_normal;\n\n // B) Schwarzschild gravitation\n //vector_3 normal = \n // random_cosine_weighted_hemisphere(\n // surface_normal, local_gen, local_dis);\n\n // C) Quantum gravitation\n vector_3 r = random_unit_vector(local_gen, local_dis);\n r.x *= emitter_radius;\n r.y *= emitter_radius;\n r.z *= emitter_radius;\n vector_3 normal = (location - r).normalize();\n\n\n local_count += intersect(\n location, normal,\n receiver_distance, receiver_radius);\n\n local_count_plus += intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n // Update global progress periodically\n local_progress++;\n if (local_progress >= progress_update_interval)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n \n local_progress = 0;\n }\n }\n\n // Add any remaining progress\n if (local_progress > 0)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n }\n\n result_count = local_count;\n result_count_plus = local_count_plus;\n}\n\n", "answer_id": 45343, "answer_text": "The first answer fails to mention that there is a purely quantum method (labeled C)) -- the cosine weighting is only a classical approximation (labeled B)). The following is the important part of the C++ code (which uses standard multi-threading):\n\n\n\n\nvoid worker_thread(\n long long unsigned int start_idx,\n long long unsigned int end_idx,\n unsigned int thread_seed,\n const real_type emitter_radius,\n const real_type receiver_distance,\n const real_type receiver_distance_plus,\n const real_type receiver_radius,\n real_type& result_count,\n real_type& result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distributionthis is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.
\ncosine weighting enforces the correct solid-angle measure, so the flux gradient obeys Gauss’s law. uniform hemisphere or tangent-plane sampling breaks that, which is why the field comes out wrong. the 2/π factor is the usual cosine-hemisphere normalization.
\nin physics terms, you’re doing a Monte Carlo solution of Poisson’s equation via flux sampling, and the Schwarzschild behavior drops out naturally when the sampling measure matches the geometry. not a single “owner” it’s standard Monte Carlo done with the right weighting.
\n", "answer_id": 45329, "answer_text": "this is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.\n\n\n\n\ncosine weighting enforces the correct solid-angle measure, so the flux gradient obeys Gauss’s law. uniform hemisphere or tangent-plane sampling breaks that, which is why the field comes out wrong. the 2/π factor is the usual cosine-hemisphere normalization.\n\n\n\n\nin physics terms, you’re doing a Monte Carlo solution of Poisson’s equation via flux sampling, and the Schwarzschild behavior drops out naturally when the sampling measure matches the geometry. not a single “owner” it’s standard Monte Carlo done with the right weighting.", "answer_url": "https://scicomp.stackexchange.com/a/45329", "author": "Linda Anderson", "author_url": "https://scicomp.stackexchange.com/users/56218/linda-anderson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-05T09:26:54+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": 45322, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Linda Anderson", "profile_url": "https://scicomp.stackexchange.com/users/56218/linda-anderson", "user_type": "registered"}, "created_at": "2026-01-05T09:26:54+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "8F296337-1611-4B90-B028-6FDD3F098E8A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/8F296337-1611-4B90-B028-6FDD3F098E8A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Linda Anderson", "profile_url": "https://scicomp.stackexchange.com/users/56218/linda-anderson", "user_type": "registered"}, "created_at": "2026-01-05T09:27:15+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "317C93D3-B055-47E3-8255-35BB56F95C1B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/317C93D3-B055-47E3-8255-35BB56F95C1B/view-source"}], "score": 5, "updated_at": "2026-01-05T09:27:15+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "this is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.
\ncosine weighting enforces the correct solid-angle measure, so the flux gradient obeys Gauss’s law. uniform hemisphere or tangent-plane sampling breaks that, which is why the field comes out wrong. the 2/π factor is the usual cosine-hemisphere normalization.
\nin physics terms, you’re doing a Monte Carlo solution of Poisson’s equation via flux sampling, and the Schwarzschild behavior drops out naturally when the sampling measure matches the geometry. not a single “owner” it’s standard Monte Carlo done with the right weighting.
\n", "answer_id": 45329, "answer_text": "this is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.\n\n\n\n\ncosine weighting enforces the correct solid-angle measure, so the flux gradient obeys Gauss’s law. uniform hemisphere or tangent-plane sampling breaks that, which is why the field comes out wrong. the 2/π factor is the usual cosine-hemisphere normalization.\n\n\n\n\nin physics terms, you’re doing a Monte Carlo solution of Poisson’s equation via flux sampling, and the Schwarzschild behavior drops out naturally when the sampling measure matches the geometry. not a single “owner” it’s standard Monte Carlo done with the right weighting.", "answer_url": "https://scicomp.stackexchange.com/a/45329", "author": "Linda Anderson", "author_url": "https://scicomp.stackexchange.com/users/56218/linda-anderson", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-05T09:26:54+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": 45322, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Linda Anderson", "profile_url": "https://scicomp.stackexchange.com/users/56218/linda-anderson", "user_type": "registered"}, "created_at": "2026-01-05T09:26:54+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "8F296337-1611-4B90-B028-6FDD3F098E8A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/8F296337-1611-4B90-B028-6FDD3F098E8A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Linda Anderson", "profile_url": "https://scicomp.stackexchange.com/users/56218/linda-anderson", "user_type": "registered"}, "created_at": "2026-01-05T09:27:15+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "317C93D3-B055-47E3-8255-35BB56F95C1B", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/317C93D3-B055-47E3-8255-35BB56F95C1B/view-source"}], "score": 5, "updated_at": "2026-01-05T09:27:15+00:00"}, {"answer_html": "The first answer fails to mention that there is a purely quantum method (labeled C)) -- the cosine weighting is only a classical approximation (labeled B)). The following is the important part of the C++ code (which uses standard multi-threading):
\nvoid worker_thread(\n long long unsigned int start_idx,\n long long unsigned int end_idx,\n unsigned int thread_seed,\n const real_type emitter_radius,\n const real_type receiver_distance,\n const real_type receiver_distance_plus,\n const real_type receiver_radius,\n real_type& result_count,\n real_type& result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distribution<real_type> local_dis(0.0, 1.0);\n\n real_type local_count = 0;\n real_type local_count_plus = 0;\n\n // Update progress every N iterations to reduce atomic overhead\n const long long unsigned int progress_update_interval = 10000;\n long long unsigned int local_progress = 0;\n\n for (long long unsigned int i = start_idx; i < end_idx; i++)\n {\n vector_3 location = random_unit_vector(local_gen, local_dis);\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n\n // A) Newtonian gravitation\n //vector_3 normal =\n // surface_normal;\n\n // B) Schwarzschild gravitation\n //vector_3 normal = \n // random_cosine_weighted_hemisphere(\n // surface_normal, local_gen, local_dis);\n\n // C) Quantum gravitation\n vector_3 r = random_unit_vector(local_gen, local_dis);\n r.x *= emitter_radius;\n r.y *= emitter_radius;\n r.z *= emitter_radius;\n vector_3 normal = (location - r).normalize();\n\n\n local_count += intersect(\n location, normal,\n receiver_distance, receiver_radius);\n\n local_count_plus += intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n // Update global progress periodically\n local_progress++;\n if (local_progress >= progress_update_interval)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n \n local_progress = 0;\n }\n }\n\n // Add any remaining progress\n if (local_progress > 0)\n {\n global_progress.fetch_add(\n local_progress, std::memory_order_relaxed);\n }\n\n result_count = local_count;\n result_count_plus = local_count_plus;\n}\n\n", "answer_id": 45343, "answer_text": "The first answer fails to mention that there is a purely quantum method (labeled C)) -- the cosine weighting is only a classical approximation (labeled B)). The following is the important part of the C++ code (which uses standard multi-threading):\n\n\n\n\nvoid worker_thread(\n long long unsigned int start_idx,\n long long unsigned int end_idx,\n unsigned int thread_seed,\n const real_type emitter_radius,\n const real_type receiver_distance,\n const real_type receiver_distance_plus,\n const real_type receiver_radius,\n real_type& result_count,\n real_type& result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distributionWhat is the name of the numerical technique used to generate the appropriate gravitational acceleration by using a set of gravitational field lines that are not necessarily normal to the surface of the emitter?
\nI have found that using cosine weighted pseudorandom field lines produces the result predicted by Schwarzschild's general relativity. It's a very simple calculation. Please help me identify its owner.
\nIn the past, I have written a short tutorial for C++ programmers on isotropic Newtonian gravitation.\nIn that old tutorial, I build an isotropic gravitational field through the use of pseudorandomly generated field lines.\nIn that old tutorial I use a sphere as the receiver.\nThe paper for that old tutorial is at Newtonian gravitation from scratch, for C++ programmers.
\nIn this question, I point out a match between the numerical gravitation and the gravitational time dilation from Schwarzschild's general relativity (see the book Gravitation, by Misner et al).\nHere, I use an axis-aligned bounding box (AABB) as the receiver.
\nIn this question I use Planck units, where $c = G = \\hbar = k = 1$.
\nWhere $r_{e}$ is the emitter's Schwarzschild radius, $r_{r}$ is the receiver AABB radius (e.g. half of the AABB side length), and $1\\mathrm{e}11$ and $0.01$ are arbitrary constants:\n\\begin{equation}\nr_{e} = \\sqrt{\\frac{1\\mathrm{e}11 \\log(2)}{\\pi}},\n\\end{equation}\n\\begin{equation}\nr_{r} = r_{e} \\times 0.01.\n\\end{equation}\nThe event horizon area is:\n\\begin{equation}\nA_{e} = 4 \\pi r_{e}^2.\n\\end{equation}\nThe binary entropy (e.g. field line count, see the papers about the holographic principle) is:\n\\begin{equation}\nn_{e} = \\frac{A_{e}}{4 \\log(2)} = 1\\mathrm{e}11.\n\\end{equation}\nWhere $R$ is the distance from the emitter's centre, the derivative is:\n\\begin{equation}\n\\alpha = \\frac{\\beta(R + \\epsilon) - \\beta(R)}{\\epsilon}.\n\\end{equation}\nHere $\\beta$ is the get intersecting line density function.\nThe gradient strength is:\n\\begin{equation}\ng = \\frac{-\\alpha}{r_{r}^2}.% \\approx \\frac{n_e}{2 R^3}.\n\\end{equation}\nFrom this I get the Newtonian acceleration $a_N$, where $r_e \\ll R$:\n\\begin{equation}\na_N =\\frac{g R \\log 2}{8 M_{e}} = \\sqrt{\\frac{n_e \\log 2}{4 \\pi R^4}} = \\frac{M_{e}}{R^2}.\n\\end{equation}\nI can also get a general relativistic acceleration $a_S$, where $r_e < R$:\n\\begin{equation}\na_S = \\frac{g R \\log 2}{8 M_{e}},\n\\end{equation}\nAt close proximity, where $r_e \\approx R$, the metric produced is related to the Schwarzschild metric -- curved space, curved time:\n\\begin{equation}\nt = \\sqrt{1 - \\frac{r_e}{R}},\n\\end{equation}\n\\begin{equation}\n\\frac{dt}{dR} = \\frac{r_e}{2 t R^2}.\n\\end{equation}\n\\begin{equation}\na_S \\approx \\frac{dt}{dR} \\frac{2}{\\pi} = \\frac{r_e}{\\pi t R^2}.\n\\end{equation}\nAt far proximity, where $r_e \\ll R$, $t \\approx 1$, and $dt/dR \\approx 0$, the metric produced is Newtonian -- curved space, practically flat time.
\nUsing numerical relativity, I tried pseudorandom hemisphere and pseudorandom tangent plane field lines, but they did not work.\nThe only technique that works is cosine weighted pseudorandom field lines.\nThat is to say, as per the code for this tutorial (https://github.com/sjhalayka/schwarzschild_falloff_field_lines), the cosine weighted pseudorandom field lines produce the correct result, off by a factor of $2 / \\pi$.
\nThis figure shows an axis-aligned bounding box and an isotropic emitter, looking from slightly above.\nAn example field line (red) and intersecting line segment (green) are given.\nThe bounding box is filled with these green intersecting line segments.\nIt is the gradient of the density of these line segments that forms the gravitational acceleration.\nNote that the field line is normal to the surface of the emitter (producing Newtonian gravitation).
\ndouble get_intersecting_line_density(\n const long long unsigned int n,\n const double emitter_radius,\n const double receiver_distance,\n const double receiver_distance_plus,\n const double receiver_radius)\n{\n double count = 0;\n double count_plus = 0;\n\n generator.seed(static_cast<unsigned>(0));\n\n for (long long unsigned int i = 0; i < n; i++)\n {\n vector_3 location = random_unit_vector();\n\n location.x *= emitter_radius;\n location.y *= emitter_radius;\n location.z *= emitter_radius;\n\n vector_3 surface_normal = location;\n surface_normal.normalize();\n\n vector_3 normal = \n random_cosine_weighted_hemisphere(\n surface_normal);\n\n std::optional<double> i_hit = intersect(\n location, normal, \n receiver_distance, receiver_radius);\n\n if (i_hit)\n count += *i_hit / (2.0 * receiver_radius);\n \n i_hit = intersect(\n location, normal,\n receiver_distance_plus, receiver_radius);\n\n if (i_hit)\n count_plus += *i_hit / (2.0 * receiver_radius);\n }\n\n return count_plus - count;\n}\n\nThank you for your time!
\n", "question_id": 45322, "question_license": "CC BY-SA 4.0", "question_score": 5, "question_text": "Question\n\n\n\n\nWhat is the name of the numerical technique used to generate the appropriate gravitational acceleration by using a set of gravitational field lines that are not necessarily normal to the surface of the emitter?\n\n\n\n\nI have found that using cosine weighted pseudorandom field lines produces the result predicted by Schwarzschild's general relativity. It's a very simple calculation. Please help me identify its owner.\n\n\n\n\nIntroduction\n\n\n\n\nIn the past, I have written a short tutorial for C++ programmers on isotropic Newtonian gravitation.\nIn that old tutorial, I build an isotropic gravitational field through the use of pseudorandomly generated field lines.\nIn that old tutorial I use a sphere as the receiver.\nThe paper for that old tutorial is at Newtonian gravitation from scratch, for C++ programmers (https://www.techrxiv.org/users/685306/articles/1250456-newtonian-gravitation-from-scratch-for-c-programmers).\n\n\n\n\nIn this question, I point out a match between the numerical gravitation and the gravitational time dilation from Schwarzschild's general relativity (see the book Gravitation, by Misner et al (https://search.worldcat.org/title/585119)).\nHere, I use an axis-aligned bounding box (AABB) as the receiver.\n\n\n\n\nIn this question I use Planck units, where $c = G = \\hbar = k = 1$.\n\n\n\n\nMethod\n\n\n\n\nWhere $r_{e}$ is the emitter's Schwarzschild radius, $r_{r}$ is the receiver AABB radius (e.g. half of the AABB side length), and $1\\mathrm{e}11$ and $0.01$ are arbitrary constants:\n\\begin{equation}\nr_{e} = \\sqrt{\\frac{1\\mathrm{e}11 \\log(2)}{\\pi}},\n\\end{equation}\n\\begin{equation}\nr_{r} = r_{e} \\times 0.01.\n\\end{equation}\nThe event horizon area is:\n\\begin{equation}\nA_{e} = 4 \\pi r_{e}^2.\n\\end{equation}\nThe binary entropy (e.g. field line count, see the papers about the holographic principle) is:\n\\begin{equation}\nn_{e} = \\frac{A_{e}}{4 \\log(2)} = 1\\mathrm{e}11.\n\\end{equation}\nWhere $R$ is the distance from the emitter's centre, the derivative is:\n\\begin{equation}\n\\alpha = \\frac{\\beta(R + \\epsilon) - \\beta(R)}{\\epsilon}.\n\\end{equation}\nHere $\\beta$ is the get intersecting line density function.\nThe gradient strength is:\n\\begin{equation}\ng = \\frac{-\\alpha}{r_{r}^2}.% \\approx \\frac{n_e}{2 R^3}.\n\\end{equation}\nFrom this I get the Newtonian acceleration $a_N$, where $r_e \\ll R$:\n\\begin{equation}\na_N =\\frac{g R \\log 2}{8 M_{e}} = \\sqrt{\\frac{n_e \\log 2}{4 \\pi R^4}} = \\frac{M_{e}}{R^2}.\n\\end{equation}\nI can also get a general relativistic acceleration $a_S$, where $r_e < R$:\n\\begin{equation}\na_S = \\frac{g R \\log 2}{8 M_{e}},\n\\end{equation}\nAt close proximity, where $r_e \\approx R$, the metric produced is related to the Schwarzschild metric -- curved space, curved time:\n\\begin{equation}\nt = \\sqrt{1 - \\frac{r_e}{R}},\n\\end{equation}\n\\begin{equation}\n\\frac{dt}{dR} = \\frac{r_e}{2 t R^2}.\n\\end{equation}\n\\begin{equation}\na_S \\approx \\frac{dt}{dR} \\frac{2}{\\pi} = \\frac{r_e}{\\pi t R^2}.\n\\end{equation}\nAt far proximity, where $r_e \\ll R$, $t \\approx 1$, and $dt/dR \\approx 0$, the metric produced is Newtonian -- curved space, practically flat time.\n\n\n\n\nUsing numerical relativity, I tried pseudorandom hemisphere and pseudorandom tangent plane field lines, but they did not work.\nThe only technique that works is cosine weighted pseudorandom field lines.\nThat is to say, as per the code for this tutorial (https://github.com/sjhalayka/schwarzschild_falloff_field_lines (https://github.com/sjhalayka/schwarzschild_falloff_field_lines)), the cosine weighted pseudorandom field lines produce the correct result, off by a factor of $2 / \\pi$.\n\n\n\n\nFigure\n\n\n\n\n[image: axis-aligned bounding box; source: https://i.sstatic.net/XWbsh2qc.png] (https://i.sstatic.net/XWbsh2qc.png)\n\n\n\n\nThis figure shows an axis-aligned bounding box and an isotropic emitter, looking from slightly above.\nAn example field line (red) and intersecting line segment (green) are given.\nThe bounding box is filled with these green intersecting line segments.\nIt is the gradient of the density of these line segments that forms the gravitational acceleration.\nNote that the field line is normal to the surface of the emitter (producing Newtonian gravitation).\n\n\n\n\nC++ code\n\n\n\n\ndouble get_intersecting_line_density(\n const long long unsigned int n,\n const double emitter_radius,\n const double receiver_distance,\n const double receiver_distance_plus,\n const double receiver_radius)\n{\n double count = 0;\n double count_plus = 0;\n\n generator.seed(static_castThe NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.
\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.
\n", "answer_id": 45327, "answer_text": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).", "answer_url": "https://scicomp.stackexchange.com/a/45327", "author": "Wolfgang Bangerth", "author_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-03T02:46:44+00:00", "is_accepted": true, "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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Wolfgang Bangerth", "profile_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "user_type": "registered"}, "created_at": "2026-01-03T02:46:44+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/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": "2026-01-23T14:37:58+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "B49E063C-3F0D-471B-956C-B179F2F73567", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}], "score": 10, "updated_at": "2026-01-23T14:37:58+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "class PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "72f89f4e70a0d9ea27afa54ad378f9c4e2b0812f96becf4acbd8f7ebf0cc9b85", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}, {"block_index": 1, "code_text": "def df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "b2d3d4f6e01670c9cb767d689a925772aaee0c1b9223facf411446def617adca", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}, {"block_index": 2, "code_text": "class Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "1a915d175651e4b9f9655e9ec1c9264bc3f1f929f0579d7c759eeba08ce30194", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}, {"block_index": 3, "code_text": "def train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "c7d15b6e7e7d62ba263632f66347f76b266d871b1ee7544ec9e25530d170018b", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}, {"block_index": 4, "code_text": "def create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45326, "sha256": "9ad8906458885f3d360ec2d77e3f1ad1f6ff1f533262564103a2e6f6d9b8174e", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis"}], "other_answers": [{"answer_html": "I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.
\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).
\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.
\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.
\n", "answer_id": 45328, "answer_text": "I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.\n\n\n\n\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).\n\n\n\n\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.\n\n\n\n\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.", "answer_url": "https://scicomp.stackexchange.com/a/45328", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-05T07:08:57+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2026-01-05T07:08:57+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "E5705B06-7DAC-4324-A752-C8064C49BB6C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E5705B06-7DAC-4324-A752-C8064C49BB6C/view-source"}], "score": 3, "updated_at": "2026-01-05T07:08:57+00:00"}, {"answer_html": "Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.
\n", "answer_id": 45348, "answer_text": "Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.", "answer_url": "https://scicomp.stackexchange.com/a/45348", "author": "Donte Lightfoot", "author_url": "https://scicomp.stackexchange.com/users/56387/donte-lightfoot", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-22T23:46:46+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Donte Lightfoot", "profile_url": "https://scicomp.stackexchange.com/users/56387/donte-lightfoot", "user_type": "registered"}, "created_at": "2026-01-22T23:46:46+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "790DF00C-3B67-42CD-A314-653CD46193C9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/790DF00C-3B67-42CD-A314-653CD46193C9/view-source"}], "score": 2, "updated_at": "2026-01-22T23:46:46+00:00"}], "product": "code_qa", "question": "I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.\n\n\n\n\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.\n\n\n\n\n[image: output GIF; source: https://i.sstatic.net/9QczcfVK.gif] (https://i.sstatic.net/9QczcfVK.gif)\n\n\n\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/IMsKTvWk.png] (https://i.sstatic.net/IMsKTvWk.png)\n\n\n\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$\n\n\n\n\nwhere:\n\n\n\n\n\n(c = 1)\n\n\n\n\n(f(x,y,t)) is a Gaussian spatial source with sinusoidal time dependence\n\n\n\n\n\nInitial conditions:\n\n\n\n\n\n(u(x,y,0) = 0)\n\n\n\n\n$\\partial_t u(x,y,0) = 0$\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nFirst-order absorbing (Sommerfeld):\n\n\n\n\n\n$\\partial_t u + c\\,\\partial_n u = 0$\n\n\n\n\n\nThe wavefronts don't make much sense\n\n\n\n\n\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\n\n\n\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\n\n\n\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\n\n\n\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\n\n\n\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\n\n\n\n\n\n\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer\n\n\n\n\n\n\n\n\n\nActivation: sin\n\n\n\n\n\n\n\n\n\nTraining:\n\n\n\n\n\nAdam optimizer (20k epochs)\n\n\n\n\nLBFGS refinement\n\n\n\n\n\n\n\n\n\n\nCollocation points:\n\n\n\n\n\nUniform tensor-product grid in (x, y, t)\n\n\n\n\n\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nImplemented via additional loss terms using autograd\n\n\n\n\n\n\n\n\n\n\nVisualization:\n\n\n\n\n\nPINN evaluated on a dense grid and animated with Matplotlib\n\n\n\n\n\n\n\n\n\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.\n\n\n\n\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45326", "selected_answer": {"answer_html": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.
\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.
\n", "answer_id": 45327, "answer_text": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).", "answer_url": "https://scicomp.stackexchange.com/a/45327", "author": "Wolfgang Bangerth", "author_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-03T02:46:44+00:00", "is_accepted": true, "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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Wolfgang Bangerth", "profile_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "user_type": "registered"}, "created_at": "2026-01-03T02:46:44+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/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": "2026-01-23T14:37:58+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "B49E063C-3F0D-471B-956C-B179F2F73567", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}], "score": 10, "updated_at": "2026-01-23T14:37:58+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45327, "answers": [{"answer_html": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.
\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations.
\n", "answer_id": 45327, "answer_text": "The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.\n\n\n\n\nThis is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all able to compete against traditional discretization methods. Moreover, the PINN community has done a poor job at providing fair assessments. I always recommend students take a look at: Weak baselines and reporting biases lead to overoptimism in machine learning for fluid-related partial differential equations (https://arxiv.org/abs/2407.07218).", "answer_url": "https://scicomp.stackexchange.com/a/45327", "author": "Wolfgang Bangerth", "author_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-03T02:46:44+00:00", "is_accepted": true, "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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Wolfgang Bangerth", "profile_url": "https://scicomp.stackexchange.com/users/393/wolfgang-bangerth", "user_type": "registered"}, "created_at": "2026-01-03T02:46:44+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/12F5FACA-F2F7-4BE5-BAC4-F6A8236BA147/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": "2026-01-23T14:37:58+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "B49E063C-3F0D-471B-956C-B179F2F73567", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B49E063C-3F0D-471B-956C-B179F2F73567/view-source"}], "score": 10, "updated_at": "2026-01-23T14:37:58+00:00"}, {"answer_html": "I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.
\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).
\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.
\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.
\n", "answer_id": 45328, "answer_text": "I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.\n\n\n\n\nIn classical discretizations you have to evaluate the derivatives at each cell in your grid by combining the values of adjacent cells. This is true for essentially all discretizations in one way or another (FV, FEM, DG).\n\n\n\n\nThis gives you a baseline of how much computation you would have to do to get to reasonable results, and even these have known errors.\n\n\n\n\nI don't know if the precision of the solutions you are showing are at all surprising given the number of degrees of freedom of your net.", "answer_url": "https://scicomp.stackexchange.com/a/45328", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-05T07:08:57+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2026-01-05T07:08:57+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "E5705B06-7DAC-4324-A752-C8064C49BB6C", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E5705B06-7DAC-4324-A752-C8064C49BB6C/view-source"}], "score": 3, "updated_at": "2026-01-05T07:08:57+00:00"}, {"answer_html": "Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.
\n", "answer_id": 45348, "answer_text": "Your distortion is learned memory/anisotropy from BC + sampling—make the boundary a controllable memory channel and rebalance collocation near the source.", "answer_url": "https://scicomp.stackexchange.com/a/45348", "author": "Donte Lightfoot", "author_url": "https://scicomp.stackexchange.com/users/56387/donte-lightfoot", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-22T23:46:46+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": 45326, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Donte Lightfoot", "profile_url": "https://scicomp.stackexchange.com/users/56387/donte-lightfoot", "user_type": "registered"}, "created_at": "2026-01-22T23:46:46+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "790DF00C-3B67-42CD-A314-653CD46193C9", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/790DF00C-3B67-42CD-A314-653CD46193C9/view-source"}], "score": 2, "updated_at": "2026-01-22T23:46:46+00:00"}], "domain": "computational_science", "external_links": ["https://arxiv.org/abs/2407.07218", "https://i.sstatic.net/9QczcfVK.gif", "https://i.sstatic.net/IMsKTvWk.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": "Anwesh Saha", "question_author_url": "https://scicomp.stackexchange.com/users/56260/anwesh-saha", "question_author_user_type": "registered", "question_created_at": "2026-01-01T19:29:53+00:00", "question_html": "I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.
\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.
\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):
\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$
\nwhere:
\nInitial conditions:
\nBoundary conditions:
\n$\\partial_t u + c\\,\\partial_n u = 0$
\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer
\nActivation: sin
Training:
\nCollocation points:
\nBoundary conditions:
\nVisualization:
\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.
\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.
\n", "question_id": 45326, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorted, anisotropic, or noisy.\n\n\n\n\nI would like to understand what is wrong or suboptimal in my setup (PDE formulation, boundary conditions, sampling strategy, network architecture, etc.) and what changes are required to obtain physically correct circular wavefronts.\n\n\n\n\n[image: output GIF; source: https://i.sstatic.net/9QczcfVK.gif] (https://i.sstatic.net/9QczcfVK.gif)\n\n\n\n\nTraining details:\n• Training set:\n• Interior collocation points: uniform tensor-product grid in (x,y,t) with 30^3 = 27000 points\n• Boundary points: all four spatial boundaries sampled over time with 30^2 points per boundary\n• Loss curves (residual, IC, BC):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/IMsKTvWk.png] (https://i.sstatic.net/IMsKTvWk.png)\n\n\n\n\n$\\frac{\\partial^2 u}{\\partial t^2} - c^2 (\\partial_{xx} u + \\partial_{yy} u) = f(x,y,t)$\n\n\n\n\nwhere:\n\n\n\n\n\n(c = 1)\n\n\n\n\n(f(x,y,t)) is a Gaussian spatial source with sinusoidal time dependence\n\n\n\n\n\nInitial conditions:\n\n\n\n\n\n(u(x,y,0) = 0)\n\n\n\n\n$\\partial_t u(x,y,0) = 0$\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nFirst-order absorbing (Sommerfeld):\n\n\n\n\n\n$\\partial_t u + c\\,\\partial_n u = 0$\n\n\n\n\n\nThe wavefronts don't make much sense\n\n\n\n\n\nclass PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n nn.Linear(dim_hidden, dim_hidden)\n for _ in range(num_hidden - 1)\n ])\n self.act = act\n\n def forward(self, x, y, t):\n z = torch.cat([x, y, t], dim=1)\n z = self.act(self.layer_in(z))\n for layer in self.middle_layers:\n z = self.act(layer(z))\n return self.layer_out(z)\n\n\n\n\n\ndef df(output, input, order=1):\n v = output\n for _ in range(order):\n v = torch.autograd.grad(\n v, input,\n grad_outputs=torch.ones_like(input),\n create_graph=True,\n retain_graph=True\n )[0]\n return v\n\n\ndef dfdt(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), t, order)\n\n\ndef dfdx(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), x, order)\n\n\ndef dfdy(pinn, x, y, t, order=1):\n return df(pinn(x, y, t), y, order)\n\n\n\n\n\nclass Loss:\n def residual_loss(self, pinn):\n # Wave equation residual\n return ...\n\n def initial_loss(self, pinn):\n # u(x,y,0)=0 and du/dt(x,y,0)=0\n return ...\n\n def boundary_loss(self, pinn):\n # Absorbing (Sommerfeld) BC\n # dudt + c * du/dn = 0\n return ...\n\n\n\n\n\ndef train_model(pinn, loss_fn):\n # Adam phase\n # LBFGS phase\n return pinn\n\n\n\n\n\ndef create_wave_animation(pinn):\n # Evaluate PINN on grid and animate\n pass\n\n\n\n\n\n\n\n\nNetwork: fully-connected MLP, 4 hidden layers, 80 neurons per layer\n\n\n\n\n\n\n\n\n\nActivation: sin\n\n\n\n\n\n\n\n\n\nTraining:\n\n\n\n\n\nAdam optimizer (20k epochs)\n\n\n\n\nLBFGS refinement\n\n\n\n\n\n\n\n\n\n\nCollocation points:\n\n\n\n\n\nUniform tensor-product grid in (x, y, t)\n\n\n\n\n\n\n\n\n\n\nBoundary conditions:\n\n\n\n\n\nImplemented via additional loss terms using autograd\n\n\n\n\n\n\n\n\n\n\nVisualization:\n\n\n\n\n\nPINN evaluated on a dense grid and animated with Matplotlib\n\n\n\n\n\n\n\n\n\nI expect to see symmetric circular wavefronts expanding from the source, similar to finite-difference or spectral solutions of the 2D wave equation.\n\n\n\n\nAny insight into numerical, architectural, or formulation issues would be greatly appreciated.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Anwesh Saha", "profile_url": "https://scicomp.stackexchange.com/users/56260/anwesh-saha", "user_type": "registered"}, "created_at": "2026-01-01T19:29:53+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "48F1548B-237A-4E64-9D2B-23708297897F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/48F1548B-237A-4E64-9D2B-23708297897F/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-01-02T05:44:50+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "F9E6ED4E-E272-4959-AB38-6016CEED48E6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/F9E6ED4E-E272-4959-AB38-6016CEED48E6/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Anwesh Saha", "profile_url": "https://scicomp.stackexchange.com/users/56260/anwesh-saha", "user_type": "registered"}, "created_at": "2026-01-02T05:49:23+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "D31A0254-33EE-4DC9-BC16-D05905CA3663", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D31A0254-33EE-4DC9-BC16-D05905CA3663/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Anwesh Saha", "profile_url": "https://scicomp.stackexchange.com/users/56260/anwesh-saha", "user_type": "registered"}, "created_at": "2026-01-02T06:00:26+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "C90C675C-FD01-4F7F-8343-47D3A101E2AF", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C90C675C-FD01-4F7F-8343-47D3A101E2AF/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-01-03T11:41:26+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "C6534CC8-3DAF-4FF7-918C-DDE4C08B9232", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/C6534CC8-3DAF-4FF7-918C-DDE4C08B9232/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45326/physics-informed-neural-network-for-2d-wave-equation-produces-non-circular-dis", "split": "train", "split_group": "45c7425e154db27f580935b67401becade107a292d53c7f95ef776a2eb87be1b", "tags": ["fluid-dynamics", "computational-physics", "machine-learning", "physics-informed-neural-networks"], "thread_id": "scicomp:45326", "title": "Physics-Informed Neural Network for 2D Wave Equation Produces Non-Circular / Distorted Wavefronts"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45335, "sha256": "57aac7578bb6f741268023073e8caf04782e2d1a8ebdc92d20507478f02d64b4", "source_url": "https://scicomp.stackexchange.com/a/45335"}, {"block_index": 0, "code_text": "function [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45337, "sha256": "535fd63b99697fb569289a64746583e07c5d7d903898e20406ca04bde8aa5841", "source_url": "https://scicomp.stackexchange.com/a/45337"}], "other_answers": [{"answer_html": "I managed to create a prototype solver based on ADMM in MATLAB:
\nfunction [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %<! Optimization variable\nvS = zeros(numInEq, 1); %<! Slack variable for inequality\nvS1 = zeros(numInEq, 1); %<! Preious iteration buffer\nvMu = zeros(numInEq, 1); %<! Dual variable for inequality\nvNu = zeros(numEq, 1); %<! Dual variabe for equality\n\n% Factorize the KKT System\n% (Q + rho * A' * A + rho * E' * E) * z = r\nmK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\nsK = decomposition(mK, 'chol', 'CheckCondition', false);\n\nisConv = false;\nupdatedRho = false;\n\nfor ii = 1:numIter\n vS1(:) = vS; %<! Previous iteration\n\n % Solve the Linear System\n vR = -vQ - mA.' * (paramRho * vS + vMu) + mE.' * (paramRho * vD - vNu); %<! Right hand vector\n vX = sK \\ vR;\n\n % Proximal / Projection Step\n % s = -A * z with s >= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n\nI has convergence check and adaptation of the ADMM's step size parameter $\\rho$.
\nI will add mathematical formulation and a memory optimized version using Julia.
On MATLAB with this naive code I could beat quadprog() by 30% with the same output:
I produced an ADMM based solver which I found very efficient.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nI will use $\\boldsymbol{D} = \\boldsymbol{D}^{m}$ to simplify notations.
\nThe equality constraints can be turned into matrix form and the problem becomes:
$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} = \\boldsymbol{0} \\\\\n& \\quad & \\boldsymbol{s} \\geq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe equality constraints are introduced by the Augmented Lagrangian:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}, \\boldsymbol{s}, \\boldsymbol{\\mu}, \\boldsymbol{\\nu} \\right) = \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} + {\\rho}^{-1} \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{E} \\boldsymbol{x} - \\boldsymbol{d} + {\\rho}^{-1} \\boldsymbol{\\nu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe stopping condition is when both residuals are below a threshold:
\nThe use of the infinity norm decouples the dimension of the problem from the thresholds.
\nI also used OSQP style update of the $\\rho$ parameter to accelerate convergence: ${\\rho}^{\\left( k \\right)} = {\\rho}^{\\left( k - 1 \\right)} \\sqrt{ \\frac{ {r}^{\\left( k \\right)} }{ {s}^{\\left( k \\right)} } }$.
\nI implemented all in Julia and compared to the ECOS / SCS solvers wrapped by Convex.jl.
Run Times:
\nBenchmarkTools.Trial: 1227 samples with 1 evaluation per sample.\n Range (min … max): 3.412 ms … 18.615 ms ┊ GC (min … max): 0.00% … 60.46%\n Time (median): 3.807 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 4.061 ms ± 859.845 μs ┊ GC (mean ± σ): 1.67% ± 5.36%\n\n ▅█▇▄▃ ▁\n ▄████████▇▆▇▅▆▅▅▄▄▃▃▃▃▄▃▄▄▄▃▃▃▃▃▃▂▂▂▂▃▃▂▂▂▃▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃\n 3.41 ms Histogram: frequency by time 6.54 ms <\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n\nBenchmarkTools.Trial: 98 samples with 1 evaluation per sample.\n Range (min … max): 49.280 ms … 53.704 ms ┊ GC (min … max): 0.00% … 0.00%\n Time (median): 50.892 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 51.055 ms ± 918.217 μs ┊ GC (mean ± σ): 0.00% ± 0.00%\n\n ▁ ▃ ▁▁▁█ █▃ ▁ ▃ ▁ ▆ ▁ ▁\n ▄▁▁▇▁█▁▁▄▄▇▄▄▇█▇████▇██▄█▇█▄█▄▁▄█▄▇▇█▁▇▄▄▄▄▁▇▇▄▄█▄▁▄▄▁▄▁▁▁▁▇ ▁\n 49.3 ms Histogram: frequency by time 53.2 ms <\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n\nBenchmarkTools.Trial: 7569 samples with 1 evaluation per sample.\n Range (min … max): 447.700 μs … 23.329 ms ┊ GC (min … max): 0.00% … 70.82%\n Time (median): 651.300 μs ┊ GC (median): 0.00%\n Time (mean ± σ): 656.690 μs ± 412.333 μs ┊ GC (mean ± σ): 1.30% ± 2.26%\n\n ▁▄▄▁ ▁▃▅▅▆▆█▇▇▆▅▄▂▁▁\n ▃████▆▄▃▂▂▂▂▂▁▂▃▅███████████████▇▆▆▄▅▄▄▄▃▃▂▂▂▂▂▂▂▂▂▁▁▂▁▁▁▁▁▁▁ ▄\n 448 μs Histogram: frequency by time 970 μs <\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n\nThe ADMM method is an order of magnitude faster than the generic solvers.
\nIt can be greatly improved as it designed for arbitrary matrix $\\boldsymbol{E}$. It can be farther optimized for the case of equality.
The code is available on my StackExchange Code GitHub Repository (Look at the ComputationalScience\\Q45334 folder).
Another formulation take advantage of the equality constraint to make the problem formulation smaller.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:
\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$
\nThen the above can be formulated as:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$
\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.
\nThis formulation reduces the number of constraints to handle.
\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.
The Augmented Lagrangian (Scaled form) is given by:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe rest is similar to above with the needed adjustments for the residuals calculations.
\nThis implementation reduced another 40 [Micro Sec] of the run time.
\n", "answer_id": 45342, "answer_text": "Another formulation take advantage of the equality constraint to make the problem formulation smaller.\n\n\n\n\nThe problem is given by:\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} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:\n\n\n\n\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$\n\n\n\n\nThen the above can be formulated as:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.\n\n\n\n\nThis formulation reduces the number of constraints to handle.\n\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.\n\n\n\n\nThe Augmented Lagrangian (Scaled form) is given by:\n\n\n\n\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$\n\n\n\n\nThe steps to solve:\n\n\n\n\n\nPrimal Update (Solve Linear System): $\\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} = {\\left( \\boldsymbol{P} + \\rho \\boldsymbol{A}_{\\mathcal{J}}^{\\top} \\boldsymbol{A}_{\\mathcal{J}} \\right)}^{-1} \\left( - \\boldsymbol{q} + \\rho \\boldsymbol{A}_{\\mathcal{J}} \\left( \\boldsymbol{b} - \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) \\right)$.\n\n\n\n\nSlack Update (Non Negative LS / Projection): $\\boldsymbol{s}^{\\left( k + 1 \\right)} = \\max \\left(\\boldsymbol{0}, \\boldsymbol{b} - \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent): $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\left( \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} - \\boldsymbol{b} \\right)$.\n\n\n\n\n\nThe rest is similar to above with the needed adjustments for the residuals calculations.\n\n\n\n\nThis implementation reduced another 40 [Micro Sec] of the run time.", "answer_url": "https://scicomp.stackexchange.com/a/45342", "author": "Royi", "author_url": "https://scicomp.stackexchange.com/users/7951/royi", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-17T12:18:23+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": 45334, "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": "2026-01-17T12:18:23+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB/view-source"}], "score": 1, "updated_at": "2026-01-17T12:18:23+00:00"}], "product": "code_qa", "question": "Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.\n\n\n\n\nI want to smooth the curve with the following properties:\n\n\n\n\n\nThe result, $\\left\\{ {z}_{1}, {z}_{2}, \\ldots {z}_{n} \\right\\}$ should be smooth like Spline based method.\n\n\n\n\nFor a set of indices $\\mathcal{I}$ the smoothed curve must go through the reference point, namely ${z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I}$.\n\n\n\n\nThe smoothed values between 2 reference points must be monotonic.\n\n\n\n\n\nI came up with the following model:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.\n\n\n\n\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.\n\n\n\n\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45334", "selected_answer": {"answer_html": "\n\nmonothonic
\n
I'm sure you meant monotonic.
\n\n\nI am looking for a fast way to solve the problem
\n
Are you actually? I think if you were, you would use something off-the-shelf. "Simple iterative" and "fast" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:
\nA traditional LP would express the problem thus. Define the following decision vectors:
\nFind
\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$
\ngiven the following constraints:
\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$
\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$
\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.
\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\nHere we see that the solution does exactly what we tell it to:
\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:
\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):
\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.
\n", "answer_id": 45335, "answer_text": "monothonic\n\n\n\n\n\n\n\nI'm sure you meant monotonic.\n\n\n\n\n\n\n\nI am looking for a fast way to solve the problem\n\n\n\n\n\n\n\nAre you actually? I think if you were, you would use something off-the-shelf. \"Simple iterative\" and \"fast\" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:\n\n\n\n\n\nLinear, not quadratic\n\n\n\n\nNo manual iteration per se\n\n\n\n\nEnforce inter-reference monotonicity through simple linear constraints\n\n\n\n\nModel cost as being absolute error plus absolute second-order differential, the latter receiving your $\\lambda$ weight\n\n\n\n\n\nA traditional LP would express the problem thus. Define the following decision vectors:\n\n\n\n\n\n$z \\in \\mathbb R^n$, the fit points\n\n\n\n\n$z_p \\in \\mathbb R^n$, $z_p \\ge 0$, positive-clipped fit error\n\n\n\n\n$z_n \\in \\mathbb R^n$, $z_n \\ge 0$, negative-clipped fit error\n\n\n\n\n$d_p \\in \\mathbb R^{n-2}$, $d_p \\ge 0$, positive-clipped second-order differentials\n\n\n\n\n$d_n \\in \\mathbb R^{n-2}$, $d_n \\ge 0$, negative-clipped second-order differentials\n\n\n\n\n\nFind\n\n\n\n\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$\n\n\n\n\ngiven the following constraints:\n\n\n\n\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$\n\n\n\n\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$\n\n\n\n\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\nHere we see that the solution does exactly what we tell it to:\n\n\n\n\n[image: example solution; source: https://i.sstatic.net/oTyX0oWA.png] (https://i.sstatic.net/oTyX0oWA.png)\n\n\n\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:\n\n\n\n\n[image: smoothing; source: https://i.sstatic.net/cW1t1avg.png] (https://i.sstatic.net/cW1t1avg.png)\n\n\n\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):\n\n\n\n\n[image: sparsity; source: https://i.sstatic.net/UmVF5qyE.png] (https://i.sstatic.net/UmVF5qyE.png)\n\n\n\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.", "answer_url": "https://scicomp.stackexchange.com/a/45335", "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-01-10T07:56:42+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": 45334, "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-01-10T07:56:42+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "49224026-A98C-4DFC-B187-28324764F758", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/49224026-A98C-4DFC-B187-28324764F758/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-01-10T15:16:37+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "0462867C-327F-469E-957B-1FE451F4CE5C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/0462867C-327F-469E-957B-1FE451F4CE5C/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-01-10T20:00:35+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "302EF20B-4729-4185-A059-5377ED4B7555", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/302EF20B-4729-4185-A059-5377ED4B7555/view-source"}], "score": 3, "updated_at": "2026-01-10T20:00:35+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "\n\nmonothonic
\n
I'm sure you meant monotonic.
\n\n\nI am looking for a fast way to solve the problem
\n
Are you actually? I think if you were, you would use something off-the-shelf. "Simple iterative" and "fast" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:
\nA traditional LP would express the problem thus. Define the following decision vectors:
\nFind
\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$
\ngiven the following constraints:
\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$
\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$
\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.
\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\nHere we see that the solution does exactly what we tell it to:
\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:
\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):
\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.
\n", "answer_id": 45335, "answer_text": "monothonic\n\n\n\n\n\n\n\nI'm sure you meant monotonic.\n\n\n\n\n\n\n\nI am looking for a fast way to solve the problem\n\n\n\n\n\n\n\nAre you actually? I think if you were, you would use something off-the-shelf. \"Simple iterative\" and \"fast\" don't particularly jive, here. Let's take a random stab at remodelling your problem to meet some of your criteria:\n\n\n\n\n\nLinear, not quadratic\n\n\n\n\nNo manual iteration per se\n\n\n\n\nEnforce inter-reference monotonicity through simple linear constraints\n\n\n\n\nModel cost as being absolute error plus absolute second-order differential, the latter receiving your $\\lambda$ weight\n\n\n\n\n\nA traditional LP would express the problem thus. Define the following decision vectors:\n\n\n\n\n\n$z \\in \\mathbb R^n$, the fit points\n\n\n\n\n$z_p \\in \\mathbb R^n$, $z_p \\ge 0$, positive-clipped fit error\n\n\n\n\n$z_n \\in \\mathbb R^n$, $z_n \\ge 0$, negative-clipped fit error\n\n\n\n\n$d_p \\in \\mathbb R^{n-2}$, $d_p \\ge 0$, positive-clipped second-order differentials\n\n\n\n\n$d_n \\in \\mathbb R^{n-2}$, $d_n \\ge 0$, negative-clipped second-order differentials\n\n\n\n\n\nFind\n\n\n\n\n$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$\n\n\n\n\ngiven the following constraints:\n\n\n\n\n$$ z_p \\ge z - y $$\n$$ z_n \\ge y - z $$\n$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$\n$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$\n$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $ for every index $i$ between every anchor point $y_0$, $y_1$\n\n\n\n\n$ \\frac {\\partial^2 z} {\\partial i^2} $ discretised by:\n$$ \\begin{bmatrix}\n1 & -2 & 1 \\\\\n & 1 & -2 & 1 \\\\\n & & & & \\ddots\n\\end{bmatrix} z $$\n\n\n\n\nThe problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start=0, stop=10, num=n)\n y = rand.uniform(low=-0.1, high=0.1, size=x.size).cumsum()\n iref = np.array((2, 6, 9))*(n//10)\n return x, y, iref\n\n\ndef cost(n: int, nd: int, smoothing: float) -> np.ndarray:\n return np.concatenate((\n np.zeros(n), # z does not incur a cost directly\n np.ones(2*n), # zerr cost\n np.full(2*nd, fill_value=smoothing),\n ))\n\n\ndef bounds(iref: np.ndarray, n: int, nd: int, y: np.ndarray) -> np.ndarray:\n lbound, ubound = bounds = np.zeros((2, 3*n + 2*nd))\n lbound[:n] = -np.inf\n ubound[:] = np.inf\n\n iprev = iref[:-1]\n inext = iref[1:]\n pprev = y[iprev]\n pnext = y[inext]\n pfloor = np.minimum(pprev, pnext)\n pceil = np.maximum(pprev, pnext)\n\n for i0, i1, plo, phi in zip(iprev, inext, pfloor, pceil):\n lbound[i0] = y[i0]\n ubound[i0] = y[i0]\n inner = slice(i0 + 1, i1)\n lbound[inner] = plo\n ubound[inner] = phi\n lbound[iref[-1]] = y[iref[-1]]\n ubound[iref[-1]] = y[iref[-1]]\n\n return bounds\n\n\ndef zerror_constraints(n: int, nd: int, y: np.ndarray) -> tuple[LinearConstraint, ...]:\n # zep >= z - y: z - zep <= y\n # zen >= y - z: z + zen >= y\n eye = sp.eye_array(n)\n zero = sp.csc_array((n, n))\n zerond = sp.csc_array((n, 2*nd))\n pos = LinearConstraint(\n A=sp.hstack((eye, -eye, zero, zerond), format='csc'), ub=y)\n neg = LinearConstraint(\n A=sp.hstack((eye, zero, eye, zerond), format='csc'), lb=y)\n return pos, neg\n\n\ndef d2_constraints(n: int, nd: int) -> tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p >= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p >= 0\n # d2n >= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n >= 0\n data = np.broadcast_to(\n np.array(([1], [-2], [1]), dtype=np.float32), # don't bother with /dt**2\n shape=(3, n))\n offsets = np.array((0, 1, 2), dtype=np.int32)\n kernel = sp.dia_array((data, offsets), shape=(nd, n))\n err_zero = sp.csc_array((nd, 2*n))\n eye = sp.eye_array(nd)\n zero = sp.csc_array((nd, nd))\n pos = LinearConstraint(\n A=sp.hstack((-kernel, err_zero, eye, zero), format='csc'), lb=0)\n neg = LinearConstraint(\n A=sp.hstack(( kernel, err_zero, zero, eye), format='csc'), lb=0)\n return pos, neg\n\n\ndef monotone_constraints(n: int, nd: int, y: np.ndarray, iref: np.ndarray) -> tuple[LinearConstraint, ...]:\n iprev = iref[:-1]\n inext = iref[1:]\n yprev = y[iprev]\n ynext = y[inext]\n blocks = []\n\n for i0, i1, y0, y1 in zip(iprev, inext, yprev, ynext):\n sign = np.sign(y1 - y0)\n if sign == 0:\n continue # the entire segment will already have lower and upper bounds equal to each other\n block = sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0 + 1,\n ) - sp.eye_array(\n m=i1 - i0, n=3*n + 2*nd, k=i0)\n blocks.append(sign*block)\n constraint = LinearConstraint(A=sp.vstack(blocks, format='csc'), lb=0)\n return constraint,\n\n\ndef solve(y: np.ndarray, iref: np.ndarray, smoothing: float = 1.) -> tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, >= 0, >= z-y\n zen, continuous, >= 0, >= y-z\n d2p, n-2, continuous, >= 0, >= d2z/dt2\n d2n, n-2, continuous, >= 0, >= -d2z/dt2\n '''\n n = y.size\n nd = n - 2\n constraints = (\n zerror_constraints(n, nd, y) + d2_constraints(n, nd) + monotone_constraints(n, nd, y, iref)\n )\n\n result = milp(\n c=cost(n, nd, smoothing), integrality=0, bounds=bounds(iref, n, nd, y),\n constraints=constraints,\n )\n if not result.success:\n raise result.message\n z, zep, zen, d2p, d2n = np.split(result.x, (n, 2*n, 3*n, 3*n+nd))\n return z, constraints\n\n\ndef demo() -> None:\n rand = np.random.default_rng(seed=0)\n x, y, iref = sample_data(rand, n=801)\n\n fig, ax = plt.subplots()\n ax.plot(x, y, label='orig')\n ax.scatter(x[iref], y[iref], color='red', label='ref point')\n\n for smoothing in (0.5, 3):\n z, constraints = solve(y, iref, smoothing)\n ax.plot(x, z, label=f'smooth={smoothing}')\n ax.legend()\n\n sparsity = sp.vstack([c.A for c in constraints]).sign().toarray()\n fig, ax = plt.subplots()\n ax.set_title(f'Constraint sparsity, n={y.size}')\n ax.imshow(sparsity)\n\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n\n\n\n\n\nHere we see that the solution does exactly what we tell it to:\n\n\n\n\n[image: example solution; source: https://i.sstatic.net/oTyX0oWA.png] (https://i.sstatic.net/oTyX0oWA.png)\n\n\n\n\nOutside of the reference points, monotonicity is not enforced so the smoothed curve follows the input curve. Within the reference points, monotonicity is preserved, and the solver does its best to balance smoothing and fitting; a finer-scale depiction of this behaviour:\n\n\n\n\n[image: smoothing; source: https://i.sstatic.net/cW1t1avg.png] (https://i.sstatic.net/cW1t1avg.png)\n\n\n\n\nThe sparsity pattern for the problem looks like this (size reduced for visibility):\n\n\n\n\n[image: sparsity; source: https://i.sstatic.net/UmVF5qyE.png] (https://i.sstatic.net/UmVF5qyE.png)\n\n\n\n\nThough the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.", "answer_url": "https://scicomp.stackexchange.com/a/45335", "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-01-10T07:56:42+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": 45334, "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-01-10T07:56:42+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "49224026-A98C-4DFC-B187-28324764F758", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/49224026-A98C-4DFC-B187-28324764F758/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-01-10T15:16:37+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "0462867C-327F-469E-957B-1FE451F4CE5C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/0462867C-327F-469E-957B-1FE451F4CE5C/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-01-10T20:00:35+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "302EF20B-4729-4185-A059-5377ED4B7555", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/302EF20B-4729-4185-A059-5377ED4B7555/view-source"}], "score": 3, "updated_at": "2026-01-10T20:00:35+00:00"}, {"answer_html": "I managed to create a prototype solver based on ADMM in MATLAB:
\nfunction [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n paramLambda (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeNonnegative}\n vI (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBeInteger}\n mA (:, :) {mustBeNumeric, mustBeFinite, mustBeReal}\n sParams.paramRho (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1.0\n sParams.numIter (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 5000\n sParams.epsAbs (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.epsRel (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 1e-5\n sParams.convInterval (1, 1) {mustBeNumeric, mustBeFinite, mustBeInteger, mustBePositive} = 25\n sParams.paramTau (1, 1) {mustBeNumeric, mustBeFinite, mustBeReal, mustBePositive} = 10\nend\n\narguments(Output)\n vX (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n isConv (1, 1) {mustBeA(isConv, 'logical')}\nend\n\nnumSamples = length(vY);\nnumEq = length(vI);\nnumInEq = size(mA, 1);\n\n% Quadratic Terms\nmQ = sparse(eye(numSamples)) + paramLambda * (mD' * mD);\nvQ = -vY;\n\n% Equality Constraints\nmE = sparse(1:numEq, vI, 1, numEq, numSamples);\nvD = vY(vI);\n\nparamRho = sParams.paramRho;\nparamRhoInv = inv(paramRho);\nnumIter = sParams.numIter;\nepsAbs = sParams.epsAbs;\nepsRel = sParams.epsRel;\nconvInterval = sParams.convInterval;\nparamTau = sParams.paramTau;\n\n% ADMM Variables\nvX = vY; %<! Optimization variable\nvS = zeros(numInEq, 1); %<! Slack variable for inequality\nvS1 = zeros(numInEq, 1); %<! Preious iteration buffer\nvMu = zeros(numInEq, 1); %<! Dual variable for inequality\nvNu = zeros(numEq, 1); %<! Dual variabe for equality\n\n% Factorize the KKT System\n% (Q + rho * A' * A + rho * E' * E) * z = r\nmK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\nsK = decomposition(mK, 'chol', 'CheckCondition', false);\n\nisConv = false;\nupdatedRho = false;\n\nfor ii = 1:numIter\n vS1(:) = vS; %<! Previous iteration\n\n % Solve the Linear System\n vR = -vQ - mA.' * (paramRho * vS + vMu) + mE.' * (paramRho * vD - vNu); %<! Right hand vector\n vX = sK \\ vR;\n\n % Proximal / Projection Step\n % s = -A * z with s >= 0\n vS = max(0, -(mA * vX + paramRhoInv * vMu));\n\n % Update Dual Variables\n vMu = vMu + paramRho * (mA * vX + vS);\n vNu = vNu + paramRho * (mE * vX - vD);\n\n % Check Convergence\n if mod(ii, convInterval) == 0\n primRes = norm(mA * vX + vS, 'inf');\n dualRes = norm(paramRho * mA' * (vS - vS1), 'inf');\n if ((primRes < epsAbs) && (dualRes < epsAbs))\n isConv = true;\n break;\n end\n\n % Adpat `paramRho`\n resRatio = primRes / dualRes;\n % fprintf('Primal Residual: %0.7f, Dual Residual: %0.7f\\n', primRes, dualRes);\n % fprintf('Residual Ratio: %0.2f, ρ = %0.3f\\n', resRatio, paramRho);\n if (resRatio > paramTau) || (inv(resRatio) > paramTau)\n updatedRho = true;\n else\n updatedRho = false;\n end\n if updatedRho\n paramRho = paramRho * sqrt(resRatio);\n paramRho = clip(paramRho, 1e-5, 1e5);\n paramRhoInv = inv(paramRho);\n mK = mQ + paramRho * (mA.' * mA) + paramRho * (mE.' * mE);\n sK = decomposition(mK, 'chol', 'CheckCondition', false);\n end\n end\n\nend\n\nend\n\nI has convergence check and adaptation of the ADMM's step size parameter $\\rho$.
\nI will add mathematical formulation and a memory optimized version using Julia.
On MATLAB with this naive code I could beat quadprog() by 30% with the same output:
I produced an ADMM based solver which I found very efficient.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nI will use $\\boldsymbol{D} = \\boldsymbol{D}^{m}$ to simplify notations.
\nThe equality constraints can be turned into matrix form and the problem becomes:
$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} = \\boldsymbol{0} \\\\\n& \\quad & \\boldsymbol{s} \\geq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nThe equality constraints are introduced by the Augmented Lagrangian:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}, \\boldsymbol{s}, \\boldsymbol{\\mu}, \\boldsymbol{\\nu} \\right) = \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} + {\\rho}^{-1} \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{E} \\boldsymbol{x} - \\boldsymbol{d} + {\\rho}^{-1} \\boldsymbol{\\nu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe stopping condition is when both residuals are below a threshold:
\nThe use of the infinity norm decouples the dimension of the problem from the thresholds.
\nI also used OSQP style update of the $\\rho$ parameter to accelerate convergence: ${\\rho}^{\\left( k \\right)} = {\\rho}^{\\left( k - 1 \\right)} \\sqrt{ \\frac{ {r}^{\\left( k \\right)} }{ {s}^{\\left( k \\right)} } }$.
\nI implemented all in Julia and compared to the ECOS / SCS solvers wrapped by Convex.jl.
Run Times:
\nBenchmarkTools.Trial: 1227 samples with 1 evaluation per sample.\n Range (min … max): 3.412 ms … 18.615 ms ┊ GC (min … max): 0.00% … 60.46%\n Time (median): 3.807 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 4.061 ms ± 859.845 μs ┊ GC (mean ± σ): 1.67% ± 5.36%\n\n ▅█▇▄▃ ▁\n ▄████████▇▆▇▅▆▅▅▄▄▃▃▃▃▄▃▄▄▄▃▃▃▃▃▃▂▂▂▂▃▃▂▂▂▃▂▂▂▂▂▂▂▂▂▂▂▂▁▂▂▂ ▃\n 3.41 ms Histogram: frequency by time 6.54 ms <\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n\nBenchmarkTools.Trial: 98 samples with 1 evaluation per sample.\n Range (min … max): 49.280 ms … 53.704 ms ┊ GC (min … max): 0.00% … 0.00%\n Time (median): 50.892 ms ┊ GC (median): 0.00%\n Time (mean ± σ): 51.055 ms ± 918.217 μs ┊ GC (mean ± σ): 0.00% ± 0.00%\n\n ▁ ▃ ▁▁▁█ █▃ ▁ ▃ ▁ ▆ ▁ ▁\n ▄▁▁▇▁█▁▁▄▄▇▄▄▇█▇████▇██▄█▇█▄█▄▁▄█▄▇▇█▁▇▄▄▄▄▁▇▇▄▄█▄▁▄▄▁▄▁▁▁▁▇ ▁\n 49.3 ms Histogram: frequency by time 53.2 ms <\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n\nBenchmarkTools.Trial: 7569 samples with 1 evaluation per sample.\n Range (min … max): 447.700 μs … 23.329 ms ┊ GC (min … max): 0.00% … 70.82%\n Time (median): 651.300 μs ┊ GC (median): 0.00%\n Time (mean ± σ): 656.690 μs ± 412.333 μs ┊ GC (mean ± σ): 1.30% ± 2.26%\n\n ▁▄▄▁ ▁▃▅▅▆▆█▇▇▆▅▄▂▁▁\n ▃████▆▄▃▂▂▂▂▂▁▂▃▅███████████████▇▆▆▄▅▄▄▄▃▃▂▂▂▂▂▂▂▂▂▁▁▂▁▁▁▁▁▁▁ ▄\n 448 μs Histogram: frequency by time 970 μs <\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n\nThe ADMM method is an order of magnitude faster than the generic solvers.
\nIt can be greatly improved as it designed for arbitrary matrix $\\boldsymbol{E}$. It can be farther optimized for the case of equality.
The code is available on my StackExchange Code GitHub Repository (Look at the ComputationalScience\\Q45334 folder).
Another formulation take advantage of the equality constraint to make the problem formulation smaller.
\nThe problem is given by:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:
\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$
\nThen the above can be formulated as:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$
\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.
\nThis formulation reduces the number of constraints to handle.
\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.
The Augmented Lagrangian (Scaled form) is given by:
\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$
\nThe steps to solve:
\nThe rest is similar to above with the needed adjustments for the residuals calculations.
\nThis implementation reduced another 40 [Micro Sec] of the run time.
\n", "answer_id": 45342, "answer_text": "Another formulation take advantage of the equality constraint to make the problem formulation smaller.\n\n\n\n\nThe problem is given by:\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} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nLet $\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$ then define:\n\n\n\n\n$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} && \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} && \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$\n\n\n\n\nThen the above can be formulated as:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } & \\quad & \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} \\\\\n\\text{subject to} & \\quad & \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{P} = \\boldsymbol{I} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{J}}, \\; \\boldsymbol{q} = - \\boldsymbol{y}_{\\mathcal{J}} + \\lambda \\boldsymbol{D}_{\\mathcal{J}}^{\\top} \\boldsymbol{D}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}, \\; \\boldsymbol{b} = \\boldsymbol{A}_{\\mathcal{I}} \\boldsymbol{y}_{\\mathcal{I}}$.\n\n\n\n\nThis formulation reduces the number of constraints to handle.\n\nThe inequality is treated by introducing a slack variable $\\boldsymbol{s} \\geq \\boldsymbol{0}$ such that $\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$.\n\n\n\n\nThe Augmented Lagrangian (Scaled form) is given by:\n\n\n\n\n$$\n{\\ell}_{\\rho} \\left( \\boldsymbol{x}_{\\mathcal{J}}, \\boldsymbol{s}, \\boldsymbol{\\mu} \\right) = \\frac{1}{2} \\boldsymbol{x}_{\\mathcal{J}}^{\\top} \\boldsymbol{P} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{q}^{\\top} \\boldsymbol{x}_{\\mathcal{J}} + \\frac{\\rho}{2} {\\left\\| \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} - \\boldsymbol{b} + \\boldsymbol{\\mu} \\right\\|}_{2}^{2} + {I}_{\\mathbb{R}_{+}} \\left( \\boldsymbol{s} \\right)\n$$\n\n\n\n\nThe steps to solve:\n\n\n\n\n\nPrimal Update (Solve Linear System): $\\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} = {\\left( \\boldsymbol{P} + \\rho \\boldsymbol{A}_{\\mathcal{J}}^{\\top} \\boldsymbol{A}_{\\mathcal{J}} \\right)}^{-1} \\left( - \\boldsymbol{q} + \\rho \\boldsymbol{A}_{\\mathcal{J}} \\left( \\boldsymbol{b} - \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) \\right)$.\n\n\n\n\nSlack Update (Non Negative LS / Projection): $\\boldsymbol{s}^{\\left( k + 1 \\right)} = \\max \\left(\\boldsymbol{0}, \\boldsymbol{b} - \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} - \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent): $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\left( \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} - \\boldsymbol{b} \\right)$.\n\n\n\n\n\nThe rest is similar to above with the needed adjustments for the residuals calculations.\n\n\n\n\nThis implementation reduced another 40 [Micro Sec] of the run time.", "answer_url": "https://scicomp.stackexchange.com/a/45342", "author": "Royi", "author_url": "https://scicomp.stackexchange.com/users/7951/royi", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-01-17T12:18:23+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": 45334, "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": "2026-01-17T12:18:23+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9FE8A84D-E3F5-41A7-B296-8A0BBB5EB8BB/view-source"}], "score": 1, "updated_at": "2026-01-17T12:18:23+00:00"}], "domain": "computational_science", "external_links": ["https://github.com/RoyiAvital/StackExchangeCodes", "https://github.com/cvxgrp/scs", "https://github.com/embotech/ecos", "https://github.com/jump-dev/Convex.jl", "https://i.sstatic.net/UmVF5qyE.png", "https://i.sstatic.net/VC8uzUSt.png", "https://i.sstatic.net/cW1t1avg.png", "https://i.sstatic.net/f5YcjFm6.png", "https://i.sstatic.net/oTyX0oWA.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": "Royi", "question_author_url": "https://scicomp.stackexchange.com/users/7951/royi", "question_author_user_type": "registered", "question_created_at": "2026-01-09T11:12:06+00:00", "question_html": "Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.
\nI want to smooth the curve with the following properties:
\nI came up with the following model:
\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$
\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.
\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.
\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.
\n", "question_id": 45334, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "Let a 1D curve defined by $\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$ sampled on a uniform grid.\n\n\n\n\nI want to smooth the curve with the following properties:\n\n\n\n\n\nThe result, $\\left\\{ {z}_{1}, {z}_{2}, \\ldots {z}_{n} \\right\\}$ should be smooth like Spline based method.\n\n\n\n\nFor a set of indices $\\mathcal{I}$ the smoothed curve must go through the reference point, namely ${z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I}$.\n\n\n\n\nThe smoothed values between 2 reference points must be monotonic.\n\n\n\n\n\nI came up with the following model:\n\n\n\n\n$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } & \\quad & \\frac{1}{2} \\left\\| \\boldsymbol{z} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\lambda {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{z} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} & \\quad & {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nWhere $\\boldsymbol{D}^{m}$ is the $m$ -th derivative operator.\n\n\n\n\nI am looking for a fast way to solve the problem for the case of 50-1500 samples.\n\n\n\n\nI rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.", "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": "2026-01-09T11:12:06+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "47824E2B-27A9-4037-A643-E3F6522A8C95", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/47824E2B-27A9-4037-A643-E3F6522A8C95/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": "2026-01-09T11:26:36+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "DD8F78BB-E8A8-4203-A2E1-CBE9167BB83E", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DD8F78BB-E8A8-4203-A2E1-CBE9167BB83E/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": "2026-01-10T07:58:10+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "2599F6AB-3F4E-455C-9665-0A36994C9F01", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2599F6AB-3F4E-455C-9665-0A36994C9F01/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-01-10T17:02:45+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "DE676BCF-D21E-4A19-B947-DB9D0FD71DA6", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/DE676BCF-D21E-4A19-B947-DB9D0FD71DA6/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45334/solving-regularized-least-squares-with-linear-equality-and-linear-inequality-con", "split": "train", "split_group": "f136ae78b6249a1eba9450dcaebaadcc09a41c6eb57a74d9f7e7aba798cd242d", "tags": ["linear-algebra", "optimization", "constrained-optimization", "convex-optimization", "curve-fitting"], "thread_id": "scicomp:45334", "title": "Solving Regularized Least Squares with Linear Equality and Linear Inequality Constraints for Curve Smoothing"}} {"accepted_answer": {"answer_html": "Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n
Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n
Ok, I figured it out after all, it was just a silly misunderstanding. The problem is that I misunderstood the way the Hamiltonian is defined. What I had in mind was the Hamiltonian:\n$$\nH = -J \\sum_i Z_i Z_{i+1} - h \\sum_i X_i\n$$\nwhich is correct, but I thought that the parameter $g$ was the same as the parameter $h$, because the documentation said it was the transverse field. What I failed to notice is that the Hamiltonian they use is\n$$\nH = -J (\\sum_i Z_i Z_{i+1} + g \\sum_i X_i)\n$$\nso, $g$ is not $h$, it is $g=h/J$. So the phase diagram I was getting was actually correct, it just didn't have the parameters that I expected. If I used $h$ as a parameter by correctly passing $g \\to g=h/J$, then I would get the diagram I expected:\n
If I am not mistaken, the transverse field Ising model should have a ground state which displays ferromagnetic order for $|J/g|>1$ with positive $J$ (here $J$ is the coupling and $g$ the transverse field) and disorder or Neel order otherwise. In the first case the magnetization should be 1, and in the second it should be 0.
\nI tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5<g<0.5$. In other words, it doesn't matter how strong or weak $J$ is (as long as it is positive), there is always ferromagnetic order as long as $|g|$ is smaller than $0.5$, and $M=0$ everywhere else.
\nThis is a very odd result that doesn't make sense to me, so I am inclined to believe there is something wrong with my computational methods. I attach the code I used and the diagram that it produced. My code closely mirrors the example from MPSKit.jl's github:
\nusing MPSKit, MPSKitModels, TensorKit \nusing Plots, ProgressMeter\n\nD = 6\ninit_state = InfiniteMPS(ℂ^2, ℂ^D)\n\ng_values = 0.0:0.2:2.0\nJ_values = -2.01:0.5:2.01\n\nM = @showprogress map(Iterators.product(g_values, J_values)) do (g,J)\n H = transverse_field_ising(; J=J, g=g)\n groundstate, environment, δ = find_groundstate(init_state, H, VUMPS(; verbosity=0))\n return abs(expectation_value(groundstate, 1 => σᶻ()))\nend\n\nheatmap(J_values, g_values, M, \n xlabel="J", ylabel="g", title="Magnetization M(g, J)")\n\nAnd here is the resulting heatmap:
\n\nI tried increasing the bond dimension $D$, but it did nothing. Now, this is VUMPS, but I got the same result more or less with finite $L$ DMRG. I'm at my wit's end! Any help would be appreciated.
\n", "question_id": 45344, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "If I am not mistaken, the transverse field Ising model should have a ground state which displays ferromagnetic order for $|J/g|>1$ with positive $J$ (here $J$ is the coupling and $g$ the transverse field) and disorder or Neel order otherwise. In the first case the magnetization should be 1, and in the second it should be 0.\n\n\n\n\nI tried to run a DMRG simulation, and instead of this behavior, the $M=1$ phase appears for $J>0$ and $-0.5The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)
\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}
\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.
\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}
\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.
\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:
\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f"Numerical Result: {result:.10f}")\n# Result from WolframAlpha = 0.0187983\n\n", "answer_id": 45394, "answer_text": "The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)\n\n\n\n\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}\n\n\n\n\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.\n\n\n\n\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}\n\n\n\n\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.\n\n\n\n\nCode example\n\n\n\n\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:\n\n\n\n\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983", "answer_url": "https://scicomp.stackexchange.com/a/45394", "author": "mle", "author_url": "https://scicomp.stackexchange.com/users/46538/mle", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-03-04T18:29:45+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": 45362, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "mle", "profile_url": "https://scicomp.stackexchange.com/users/46538/mle", "user_type": "registered"}, "created_at": "2026-03-04T18:29:45+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "D8A9E199-F055-462B-8A0D-91FD9CE698F5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}], "score": 2, "updated_at": "2026-03-04T18:29:45+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)
\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}
\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.
\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}
\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.
\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:
\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f"Numerical Result: {result:.10f}")\n# Result from WolframAlpha = 0.0187983\n\n", "answer_id": 45394, "answer_text": "The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)\n\n\n\n\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}\n\n\n\n\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.\n\n\n\n\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}\n\n\n\n\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.\n\n\n\n\nCode example\n\n\n\n\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:\n\n\n\n\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983", "answer_url": "https://scicomp.stackexchange.com/a/45394", "author": "mle", "author_url": "https://scicomp.stackexchange.com/users/46538/mle", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-03-04T18:29:45+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": 45362, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "mle", "profile_url": "https://scicomp.stackexchange.com/users/46538/mle", "user_type": "registered"}, "created_at": "2026-03-04T18:29:45+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "D8A9E199-F055-462B-8A0D-91FD9CE698F5", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}], "score": 2, "updated_at": "2026-03-04T18:29:45+00:00"}], "domain": "computational_science", "external_links": [], "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": "vibe", "question_author_url": "https://scicomp.stackexchange.com/users/28440/vibe", "question_author_user_type": "registered", "question_created_at": "2026-02-04T15:10:39+00:00", "question_html": "I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.
\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.
\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.
\n", "question_id": 45362, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.\n\n\n\n\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.\n\n\n\n\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "vibe", "profile_url": "https://scicomp.stackexchange.com/users/28440/vibe", "user_type": "registered"}, "created_at": "2026-02-04T15:10:39+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "9B775FCA-6689-4886-BE87-22C985705EFF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9B775FCA-6689-4886-BE87-22C985705EFF/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45362/quadrature-rule-for-ratio-of-polynomials", "split": "train", "split_group": "559c940425b563972be618e91f2ad04e0e7f4e9954fff19ed9350b4bea807ada", "tags": ["integration", "quadrature", "polynomials"], "thread_id": "scicomp:45362", "title": "Quadrature rule for ratio of polynomials"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": " // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // in x direction\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 1.0;\n beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n for (int i = 1; i < Nx; i++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -theta[i][j] / dt;\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n }\n\n // Right wall (i = Nx) - insulated\n // For Neumann condition on the right wall, we need a special formula\n // Using first order: Theta[Nx] = Theta[Nx-1]\n theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]); // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n {\n theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n }\n }\n\n // sweep in y direction (vertical)\n for (int i = 1; i < Nx; i++)\n {\n // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n // Using implicit scheme for Neumann condition with flux\n double flux_bottom = -1.0; // heat enters\n\n alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n // Forward sweep for interior nodes\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double B = A + C + 1.0 / dt;\n\n double F = -theta[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n double flux_top = 0.5; // heat exits\n\n // For top wall with flux, we use the relationship from the forward sweep\n // combined with the flux condition\n theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n // Back substitution\n for (int j = Ny - 1; j >= 0; j--)\n {\n theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n }\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "d81fd16ae667dfb8efe92a3dda8a25f1a01e7ae62e280e6f57c915faf6a9265d", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 1, "code_text": "// Omega in x direction\nvoid solveOmegaX(\n double psi[Nx + 1][Ny + 1],\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 0.0; // from boundary conditions\n beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n for (int i = 1; i < Nx; i++)\n {\n double k = sqrt(Pr / Ra) /\n (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n }\n\n omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n double psi[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int i = 1; i < Nx; i++)\n {\n alpha[0] = 0.0; // bottom wall\n beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n // back substitution\n for (int j = Ny - 1; j >= 0; j--)\n omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "0ff70c4acae7ce49e4ba6a456dcfb50acf9848af56d6d6cfd2ba003acc2b42c0", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 2, "code_text": "// PSI equation\nvoid solvePsi(\n double psi[Nx + 1][Ny + 1],\n double psik[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double hx, double hy,\n double relax, double eps)\n{\n double max_diff = 1.0, psi_new;\n // This cycle from the lecture line ***\n while (max_diff > eps)\n {\n max_diff = 0.0;\n\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n psi_new =\n (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n hx * hx * hy * hy * omega[i][j]) /\n (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n double diff = fabs(psi[i][j] - psik[i][j]);\n if (diff > max_diff)\n max_diff = diff;\n }\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "287d4fd2bd10409c0afec92b345d9927a085e1409a4d4e69e112658316bd1de1", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 3, "code_text": "// Velocities\n// using formula \nvoid computeVelocity(\n double psi[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double hx, double hy)\n{\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "c8ee4a8e2f292c4de523aa887dc5d69dcc882f56e8ce9a348ee5fe51ca071886", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 4, "code_text": " // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n // Boundary conditions for psi (psi=0 on all walls)\n for (int i = 0; i <= Nx; i++)\n {\n psi[i][0] = 0.0; // bottom wall\n psi[i][Ny] = 0.0; // top wall\n }\n for (int j = 0; j <= Ny; j++)\n {\n psi[0][j] = 0.0; // left wall\n psi[Nx][j] = 0.0; // right wall\n }\n}\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45377, "sha256": "9fe12fd49b69dcf79f44653d42997784ead03639737baf06c0857f5384c12f14", "source_url": "https://scicomp.stackexchange.com/questions/45377/my-code-gives-inverted-temperatures-for-natural-convection-problem-c"}, {"block_index": 5, "code_text": "#includeit seems you are trying to simulate a Rayleigh-Benard convection in a cavity. It is typically coupled with flow field, which you are trying to simulate through omega-psi formulation. No, I believe the convection currents and temperature fields will look different than what you have shown in the picture. For clarity, can you check the following steps 1) Simulate a moving cavity lid at different Re numbers and compare against standard literature (like Ghia et.al (1982)). This freezes multiple things like verification of upwind schemes etc. 2) Recheck the enthalpy/heat equation whether the convection terms are taken care properly. For reference, typically over time, it should develop into convection cells. Please find my simulations for omega-psi attached in below picture
it seems you are trying to simulate a Rayleigh-Benard convection in a cavity. It is typically coupled with flow field, which you are trying to simulate through omega-psi formulation. No, I believe the convection currents and temperature fields will look different than what you have shown in the picture. For clarity, can you check the following steps 1) Simulate a moving cavity lid at different Re numbers and compare against standard literature (like Ghia et.al (1982)). This freezes multiple things like verification of upwind schemes etc. 2) Recheck the enthalpy/heat equation whether the convection terms are taken care properly. For reference, typically over time, it should develop into convection cells. Please find my simulations for omega-psi attached in below picture
Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:
\n\n\n$0 \\leq x \\leq 1.5 0 \\leq y \\leq 1.0$ Pr = 7, Re = 7 Ra= 1e3, 1e4 $\\ldots$1e7.\nLeft and right walls are insulated. At the bottom wall $q_1= 1000$ and at\nthe upper wall $q_2=0.5*q_1$
\n
The temperature field generated by my cpp code was used on SurferProgram to visualize the isothermic lines. Physically it does not make sense, at the bottom where the heat flux is positive, temperature is the lowest, at the upper-- the hottest.
\nThe isotherms are straight horizontal lines. It looks like the heat conduction of a block of copper when one of the wall has higher constant temperature
\nMay be a problem when defining the heat flux in solveTemperature function. Shouldnt the isotherms be waivier? The walls are nonpermeable (no liquid passes trouht them).
I tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.\nThis image is for Ra = 1e3\n
Here is the piece of code for calculating the temperatures
\n // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // in x direction\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 1.0;\n beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n for (int i = 1; i < Nx; i++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -theta[i][j] / dt;\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n }\n\n // Right wall (i = Nx) - insulated\n // For Neumann condition on the right wall, we need a special formula\n // Using first order: Theta[Nx] = Theta[Nx-1]\n theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]); // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n {\n theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n }\n }\n\n // sweep in y direction (vertical)\n for (int i = 1; i < Nx; i++)\n {\n // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n // Using implicit scheme for Neumann condition with flux\n double flux_bottom = -1.0; // heat enters\n\n alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n // Forward sweep for interior nodes\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double B = A + C + 1.0 / dt;\n\n double F = -theta[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n double flux_top = 0.5; // heat exits\n\n // For top wall with flux, we use the relationship from the forward sweep\n // combined with the flux condition\n theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n // Back substitution\n for (int j = Ny - 1; j >= 0; j--)\n {\n theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n }\n }\n}\n\nVortex solver
\n// Omega in x direction\nvoid solveOmegaX(\n double psi[Nx + 1][Ny + 1],\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 0.0; // from boundary conditions\n beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n for (int i = 1; i < Nx; i++)\n {\n double k = sqrt(Pr / Ra) /\n (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n }\n\n omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n double psi[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int i = 1; i < Nx; i++)\n {\n alpha[0] = 0.0; // bottom wall\n beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n // back substitution\n for (int j = Ny - 1; j >= 0; j--)\n omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n }\n}\n\nStream function solver
\n// PSI equation\nvoid solvePsi(\n double psi[Nx + 1][Ny + 1],\n double psik[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double hx, double hy,\n double relax, double eps)\n{\n double max_diff = 1.0, psi_new;\n // This cycle from the lecture line ***\n while (max_diff > eps)\n {\n max_diff = 0.0;\n\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n psi_new =\n (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n hx * hx * hy * hy * omega[i][j]) /\n (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n double diff = fabs(psi[i][j] - psik[i][j]);\n if (diff > max_diff)\n max_diff = diff;\n }\n }\n}\n\nVelocity calculator
\n// Velocities\n// using formula \nvoid computeVelocity(\n double psi[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double hx, double hy)\n{\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n }\n}\n\nSetting boundary conditions
\n // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n // Boundary conditions for psi (psi=0 on all walls)\n for (int i = 0; i <= Nx; i++)\n {\n psi[i][0] = 0.0; // bottom wall\n psi[i][Ny] = 0.0; // top wall\n }\n for (int j = 0; j <= Ny; j++)\n {\n psi[0][j] = 0.0; // left wall\n psi[Nx][j] = 0.0; // right wall\n }\n}\n\nThis is the main code
\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\nusing namespace std;\nconstexpr int Nx = 180;\nconstexpr int Ny = 60;\n\n int main()\n {\n const double Lx = 1.5, Ly = 1.0;\n const double hx = Lx / Nx, hy = Ly / Ny;\n const double Pr = 0.7, Ra = 1e8, dt = 0.001;\n const double eps = 1e-6, relax = 1.0;\n \n double t = 0.0, t_k = 10.0;\n \n static double psi[Nx + 1][Ny + 1]{}, psik[Nx + 1][Ny + 1]{}, omega[Nx + 1][Ny + 1]{};\n static double theta[Nx + 1][Ny + 1]{}, u[Nx + 1][Ny + 1]{}, v[Nx + 1][Ny + 1]{};\n static double alpha[(Nx > Ny ? Nx : Ny) + 1]{}, beta[(Nx > Ny ? Nx : Ny) + 1]{}; // if Nx > Ny then take Nx\n // otherwise take Ny\n \n while (t < t_k)\n {\n applyPsiBC(psi);\n solvePsi(psi, psik, omega, hx, hy, relax, eps);\n computeVelocity(psi, u, v, hx, hy);\n solveOmegaX(psi, theta, u, omega, alpha, beta, hx, dt, Pr, Ra);\n solveOmegaY(psi, v, omega, alpha, beta, hy, dt, Pr, Ra);\n solveTemperature(theta, u, v, alpha, beta, hx, hy, dt, Pr, Ra);\n \n t += dt;\n cout << t << endl;\n }\n \n // OUTPUT to files\n ofstream fpsi("psitest.txt"), fomega("omegatest.txt"), ftheta("thetatest.txt");\n \n for (int i = 0; i <= Nx; i++)\n {\n for (int j = 0; j <= Ny; j++)\n {\n double x = i * hx;\n double y = j * hy;\n fomega << x << " " << y << " " << omega[i][j] << "\\n";\n ftheta << x << " " << y << " " << theta[i][j] << "\\n";\n fpsi << x << " " << y << " " << psi[i][j] << "\\n";\n }\n }\n \n cout << "Calculation completed. Files: psitest.txt, omegatest.txt, thetatest.txt\\n";\n return 0;\n }\n\n", "question_id": 45377, "question_license": "CC BY-SA 4.0", "question_score": 0, "question_text": "Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:\n\n\n\n\n\n\n\n$0 \\leq x \\leq 1.5 0 \\leq y \\leq 1.0$ Pr = 7, Re = 7 Ra= 1e3, 1e4 $\\ldots$1e7.\nLeft and right walls are insulated. At the bottom wall $q_1= 1000$ and at\nthe upper wall $q_2=0.5*q_1$\n\n\n\n\n\n\n\nThe temperature field generated by my cpp code was used on SurferProgram to visualize the isothermic lines. Physically it does not make sense, at the bottom where the heat flux is positive, temperature is the lowest, at the upper-- the hottest.\n\n\n\n\nThe isotherms are straight horizontal lines. It looks like the heat conduction of a block of copper when one of the wall has higher constant temperature\n\n\n\n\nMay be a problem when defining the heat flux in solveTemperature function. Shouldnt the isotherms be waivier? The walls are nonpermeable (no liquid passes trouht them).\n\n\n\n\nI tried using higher Ra, there were substancial changes, but still dont know if is physically accurate.\nThis image is for Ra = 1e3\n[image: for Ra = 1e3; source: https://i.sstatic.net/Z4fMSBrm.png] (https://i.sstatic.net/Z4fMSBrm.png)\n\n\n\n\nThis image is for Ra = 1e7\n[image: for Ra = 1e7; source: https://i.sstatic.net/4a2ls0zL.png] (https://i.sstatic.net/4a2ls0zL.png)\n\n\n\n\nHere is the piece of code for calculating the temperatures\n\n\n\n\n // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // in x direction\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 1.0;\n beta[0] = 0.0; // because boundary condition on left wall: theta=1\n\n for (int i = 1; i < Nx; i++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -theta[i][j] / dt;\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]);\n }\n\n // Right wall (i = Nx) - insulated\n // For Neumann condition on the right wall, we need a special formula\n // Using first order: Theta[Nx] = Theta[Nx-1]\n theta[Nx][j] = beta[Nx - 1] / (1.0 - alpha[Nx - 1]); // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n {\n theta[i][j] = alpha[i] * theta[i + 1][j] + beta[i];\n }\n }\n\n // sweep in y direction (vertical)\n for (int i = 1; i < Nx; i++)\n {\n // BOTTOM wall (j = 0) - heat flux IN: dTheta/dY = -1\n // Using implicit scheme for Neumann condition with flux\n double flux_bottom = -1.0; // heat enters\n\n alpha[0] = 2.0 * dt / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt);\n beta[0] = (hy * hy * sqrt(Pr * Ra) / (hy * hy * sqrt(Pr * Ra) + 2.0 * dt)) *\n (theta[i][0] + (dt * flux_bottom) / (hy * sqrt(Pr * Ra)));\n\n // Forward sweep for interior nodes\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 / (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n double A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n double B = A + C + 1.0 / dt;\n\n double F = -theta[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n // TOP wall (j = Ny) - heat flux OUT: dTheta/dY = +0.5\n double flux_top = 0.5; // heat exits\n\n // For top wall with flux, we use the relationship from the forward sweep\n // combined with the flux condition\n theta[i][Ny] = (beta[Ny - 1] + hy * flux_top) / (1.0 - alpha[Ny - 1]);\n\n // Back substitution\n for (int j = Ny - 1; j >= 0; j--)\n {\n theta[i][j] = alpha[j] * theta[i][j + 1] + beta[j];\n }\n }\n}\n\n\n\n\n\nVortex solver\n\n\n\n\n// Omega in x direction\nvoid solveOmegaX(\n double psi[Nx + 1][Ny + 1],\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int j = 1; j < Ny; j++)\n {\n alpha[0] = 0.0; // from boundary conditions\n beta[0] = -2.0 * psi[1][j] / (hx * hx);\n\n for (int i = 1; i < Nx; i++)\n {\n double k = sqrt(Pr / Ra) /\n (1.0 + fabs(u[i][j]) * hx * 0.5 * sqrt(Ra / Pr));\n\n A = k / (hx * hx) - u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n C = k / (hx * hx) + u[i][j] / (2 * hx) + fabs(u[i][j]) / (2 * hx);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt - (theta[i + 1][j] - theta[i - 1][j]) / (2 * hx);\n\n alpha[i] = A / (B - C * alpha[i - 1]);\n beta[i] = (C * beta[i - 1] - F) / (B - C * alpha[i - 1]); // All formulas from lecture in notebook\n }\n\n omega[Nx][j] = -2.0 * (psi[Nx - 1][j] - psi[Nx][j]) / (hx * hx); // right wall\n\n // back substitution\n for (int i = Nx - 1; i >= 0; i--)\n omega[i][j] = alpha[i] * omega[i + 1][j] + beta[i];\n }\n}\n\n// Omega in y direction\nvoid solveOmegaY(\n double psi[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n for (int i = 1; i < Nx; i++)\n {\n alpha[0] = 0.0; // bottom wall\n beta[0] = -2.0 * psi[i][1] / (hy * hy);\n\n for (int j = 1; j < Ny; j++)\n {\n double k = 1.0 /\n (sqrt(Pr * Ra) * (1.0 + fabs(v[i][j]) * hy * 0.5 * sqrt(Pr * Ra)));\n\n A = k / (hy * hy) - v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n C = k / (hy * hy) + v[i][j] / (2 * hy) + fabs(v[i][j]) / (2 * hy);\n B = A + C + 1.0 / dt;\n\n F = -omega[i][j] / dt;\n\n alpha[j] = A / (B - C * alpha[j - 1]);\n beta[j] = (C * beta[j - 1] - F) / (B - C * alpha[j - 1]);\n }\n\n omega[i][Ny] = -2.0 * (psi[i][Ny - 1] - psi[i][Ny]) / (hy * hy); // top wall\n\n // back substitution\n for (int j = Ny - 1; j >= 0; j--)\n omega[i][j] = alpha[j] * omega[i][j + 1] + beta[j];\n }\n}\n\n\n\n\n\nStream function solver\n\n\n\n\n// PSI equation\nvoid solvePsi(\n double psi[Nx + 1][Ny + 1],\n double psik[Nx + 1][Ny + 1],\n double omega[Nx + 1][Ny + 1],\n double hx, double hy,\n double relax, double eps)\n{\n double max_diff = 1.0, psi_new;\n // This cycle from the lecture line ***\n while (max_diff > eps)\n {\n max_diff = 0.0;\n\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n psik[i][j] = psi[i][j]; // psi_k - from previous iteration\n\n psi_new =\n (hy * hy * (psi[i - 1][j] + psi[i + 1][j]) +\n hx * hx * (psi[i][j - 1] + psi[i][j + 1]) +\n hx * hx * hy * hy * omega[i][j]) /\n (2.0 * (hx * hx + hy * hy)); // psi_new is psi with hat from lecture\n\n psi[i][j] = psik[i][j] + relax * (psi_new - psik[i][j]);\n\n double diff = fabs(psi[i][j] - psik[i][j]);\n if (diff > max_diff)\n max_diff = diff;\n }\n }\n}\n\n\n\n\n\nVelocity calculator\n\n\n\n\n// Velocities\n// using formula \nvoid computeVelocity(\n double psi[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double hx, double hy)\n{\n for (int i = 1; i < Nx; i++)\n for (int j = 1; j < Ny; j++)\n {\n u[i][j] = (psi[i][j + 1] - psi[i][j - 1]) / (2.0 * hy); // central difference approximation\n v[i][j] = -(psi[i + 1][j] - psi[i - 1][j]) / (2.0 * hx);\n }\n}\n\n\n\n\n\nSetting boundary conditions\n\n\n\n\n // Boundary conditions for PSI\nvoid applyPsiBC(double psi[Nx + 1][Ny + 1])\n{\n // Boundary conditions for psi (psi=0 on all walls)\n for (int i = 0; i <= Nx; i++)\n {\n psi[i][0] = 0.0; // bottom wall\n psi[i][Ny] = 0.0; // top wall\n }\n for (int j = 0; j <= Ny; j++)\n {\n psi[0][j] = 0.0; // left wall\n psi[Nx][j] = 0.0; // right wall\n }\n}\n\n\n\n\n\nThis is the main code\n\n\n\n\n#include Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n", "answer_id": 45388, "answer_text": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.", "answer_url": "https://scicomp.stackexchange.com/a/45388", "author": "wim", "author_url": "https://scicomp.stackexchange.com/users/5286/wim", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-02-27T09:44:31+00:00", "is_accepted": true, "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": 45387, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-27T09:44:31+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "42AA8384-A67D-4B93-8A67-6F2708905EFF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-28T23:54:12+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "3E89E9AE-7857-41C4-8456-59AB2D1A01FD", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-02T09:09:00+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "98F99AB1-1D15-4C9A-942A-7E8E8455BA0F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}], "score": 7, "updated_at": "2026-03-02T09:09:00+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "function [x, y] = ThreeProduct(a, b, c)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45387, "sha256": "bd4356e06b4e83b3708b56f9d06ac35cfeedc70c4f5106650611050aae8f90f8", "source_url": "https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers"}, {"block_index": 1, "code_text": "function [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45387, "sha256": "80ed3e97e5f90454b0f805d53e1135475404e4eec18ee94dae66478e44276393", "source_url": "https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers"}], "other_answers": [], "product": "code_qa", "question": "TL;DR: I am looking for a function that computes the product of three floating point numbers:\n\n\n\n\nfunction [x, y] = ThreeProduct(a, b, c)\n\n\n\n\n\nSuch that:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\n\n\n\nBackground\n\n\n\n\nOgita et al. (2005) introduced a method of computing a dot product based on \"Error Free Transformation\" primitives, such as TwoSum() (due to Knuth) and TwoProduct():\n\n\n\n\nfunction [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\n\n\n\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name \"Error Free Transformation\". That is, for TwoSum():\n\n\n\n\n$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$\n\n\n\n\nAnd for TwoProduct():\n\n\n\n\n$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$\n\n\n\n\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.\n\n\n\n\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.\n\n\n\n\nMy question is whether there is a known algorithm for the product of three floating point numbers (\"ThreeProduct()\"). That is, something where the following holds:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.\n\n\n\n\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.\n\n\n\n\n\n\n\nReferences:\n\n\n\n\nOgita, T. et al., \"Accurate Sum and Dot Product\", SIAM Journal of Scientific Computing, 2005.\n\n\n\n\nGraillat, S. \"Accurate Floating Point Product and Exponentiation (https://hal.science/hal-00164607v1)\". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45387", "selected_answer": {"answer_html": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n", "answer_id": 45388, "answer_text": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.", "answer_url": "https://scicomp.stackexchange.com/a/45388", "author": "wim", "author_url": "https://scicomp.stackexchange.com/users/5286/wim", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-02-27T09:44:31+00:00", "is_accepted": true, "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": 45387, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-27T09:44:31+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "42AA8384-A67D-4B93-8A67-6F2708905EFF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-28T23:54:12+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "3E89E9AE-7857-41C4-8456-59AB2D1A01FD", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-02T09:09:00+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "98F99AB1-1D15-4C9A-942A-7E8E8455BA0F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}], "score": 7, "updated_at": "2026-03-02T09:09:00+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45388, "answers": [{"answer_html": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.
In principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).
Writing $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:
\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.
\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).
\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:
\nWith
\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\nthe sum becomes a standard dot product:
\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$
\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.
\nReferences
\nBoldo S. and Melquiond, G., "Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd", IEEE Transactions on Computers, 57(4):2008.
\n", "answer_id": 45388, "answer_text": "Unfortunately, an error free transform Threeproduct() of the form $a⋅b⋅c=x+y$ doesn't necessarily exist for arbitrary $a$, $b$ and $c$. In IEEE 754 double precision the significant precision of $a$, $b$ and $c$ is 53 bits, which means that the exact binary representation of the significant of $a⋅b⋅c$ may be up to $3 \\times 53=159$ bits wide. In general these $159$ bits do not fit into two double precision numbers.\n\n\n\n\nIn principle an error free transform Threeproduct() of the form $a⋅b⋅c=x+y+z$, with\n$x = \\operatorname{fl}(a · b ·c)$ and $|x|>>|y|>>|z|$ should be possible (aside from underflow or overflow), but computing these $x$, $y$ and $z$ is not a trivial task (as far as I know).\n\n\n\n\nWriting $a⋅b⋅c$ as an error free sum of 4 doubles is much easier to achieve:\nWith $a · b= p+q$, the product $a · b · c$ becomes $a · b · c = (p+q)c = pc + qc$. Error free transforming the products $pc$ and $qc$ into sums too:\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[w, x] = TwoProductFMA(p, c)\n[y, z] = TwoProductFMA(q, c)\n\n\n\n\n\n\nNow $a⋅b⋅c = pc + qc = w+x+y+z$ exactly.\n\n\n\n\nOnce you have converted each three product in the sum\n$S = abc + def + hij + ...$ into a sum of 4 doubles you can use the method of Ogita et al. (which you mentioned in your question), to sum all the $4n$ doubles. For a correctly rounded sum $S$ see also Boldo and Melquiond (2008).\n\n\n\n\nAlternatively you can rewrite the sum of three products $S = abc + def + hij + ...$ as a standard dot product:\n\n\n\n\nWith\n\n\n\n\n[p, q] = TwoProductFMA(a, b)\n[r, s] = TwoProductFMA(d, e)\n[t, u] = TwoProductFMA(h, i)\n\n\n\n\n\n\nthe sum becomes a standard dot product:\n\n\n\n\n$$\n\\begin{array}{rcl}\nS & = & abc + def + hij + ... \\\\\n & = &(p+q)c + (r+s)f + (t+u)j + ... \\\\\n & = & pc + qc + rf + sf + tj + uj + ... \n\\end{array}\n$$\n\n\n\n\nSee paragraph 5 of Ogita et al. for the accurate computation of dot products.\n\n\n\n\n\n\n\nReferences\n\n\n\n\nBoldo S. and Melquiond, G., \"Emulation of a FMA and Correctly Rounded Sums: Proved Algorithms Using Rounding to Odd (https://ieeexplore.ieee.org/document/4358278)\", IEEE Transactions on Computers, 57(4):2008.", "answer_url": "https://scicomp.stackexchange.com/a/45388", "author": "wim", "author_url": "https://scicomp.stackexchange.com/users/5286/wim", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-02-27T09:44:31+00:00", "is_accepted": true, "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": 45387, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-27T09:44:31+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "42AA8384-A67D-4B93-8A67-6F2708905EFF", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/42AA8384-A67D-4B93-8A67-6F2708905EFF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "wim", "profile_url": "https://scicomp.stackexchange.com/users/5286/wim", "user_type": "registered"}, "created_at": "2026-02-28T23:54:12+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "3E89E9AE-7857-41C4-8456-59AB2D1A01FD", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3E89E9AE-7857-41C4-8456-59AB2D1A01FD/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-02T09:09:00+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "98F99AB1-1D15-4C9A-942A-7E8E8455BA0F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/98F99AB1-1D15-4C9A-942A-7E8E8455BA0F/view-source"}], "score": 7, "updated_at": "2026-03-02T09:09:00+00:00"}], "domain": "computational_science", "external_links": ["https://hal.science/hal-00164607v1", "https://ieeexplore.ieee.org/document/4358278"], "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": "Damien", "question_author_url": "https://scicomp.stackexchange.com/users/761/damien", "question_author_user_type": "registered", "question_created_at": "2026-02-27T05:27:22+00:00", "question_html": "TL;DR: I am looking for a function that computes the product of three floating point numbers:
\nfunction [x, y] = ThreeProduct(a, b, c)\n\nSuch that:
\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$
\nBackground
\nOgita et al. (2005) introduced a method of computing a dot product based on "Error Free Transformation" primitives, such as TwoSum() (due to Knuth) and TwoProduct():
function [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name "Error Free Transformation". That is, for TwoSum():
$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$
\nAnd for TwoProduct():
$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$
\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.
\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.
\nMy question is whether there is a known algorithm for the product of three floating point numbers ("ThreeProduct()"). That is, something where the following holds:
$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$
\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.
\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.
References:
\nOgita, T. et al., "Accurate Sum and Dot Product", SIAM Journal of Scientific Computing, 2005.
\nGraillat, S. "Accurate Floating Point Product and Exponentiation". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.
\n", "question_id": 45387, "question_license": "CC BY-SA 4.0", "question_score": 10, "question_text": "TL;DR: I am looking for a function that computes the product of three floating point numbers:\n\n\n\n\nfunction [x, y] = ThreeProduct(a, b, c)\n\n\n\n\n\nSuch that:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\n\n\n\nBackground\n\n\n\n\nOgita et al. (2005) introduced a method of computing a dot product based on \"Error Free Transformation\" primitives, such as TwoSum() (due to Knuth) and TwoProduct():\n\n\n\n\nfunction [x, y] = TwoSum(a, b)\n x = fl(a + b)\n z = fl(x − a)\n y = fl((a − (x − z)) + (b − z))\n\nfunction [x, y] = TwoProductFMA(a, b)\n x = fl(a · b)\n y = FMA(a, b, −x)\n\n\n\n\n\nThe beauty of these algorithms is that any rounding on the result $x$ is stored in the rounding component $y$, which is the source of the name \"Error Free Transformation\". That is, for TwoSum():\n\n\n\n\n$$\na + b = x + y \\\\\nx = \\operatorname{fl}(a + b)\n$$\n\n\n\n\nAnd for TwoProduct():\n\n\n\n\n$$\na · b = x + y \\\\\nx = \\operatorname{fl}(a · b)\n$$\n\n\n\n\nWhere $\\operatorname{fl}()$ is the result of a floating point computation.\n\n\n\n\nSince the residual is captured, it can carried forward when computing on a sequence of numbers, such as the dot product in Ogita.\n\n\n\n\nMy question is whether there is a known algorithm for the product of three floating point numbers (\"ThreeProduct()\"). That is, something where the following holds:\n\n\n\n\n$$\na · b · c = x + y \\\\\nx = \\operatorname{fl}(a · b ·c)\n$$\n\n\n\n\nI have not yet found such an algorithm. The closest is Graillat (2009) for a compensated product of $n$ numbers (Algorithms 3.2 - 3.4), but there are no claims as to whether the requested properties holds.\n\n\n\n\nMy motivation is that I have a sequence of the sum of three products $x = abc + def + hij + ...$ where it would be straightforward to retrofit Ogita's dot product algorithm, as long as I had the ThreeProduct() ERT primitive.\n\n\n\n\n\n\n\nReferences:\n\n\n\n\nOgita, T. et al., \"Accurate Sum and Dot Product\", SIAM Journal of Scientific Computing, 2005.\n\n\n\n\nGraillat, S. \"Accurate Floating Point Product and Exponentiation (https://hal.science/hal-00164607v1)\". IEEE Transactions on Computers, 2009, 58 (7), pp.994-1000.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-02-27T05:27:22+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "652E8057-1F40-4128-9B15-6014E7677D14", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/652E8057-1F40-4128-9B15-6014E7677D14/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-02-27T06:42:56+00:00", "raw_file": "raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json", "raw_sha256": "4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e", "revision_guid": "59EECD04-2DAA-4DFE-BCE0-7030495A97DF", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/59EECD04-2DAA-4DFE-BCE0-7030495A97DF/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-01T22:07:55+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "E19820FB-0C5D-448A-8B7D-D7FDF8F66E81", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E19820FB-0C5D-448A-8B7D-D7FDF8F66E81/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Damien", "profile_url": "https://scicomp.stackexchange.com/users/761/damien", "user_type": "registered"}, "created_at": "2026-03-01T22:16:04+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "D963AE6C-EC36-4A5E-8DC4-93C74CE72E7B", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D963AE6C-EC36-4A5E-8DC4-93C74CE72E7B/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45387/error-free-transformation-for-the-product-of-three-floating-point-numbers", "split": "train", "split_group": "ccbf1a2018830746c8a5890b1f9c9d0e315a7b4d5a58beb262b81c93f94c5380", "tags": ["floating-point"], "thread_id": "scicomp:45387", "title": "\"Error Free Transformation\" for the product of three floating point numbers"}} {"accepted_answer": {"answer_html": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.
\n", "answer_id": 45440, "answer_text": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.", "answer_url": "https://scicomp.stackexchange.com/a/45440", "author": "FilmCoder", "author_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-05-05T05:53:32+00:00", "is_accepted": true, "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": 45396, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "FilmCoder", "profile_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "user_type": "registered"}, "created_at": "2026-05-05T05:53:32+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "C39D8103-AD54-44E2-90A3-4461BB25C47E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}], "score": 3, "updated_at": "2026-05-05T05:53:32+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "let quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &NodeMakogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.
\n", "answer_id": 45440, "answer_text": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.", "answer_url": "https://scicomp.stackexchange.com/a/45440", "author": "FilmCoder", "author_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-05-05T05:53:32+00:00", "is_accepted": true, "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": 45396, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "FilmCoder", "profile_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "user_type": "registered"}, "created_at": "2026-05-05T05:53:32+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "C39D8103-AD54-44E2-90A3-4461BB25C47E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}], "score": 3, "updated_at": "2026-05-05T05:53:32+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45440, "answers": [{"answer_html": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance Fields" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.
\n", "answer_id": 45440, "answer_text": "Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper \"Hierarchical hp-Adaptive Signed Distance Fields\" by Koschier et al., 2016. In this paper, they make sure to use an orthonormal polynomial basis. Meanwhile, the Legendre polynomials are, by default, orthogonal but not orthonormal. The code above requires normalizing them by multiplying each polynomial by $\\sqrt{\\frac{2\\rho_x + 1}{w_x}}$ where $\\rho_x$ is the degree of the polynomial along the current axis (which we call $x$) and $w_x$ is the width of the cell along this axis; see also Equation (4) in the paper.", "answer_url": "https://scicomp.stackexchange.com/a/45440", "author": "FilmCoder", "author_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-05-05T05:53:32+00:00", "is_accepted": true, "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": 45396, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "FilmCoder", "profile_url": "https://scicomp.stackexchange.com/users/56811/filmcoder", "user_type": "registered"}, "created_at": "2026-05-05T05:53:32+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "C39D8103-AD54-44E2-90A3-4461BB25C47E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C39D8103-AD54-44E2-90A3-4461BB25C47E/view-source"}], "score": 3, "updated_at": "2026-05-05T05:53:32+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/4aqhk3tL.png", "https://i.sstatic.net/K6cTCsGy.png", "https://i.sstatic.net/mLTa1ZsD.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": "Makogan", "question_author_url": "https://scicomp.stackexchange.com/users/38908/makogan", "question_author_user_type": "registered", "question_created_at": "2026-03-05T07:11:11+00:00", "question_html": "I have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):
\n\nThere's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.
\nBut of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.
\nThe image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:
\n\nThis is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.
\nHowever, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:
\n\nNot only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.
\nI am going to describe the logic in a high level:
\nThe actual code is this:
\nlet quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &Node<HpNode<f32, 10>>| {\n // Legendre coefficients.\n let cfs = node.data.coeffs(); \n let coeff_count = node.data.coeff_count();\n\n let pos = box_position + box_dims / 2.;\n let p = (cam_pos - pos) / box_dims;\n let v = ray / box_dims;\n\n let mut a = 0.;\n let mut b = 0.;\n let mut c = 0.;\n // Shift and scale the ray and pos to the local node.\n let ray = v;\n let ray_pos = p;\n for i in 0..coeff_count\n {\n // Coefficient + the degree of each legendre polynomial that was\n // tensor producted to make the basis element, i.e. one of\n // 1, x, y, z, xy, zx, yz, xx,yy, zz with repsective tuples\n // (0, 0, 0) (1, 0, 0),..., (1,0,1) ..., (2, 0, 0), (0, 2, 0), (0, 0, 2)\n let (s, powers) = cfs[i as usize];\n // Compute coefficients for each dimension's Legendre polynomial\n // restricted to line.\n let mut poly = [1., 0., 0.];\n // accumulates as [t^0, t^1, t^2] coefficients.\n\n for axis in 0..3\n {\n // Get teh axial coefficients of this ray\n let (v, p) = match axis\n {\n 0 => (ray.x, ray_pos.x),\n 1 => (ray.y, ray_pos.y),\n 2 => (ray.z, ray_pos.z),\n _ => unreachable!(),\n };\n\n let power = powers[axis];\n\n // Legendre polynomial P_n(vt + p) coefficients in t.\n let leg_coeffs = match power\n {\n 0 => [1., 0., 0.],\n 1 => [p, v, 0.],\n // coefficients of the legendre polynomial of degree 2\n 2 => [1.5 * p * p - 0.5, 3. * p * v, 1.5 * v * v],\n _ => unreachable!(),\n };\n\n // Multiply poly *= leg_coeffs.\n let temp = [\n poly[0] * leg_coeffs[0],\n poly[0] * leg_coeffs[1] + poly[1] * leg_coeffs[0],\n poly[0] * leg_coeffs[2]\n + poly[1] * leg_coeffs[1]\n + poly[2] * leg_coeffs[0],\n ];\n poly = temp;\n }\n\n a += s * poly[2];\n b += s * poly[1];\n c += s * poly[0];\n }\n\n let disc = b * b - 4. * a * c;\n if disc < 0.\n {\n return f32::INFINITY;\n }\n\n let sqrt_disc = disc.sqrt();\n let inv_2a = 1. / (2. * a);\n\n // Quadratic solutions.\n let x1 = (-b - sqrt_disc) * inv_2a;\n let x2 = (-b + sqrt_disc) * inv_2a;\n\n // Branchless valid selection: if x < 0, replace with infinity.\n let valid_x1 = if x1 < 0. { f32::INFINITY } else { x1 };\n let valid_x2 = if x2 < 0. { f32::INFINITY } else { x2 };\n\n // Take minimum of valid solutions.\n let quad_t = valid_x1.min(valid_x2);\n\n // Handle linear case.\n let is_linear = a.abs() < 0.0001;\n let linear_t = -c / b;\n\n let linear_t = if linear_t < 0. { f32::INFINITY } else { linear_t };\n\n if is_linear { linear_t } else { quad_t }\n };\n\nTo add further context, to generate the image with the additional spheres all you need to do is hard code the coefficients for a sphere:
\n let cfs = [\n (-0.1 + 1., [0, 0, 0]),\n (2./3., [2, 0, 0]),\n (2./3., [0, 2, 0]),\n (2./3., [0, 0, 2]),\n ];\n let coeff_count = 4;\n\nTo override the ones coming in. But the input coefficients cannot eb wrong because then the first image would not work.
\nThere's something wrong with the way I am computing my ray quadric collisions that is specific to the Legendre case. When I modify my logic to work with the sphere quadrics it works, as shown, so I must have messed something up with when computing the coefficients, but when I see the written code I fail to see what.
\n", "question_id": 45396, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Background\n\n\n\n\nI have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/mLTa1ZsD.png] (https://i.sstatic.net/mLTa1ZsD.png)\n\n\n\n\nThere's some artifacts on the ears, but I would say this is a pretty good approximation of the original bunny SDF.\n\n\n\n\nBut of course since each node in my oct-tree is approximating a quadric, I can do better than sphere tracing, I can compute exact collisions by setting the right equation.\n\n\n\n\nThe image above was generated by using a legendre basis as the vector space so I am just using legendre polynomials for which the degree is at most 2. For testing my quadric Idea I first used a hard coded monomial basis where each node is just a sphere, and I get this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/K6cTCsGy.png] (https://i.sstatic.net/K6cTCsGy.png)\n\n\n\n\nThis is roughly what I would expect, so at least with the hard coded sphere monomials the quadric solving logic works.\n\n\n\n\nHowever, when I try to solve the actual legendre system defined by the actual input (the ones used to create the first image) I get this:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/4aqhk3tL.png] (https://i.sstatic.net/4aqhk3tL.png)\n\n\n\n\nNot only does it look wrong, the actual shapes of each node change depending on the view direction. Which is not at all what I would expect even if the coefficients were wrong.\n\n\n\n\nI am going to describe the logic in a high level:\n\n\n\n\n\nConsider that an $\\mathbb{R^3}$ legendre polynomial becomes a regular polynomial when restricted to the parametric line of a ray.\n\n\n\n\nGrab the coefficients of the quadric on the current node, knowing these are coefficients of a legendre polynomial, not monomials.\n\n\n\n\nFor each coefficient, add it to the corresponding constant, linear or quadric set of coefficents (for monomials).\n\n\n\n\nGrab the final, properly factored, coeffcients and solve a simple quadratic equation to figure out if and where the ray intersects the quadric on the current node.\n\n\n\n\n\nThe actual code is this:\n\n\n\n\nlet quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &NodeThe gist of the problem is (as the Author has suggested) to "assign" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.
\nThe given example exhibits some simplifying features that make the matching possible "by inspection" (with suitable bookkeeping).
\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.
\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.
\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.
\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.
\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).
\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:
\n| First polynomial | \nSecond polynomial | \n
|---|---|
| $1$ or $q^0$ | \n$q^{8+2x_{13}}$ | \n
| $q^2$ | \n$q^{10+2x_{13}}$ | \n
| $q^8$ | \n$q^{4+2x_{15}}$ | \n
| $q^{10}$ | \n$q^{6+2x_{15}}$ | \n
| $q^{12}$ | \n$q^{2x_{17}}$ | \n
| $q^{14}$ | \n$q^{2+2x_{17}}$ | \n
| $q^{16}$ | \n$q^{2x_{35}}$ | \n
| $q^{18}$ | \n$q^{2+2x_{35}}$ | \n
| $q^{20}$ | \n$q^{-4+2x_{37}}$ | \n
| $q^{22}$ | \n$q^{-2+2x_{37}}$ | \n
| $q^{24}$ | \n$q^{-8+2x_{57}}$ | \n
| $q^{26}$ | \n$q^{-6+2x_{57}}$ | \n
Note that the terms in the right column occur in six pairs of "stride two", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of "stride two". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.
\nThis resembles the graphic degree problem in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.
\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.
\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.
\n", "answer_id": 45473, "answer_text": "The gist of the problem is (as the Author has suggested) to \"assign\" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.\n\n\n\n\nThe given example exhibits some simplifying features that make the matching possible \"by inspection\" (with suitable bookkeeping).\n\n\n\n\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.\n\n\n\n\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.\n\n\n\n\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.\n\n\n\n\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.\n\n\n\n\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).\n\n\n\n\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:\n\n\n\n\n\n\n\n\n\nFirst polynomial\nSecond polynomial\n\n\n\n\n\n\n\n\n\t$1$ or $q^0$\n\t$q^{8+2x_{13}}$\n\n\n\n\n\n\n\t$q^2$\n\t$q^{10+2x_{13}}$\n\n\n\n\n\n\n\t$q^8$\n\t$q^{4+2x_{15}}$\n\n\n\n\n\n\n\t$q^{10}$\n\t$q^{6+2x_{15}}$\n\n\n\n\n\n\n\t$q^{12}$\n\t$q^{2x_{17}}$\n\n\n\n\n\n\n\t$q^{14}$\n\t$q^{2+2x_{17}}$\n\n\n\n\n\n\n\t$q^{16}$\n\t$q^{2x_{35}}$\n\n\n\n\n\n\n\t$q^{18}$\n\t$q^{2+2x_{35}}$\n\n\n\n\n\n\n\t$q^{20}$\n\t$q^{-4+2x_{37}}$\n\n\n\n\n\n\n\t$q^{22}$\n\t$q^{-2+2x_{37}}$\n\n\n\n\n\n\n\t$q^{24}$\n\t$q^{-8+2x_{57}}$\n\n\n\n\n\n\n\t$q^{26}$\n\t$q^{-6+2x_{57}}$\n\n\n\n\n\n\n\n\n\nNote that the terms in the right column occur in six pairs of \"stride two\", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of \"stride two\". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.\n\n\n\n\nThis resembles the graphic degree problem (https://en.wikipedia.org/wiki/Graph_realization_problem) in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.\n\n\n\n\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog (https://en.wikipedia.org/wiki/Prolog) because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.\n\n\n\n\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.", "answer_url": "https://scicomp.stackexchange.com/a/45473", "author": "hardmath", "author_url": "https://scicomp.stackexchange.com/users/651/hardmath", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-06-24T21:53:31+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": 45472, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "hardmath", "profile_url": "https://scicomp.stackexchange.com/users/651/hardmath", "user_type": "moderator"}, "created_at": "2026-06-24T21:53:31+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "6B10CE88-2D26-43C8-9F27-870834FE5FB3", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6B10CE88-2D26-43C8-9F27-870834FE5FB3/view-source"}], "score": 2, "updated_at": "2026-06-24T21:53:31+00:00"}], "product": "code_qa", "question": "I am trying to solve a linear system of equations that comes from equating two Laurent polynomials (https://en.wikipedia.org/wiki/Laurent_polynomial). The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.\n\n\n\n\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.\n\n\n\n\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.\n\n\n\n\nDo you guys know of any hint or solution on how to tackle these problems?\n\n\n\n\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$\n\n\n\n\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$\n\n\n\n\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45472", "selected_answer": {"answer_html": "Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative "pulls down" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:
restart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.
\n", "answer_id": 45482, "answer_text": "Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative \"pulls down\" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:\n\n\n\n\nrestart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\n\n\n\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.", "answer_url": "https://scicomp.stackexchange.com/a/45482", "author": "dharr", "author_url": "https://scicomp.stackexchange.com/users/50934/dharr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-06-28T17:22:41+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": 45472, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-28T17:22:41+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "17B5B435-530D-44FB-A531-8C7EBC69DAB0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/17B5B435-530D-44FB-A531-8C7EBC69DAB0/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-28T17:30:54+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "B335F14D-BC1A-4871-8C8E-AA1A1574CE8E", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B335F14D-BC1A-4871-8C8E-AA1A1574CE8E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T00:34:42+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "AE6B318A-E224-4873-94DF-796E47B0400A", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AE6B318A-E224-4873-94DF-796E47B0400A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T01:28:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "E46B4CBF-9F68-49D7-885E-BE0F07FBA25B", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E46B4CBF-9F68-49D7-885E-BE0F07FBA25B/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T02:02:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "BE24CE57-475F-48DB-8B09-676A64E891E3", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BE24CE57-475F-48DB-8B09-676A64E891E3/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-07-06T01:31:28+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "64B9EB1B-7407-427F-BF22-4AF94181F69C", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/64B9EB1B-7407-427F-BF22-4AF94181F69C/view-source"}], "score": 3, "updated_at": "2026-07-06T01:31:28+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "The gist of the problem is (as the Author has suggested) to "assign" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.
\nThe given example exhibits some simplifying features that make the matching possible "by inspection" (with suitable bookkeeping).
\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.
\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.
\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.
\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.
\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).
\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:
\n| First polynomial | \nSecond polynomial | \n
|---|---|
| $1$ or $q^0$ | \n$q^{8+2x_{13}}$ | \n
| $q^2$ | \n$q^{10+2x_{13}}$ | \n
| $q^8$ | \n$q^{4+2x_{15}}$ | \n
| $q^{10}$ | \n$q^{6+2x_{15}}$ | \n
| $q^{12}$ | \n$q^{2x_{17}}$ | \n
| $q^{14}$ | \n$q^{2+2x_{17}}$ | \n
| $q^{16}$ | \n$q^{2x_{35}}$ | \n
| $q^{18}$ | \n$q^{2+2x_{35}}$ | \n
| $q^{20}$ | \n$q^{-4+2x_{37}}$ | \n
| $q^{22}$ | \n$q^{-2+2x_{37}}$ | \n
| $q^{24}$ | \n$q^{-8+2x_{57}}$ | \n
| $q^{26}$ | \n$q^{-6+2x_{57}}$ | \n
Note that the terms in the right column occur in six pairs of "stride two", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of "stride two". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.
\nThis resembles the graphic degree problem in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.
\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.
\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.
\n", "answer_id": 45473, "answer_text": "The gist of the problem is (as the Author has suggested) to \"assign\" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables $x_{ij}$ in the second Laurent polyomial.\n\n\n\n\nThe given example exhibits some simplifying features that make the matching possible \"by inspection\" (with suitable bookkeeping).\n\n\n\n\nWe assume the variables are allowed to take on integer values. I believe the example problem is infeasible if the $x_{ij}$ were restricted to nonnegative integers, as we will have occasion to point out below.\n\n\n\n\nAlso the matching in the given example decouples variables that appear in the three terms corresponding to $a^{20},a^{18},a^{16}$. In other words we can match and solve separately for variables as they appear in only one of these three terms. Whether this is a general feature of the problems contemplated by the Author is not clear, so in the interest of simplicity I'll point out in my solution how that simplifies things.\n\n\n\n\nIn order to arrange equality of the two Laurent polynomials, it is necessary and sufficient to get equality of the coefficients of $a^{20},a^{18},a^{16}$ respectively. The equality of the $a^{20}$ terms depends on six unknown values $$x_{13},x_{15},x_{17},x_{35},x_{37},x_{57}$$ while equality of the $a^{18}$ terms depends similarly on twenty unknowns $x_{12},\\ldots,x_{79}$ and that of the $a^{16}$ terms depends on ten unknowns $x_{24},\\ldots,x_{89}$.\n\n\n\n\nBecause these three groups of unknowns are disjoint, they decouple; their solutions can be assigned independently. We proceed to give a detailed account of the possible solutions for the first group of unknowns.\n\n\n\n\nComparing the coefficients of $a^{20}$, we find that monic terms $q^{-6},q^{6},q^{18}$ are already provided in the second Laurent polynomial. However the first polynomial has a term $2q^{18}$, so this nonmonic term has to be accounted for by variable exponents in the second polynomial (in addition to accounting for all the remaining terms in the coefficient of $a^{20}$).\n\n\n\n\nWhen those duplicate terms are omitted, e.g. by subtracting the like coefficients of $a^{20}$, we see that we have two lists of monic terms to be matched:\n\n\n\n\n\n\n\n\n\nFirst polynomial\nSecond polynomial\n\n\n\n\n\n\n\n\n\t$1$ or $q^0$\n\t$q^{8+2x_{13}}$\n\n\n\n\n\n\n\t$q^2$\n\t$q^{10+2x_{13}}$\n\n\n\n\n\n\n\t$q^8$\n\t$q^{4+2x_{15}}$\n\n\n\n\n\n\n\t$q^{10}$\n\t$q^{6+2x_{15}}$\n\n\n\n\n\n\n\t$q^{12}$\n\t$q^{2x_{17}}$\n\n\n\n\n\n\n\t$q^{14}$\n\t$q^{2+2x_{17}}$\n\n\n\n\n\n\n\t$q^{16}$\n\t$q^{2x_{35}}$\n\n\n\n\n\n\n\t$q^{18}$\n\t$q^{2+2x_{35}}$\n\n\n\n\n\n\n\t$q^{20}$\n\t$q^{-4+2x_{37}}$\n\n\n\n\n\n\n\t$q^{22}$\n\t$q^{-2+2x_{37}}$\n\n\n\n\n\n\n\t$q^{24}$\n\t$q^{-8+2x_{57}}$\n\n\n\n\n\n\n\t$q^{26}$\n\t$q^{-6+2x_{57}}$\n\n\n\n\n\n\n\n\n\nNote that the terms in the right column occur in six pairs of \"stride two\", i.e. the exponents will differ by two regardless of what (integer) values are assigned. Fortunately the left column also consists of six pairs of \"stride two\". In this case one solution is obtained by matching the left and right columns in the order indicated. Most generally we can match any of the six consecutive pairs on the left with any of the six consecutive pairs on the right, which means there are $6!$ distinct solutions.\n\n\n\n\nThis resembles the graphic degree problem (https://en.wikipedia.org/wiki/Graph_realization_problem) in which one is asked if a degree sequence can be attained by nodes of a simple graph. There are polynomial time algorithms for this problem.\n\n\n\n\nMy personal choice of language for finding the matchings between two lists of polynomial terms would be Prolog (https://en.wikipedia.org/wiki/Prolog) because of its inherent list syntax and backtracking faculty. While I'm confident both Python and Mathematica could deal with lists, I'd be doubtful about the effort needed to tack on backtracking logic in them.\n\n\n\n\nI must pause for now to deal with some real world tasks, but I plan to return and sketch out the solutions for matching the $a^{18}$ and $a^{16}$ coefficients. I think both will introduce some noteworthy complications.", "answer_url": "https://scicomp.stackexchange.com/a/45473", "author": "hardmath", "author_url": "https://scicomp.stackexchange.com/users/651/hardmath", "author_user_type": "moderator", "content_license": "CC BY-SA 4.0", "created_at": "2026-06-24T21:53:31+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": 45472, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "hardmath", "profile_url": "https://scicomp.stackexchange.com/users/651/hardmath", "user_type": "moderator"}, "created_at": "2026-06-24T21:53:31+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "6B10CE88-2D26-43C8-9F27-870834FE5FB3", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6B10CE88-2D26-43C8-9F27-870834FE5FB3/view-source"}], "score": 2, "updated_at": "2026-06-24T21:53:31+00:00"}, {"answer_html": "Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative "pulls down" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:
restart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.
\n", "answer_id": 45482, "answer_text": "Consider first the simpler problem where we have only the laurent polynomials in $q$ that are multiplied by $a^{20}$; call these $P_{1}$ and $P_{2}$. When\nwe have the desired $x_{i}$ values the two polynomials are equal for all values of $q$. The case of $q=1$ is easy to test since the result does not depend on the values of the exponents. So we expect $P_{1}(1)=P_{2}(1)$ and\nsince we were quaranteed the same set of monomials we find that is trivially true (both are $16$ in this case). Next consider that the derivative polynomials $dP_{1}/dq$ and $dP_{2}/dq$ at $q=1$ must also be equal. The\nderivative \"pulls down\" the exponents and the result is a linear equation in the $x_{i}$, which in this case is\n$$\n220=60+4x_{13}+4x_{15}+4x_{17}+4x_{35}+4x_{37}+4x_{57}\n$$\nFor the second derivative we find a quadratic equation\n$$\n4300=1236+(2+2x_{35})^{2}+(4+2x_{15})^{2}+4x_{17}^{2}+\\ldots\n$$\nand so on. There are $6$ unknowns and so we need $6$ equations, i.e.., up to the 6th derivative. Solving polynomial systems of equations is standard in computer algebra systems and although it may be slow for large number of variables, it is probably faster than solving a combinatorial problem. In this case, Maple's\nsolve produced 100 solutions in just over one second. The first of these is\n$$\n\\{x_{13}=0,x_{15}=10,x_{17}=6,x_{35}=0,x_{37}=12,x_{57}=12\\}\n$$\nThe complete Maple code is:\n\n\n\n\nrestart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + 2*(5 + x[17])) + q^(2*x[35]) + q^(-8 + 2*(5 + x[35])) + q^(-4 + 2*x[37]) + q^(-2 + 2*x[37]) + q^(-8 + 2*x[57]) + q^(-6 + 2*x[57]);\nvars := indets(P2, name) minus {q};\nn := nops(vars);\nfor i from 1 to n do\n eq[i] := eval(diff(P1, q$i), q=1) = eval(diff(P2, q$i), q=1);\nend do:\neqs := convert(eq, set);\nans := [solve(eqs, vars)];\nnsols := nops(ans);\nans[1]; # display first of 100 solutions\n\n\n\n\n\nFor the complete problem, if you know the $a^{20}$, $a^{18}$ and $a^{16}$ problems are uncoupled, then they can be solved separately; each solution of the first can go with the each of the second and so on. Solving them together will lead to an unworkable number of solutions.", "answer_url": "https://scicomp.stackexchange.com/a/45482", "author": "dharr", "author_url": "https://scicomp.stackexchange.com/users/50934/dharr", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-06-28T17:22:41+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": 45472, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-28T17:22:41+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "17B5B435-530D-44FB-A531-8C7EBC69DAB0", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/17B5B435-530D-44FB-A531-8C7EBC69DAB0/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-28T17:30:54+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "B335F14D-BC1A-4871-8C8E-AA1A1574CE8E", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B335F14D-BC1A-4871-8C8E-AA1A1574CE8E/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T00:34:42+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "AE6B318A-E224-4873-94DF-796E47B0400A", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AE6B318A-E224-4873-94DF-796E47B0400A/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T01:28:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "E46B4CBF-9F68-49D7-885E-BE0F07FBA25B", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/E46B4CBF-9F68-49D7-885E-BE0F07FBA25B/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-06-29T02:02:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "BE24CE57-475F-48DB-8B09-676A64E891E3", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BE24CE57-475F-48DB-8B09-676A64E891E3/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "dharr", "profile_url": "https://scicomp.stackexchange.com/users/50934/dharr", "user_type": "registered"}, "created_at": "2026-07-06T01:31:28+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "64B9EB1B-7407-427F-BF22-4AF94181F69C", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/64B9EB1B-7407-427F-BF22-4AF94181F69C/view-source"}], "score": 3, "updated_at": "2026-07-06T01:31:28+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Graph_realization_problem", "https://en.wikipedia.org/wiki/Laurent_polynomial", "https://en.wikipedia.org/wiki/Prolog"], "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": "ateixeira82", "question_author_url": "https://scicomp.stackexchange.com/users/56972/ateixeira82", "question_author_user_type": "registered", "question_created_at": "2026-06-21T10:31:05+00:00", "question_html": "I am trying to solve a linear system of equations that comes from equating two Laurent polynomials. The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.
\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.
\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.
\nDo you guys know of any hint or solution on how to tackle these problems?
\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$
\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$
\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.
\n", "question_id": 45472, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "I am trying to solve a linear system of equations that comes from equating two Laurent polynomials (https://en.wikipedia.org/wiki/Laurent_polynomial). The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve for.\n\n\n\n\nThey always have the same set of monomials, hence I know that the system is not trivially unsolvable. So we need to solve these linear equations, but the rub is that we don't know which equations should be allocated to which polynomial. There are a lot of these equations that come from multiple conditions, and the solutions must be consistent for all conditions.\n\n\n\n\nMy idea was to do a sort of combinatorics algorithm but I failed miserably.\nIn any case I guess that must be a problem that occurred other times, or at least something similar to it, and maybe it was already solved by someone with python, mathematica (I mainly use mathematica) or any other programming language.\n\n\n\n\nDo you guys know of any hint or solution on how to tackle these problems?\n\n\n\n\nAs an example to make things more clear. This is the purely numerical polynomial:\n$a^{20}\\left(\n1 + q^{-6} + q^{2} + q^{6} + q^{8} + q^{10} + q^{12} + q^{14} + q^{16}\n+ 2 q^{18} + q^{20} + q^{22} + q^{24} + q^{26} + q^{30}\n\\right)\n+\na^{18}\\left(\n-1 - q^{-12} - q^{-10} - q^{-6} - 2 q^{-4} - q^{-2}\n- 2 q^{2} - 2 q^{4} - 2 q^{6} - 2 q^{8} - 2 q^{10}\n- 3 q^{12} - 3 q^{14} - 2 q^{16} - 3 q^{18} - 3 q^{20}\n- 2 q^{22} - 2 q^{24} - 2 q^{26} - q^{28} - q^{30} - q^{32}\n\\right)\n+\na^{16}\\left(\n1 + q^{-16} + q^{-10} + q^{-8} + q^{-4} + q^{-2}\n+ q^{2} + q^{4} + q^{6} + 2 q^{8} + q^{10} + q^{12}\n+ 2 q^{14} + 2 q^{16} + q^{18} + 2 q^{20}\n+ q^{22} + q^{24} + q^{26} + q^{28} + q^{32}\n\\right)\n$\n\n\n\n\nand here is the polynomial with the variables:\n$a^{20}\\left(\nq^{-6} + q^{6} + q^{18} + q^{30}\n+ q^{-8 + 2(8 + x_{13})}\n+ q^{-8 + 2(9 + x_{13})}\n+ q^{-8 + 2(6 + x_{15})}\n+ q^{-8 + 2(7 + x_{15})}\n+ q^{2 x_{17}}\n+ q^{-8 + 2(5 + x_{17})}\n+ q^{2 x_{35}}\n+ q^{-8 + 2(5 + x_{35})}\n+ q^{-4 + 2 x_{37}}\n+ q^{-2 + 2 x_{37}}\n+ q^{-8 + 2 x_{57}}\n+ q^{-6 + 2 x_{57}}\n\\right)\n+\na^{18}\\left(\n- q^{14 + 2 x_{12}}\n- q^{16 + 2 x_{12}}\n- q^{10 + 2 x_{14}}\n- q^{12 + 2 x_{14}}\n- q^{6 + 2 x_{16}}\n- q^{8 + 2 x_{16}}\n- q^{-14 + 2(8 + x_{18})}\n- q^{-12 + 2(8 + x_{18})}\n- q^{-14 + 2(6 + x_{19})}\n- q^{-12 + 2(6 + x_{19})}\n- q^{10 + 2 x_{23}}\n- q^{12 + 2 x_{23}}\n- q^{6 + 2 x_{25}}\n- q^{8 + 2 x_{25}}\n- q^{-14 + 2(8 + x_{27})}\n- q^{-12 + 2(8 + x_{27})}\n- q^{6 + 2 x_{34}}\n- q^{8 + 2 x_{34}}\n- q^{-14 + 2(8 + x_{36})}\n- q^{-12 + 2(8 + x_{36})}\n- q^{-14 + 2(6 + x_{38})}\n- q^{-12 + 2(6 + x_{38})}\n- q^{-6 + 2 x_{39}}\n- q^{-4 + 2 x_{39}}\n- q^{-14 + 2(8 + x_{45})}\n- q^{-12 + 2(8 + x_{45})}\n- q^{-14 + 2(6 + x_{47})}\n- q^{-12 + 2(6 + x_{47})}\n- q^{-14 + 2(6 + x_{56})}\n- q^{-12 + 2(6 + x_{56})}\n- q^{-6 + 2 x_{58}}\n- q^{-4 + 2 x_{58}}\n- q^{-10 + 2 x_{59}}\n- q^{-8 + 2 x_{59}}\n- q^{-6 + 2 x_{67}}\n- q^{-4 + 2 x_{67}}\n- q^{-10 + 2 x_{78}}\n- q^{-8 + 2 x_{78}}\n- q^{-14 + 2 x_{79}}\n- q^{-12 + 2 x_{79}}\n\\right)\n+\na^{16}\\left(\nq^{-16} + q^{-4} + q^{8} + q^{20} + q^{32}\n+ q^{12 + 2 x_{24}}\n+ q^{14 + 2 x_{24}}\n+ q^{8 + 2 x_{26}}\n+ q^{10 + 2 x_{26}}\n+ q^{4 + 2 x_{28}}\n+ q^{6 + 2 x_{28}}\n+ q^{-16 + 2(8 + x_{29})}\n+ q^{-16 + 2(9 + x_{29})}\n+ q^{4 + 2 x_{46}}\n+ q^{6 + 2 x_{46}}\n+ q^{-16 + 2(8 + x_{48})}\n+ q^{-16 + 2(9 + x_{48})}\n+ q^{-16 + 2(6 + x_{49})}\n+ q^{-16 + 2(7 + x_{49})}\n+ q^{-16 + 2(6 + x_{68})}\n+ q^{-16 + 2(7 + x_{68})}\n+ q^{-8 + 2 x_{69}}\n+ q^{-16 + 2(5 + x_{69})}\n+ q^{-12 + 2 x_{89}}\n+ q^{-10 + 2 x_{89}}\n\\right)$\n\n\n\n\nThere are other such equations, and the goal is to solve for $x_{ij}$. Since we don't know beforehand how to match the numerical exponents to the exponents with variables, we have to do it with combinatorics and then use the same method on the other set of equations to guarantee that we have a consistent set of solutions.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ateixeira82", "profile_url": "https://scicomp.stackexchange.com/users/56972/ateixeira82", "user_type": "registered"}, "created_at": "2026-06-21T10:31:05+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "F5FC1979-2C80-415C-8F46-2AF9C62D8214", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/F5FC1979-2C80-415C-8F46-2AF9C62D8214/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ateixeira82", "profile_url": "https://scicomp.stackexchange.com/users/56972/ateixeira82", "user_type": "registered"}, "created_at": "2026-06-21T14:46:19+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "53FB132D-482A-4B58-AD12-EF8D7216467C", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/53FB132D-482A-4B58-AD12-EF8D7216467C/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "hardmath", "profile_url": "https://scicomp.stackexchange.com/users/651/hardmath", "user_type": "moderator"}, "created_at": "2026-06-24T19:16:29+00:00", "raw_file": "raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json", "raw_sha256": "34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75", "revision_guid": "41EC7BF5-D5F7-4405-918D-9C3797D59DDE", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/41EC7BF5-D5F7-4405-918D-9C3797D59DDE/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45472/solving-linear-system-of-equations-with-combinatorics", "split": "train", "split_group": "bc3b4da5bdff031e2377bca4a34351252b5b5eb37044f7ea6ace3a407e2df29e", "tags": ["python", "linear-system", "mathematica", "combinatorics"], "thread_id": "scicomp:45472", "title": "Solving linear system of equations with combinatorics"}} {"accepted_answer": {"answer_html": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.
\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.
\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method
\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6
\nThe original comment was:
\n\n\n", "answer_id": 45503, "answer_text": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.", "answer_url": "https://scicomp.stackexchange.com/a/45503", "author": "Omar Osman Mahamoud", "author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-29T16:42:27+00:00", "is_accepted": true, "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": 45487, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-29T16:42:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DD32D002-9E3F-4398-BC22-FB7FBF667951", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}], "score": 2, "updated_at": "2026-07-29T16:42:27+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "def euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45487, "sha256": "cf0bde6333be3658682c2bbbf3514be3f691d7dfe36bcc4c07befe85d7046069", "source_url": "https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"}, {"block_index": 1, "code_text": "def Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45487, "sha256": "16f70485ac76c3d299f343fc55817b8b11ff0d5048050d78df40f99c7a3c34d5", "source_url": "https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"}, {"block_index": 2, "code_text": "def Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45487, "sha256": "664f217d728581a98996f2f18b9c12d83f56da4e8f3ec3511a3531d746e98194", "source_url": "https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t"}, {"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\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": 45490, "sha256": "0739849795b9b7d88e5352edf2511378cd32dd94d0652612d0afef3309011d46", "source_url": "https://scicomp.stackexchange.com/a/45490"}, {"block_index": 1, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45490, "sha256": "5e92562921cb4c242909f38ee3d1a780addba783f5b7d0dce4ef1fffc163584d", "source_url": "https://scicomp.stackexchange.com/a/45490"}], "other_answers": [{"answer_html": "Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:
\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\nFor n=5000, dt=0.001, the output is closer yet:
\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n", "answer_id": 45490, "answer_text": "From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n[image: comparison; source: https://i.sstatic.net/ZOXbZlmS.png] (https://i.sstatic.net/ZOXbZlmS.png)\n\n\n\n\nFor n=5000, dt=0.001, the output is closer yet:\n\n\n\n\n[image: dt=0.001; source: https://i.sstatic.net/mLRffKQD.png] (https://i.sstatic.net/mLRffKQD.png)\n\n\n\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine (https://www.sciencedirect.com/science/article/pii/0893965989900797) form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: RK32; source: https://i.sstatic.net/DgMDrx4E.png] (https://i.sstatic.net/DgMDrx4E.png)", "answer_url": "https://scicomp.stackexchange.com/a/45490", "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-07-13T01:47:13+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": 45487, "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-07-13T01:47:13+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "06EC415F-DC78-49A5-97D0-ED020CE6C74F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/06EC415F-DC78-49A5-97D0-ED020CE6C74F/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-07-13T03:28:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "88B016CA-5B2E-46C7-99DA-7F374A3A0853", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/88B016CA-5B2E-46C7-99DA-7F374A3A0853/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-07-13T21:27:38+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "51F9060A-E0B8-4FC6-AAA1-D61ED8331962", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/51F9060A-E0B8-4FC6-AAA1-D61ED8331962/view-source"}], "score": 6, "updated_at": "2026-07-13T21:27:38+00:00"}, {"answer_html": "When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.
\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!
\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)
\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods "symplectic integrators", because they preserve energy and impulse better, but my memory may be leaky.
\n", "answer_id": 45491, "answer_text": "When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.\n\n\n\n\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!\n\n\n\n\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)\n\n\n\n\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods \"symplectic integrators\", because they preserve energy and impulse better, but my memory may be leaky.", "answer_url": "https://scicomp.stackexchange.com/a/45491", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T06:50:20+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": 45487, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2026-07-13T06:50:20+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E/view-source"}], "score": 7, "updated_at": "2026-07-13T06:50:20+00:00"}], "product": "code_qa", "question": "I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.\n\n\n\n\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.\n\n\n\n\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?\n\n\n\n\nHere are the three implementations.\n\n\n\n\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\n\n\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45487", "selected_answer": {"answer_html": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.
\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.
\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method
\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6
\nThe original comment was:
\n\n\n", "answer_id": 45503, "answer_text": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.", "answer_url": "https://scicomp.stackexchange.com/a/45503", "author": "Omar Osman Mahamoud", "author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-29T16:42:27+00:00", "is_accepted": true, "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": 45487, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-29T16:42:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DD32D002-9E3F-4398-BC22-FB7FBF667951", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}], "score": 2, "updated_at": "2026-07-29T16:42:27+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45503, "answers": [{"answer_html": "Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:
\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\nFor n=5000, dt=0.001, the output is closer yet:
\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n", "answer_id": 45490, "answer_text": "From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fine, the methods are closer:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\nn_steps = 300\n\n\ndef euler_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\ndef runge_kutta_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\ndef verlet_function(x_earth: float = 1.5, y_earth: float = 0.,\n vx_earth: float = 0., vy_earth: float = 2*np.pi,\n dt: float = 0.1) -> tuple[list, list]:\n xpos = []\n ypos = []\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\ndef main() -> None:\n fig, ax = plt.subplots()\n for method, name in (\n (euler_function, 'Euler'),\n (runge_kutta_function, 'RK2'),\n (verlet_function, 'Verlet'),\n ):\n x, y = method(dt=0.01)\n ax.plot(x, y, label=name)\n ax.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n[image: comparison; source: https://i.sstatic.net/ZOXbZlmS.png] (https://i.sstatic.net/ZOXbZlmS.png)\n\n\n\n\nFor n=5000, dt=0.001, the output is closer yet:\n\n\n\n\n[image: dt=0.001; source: https://i.sstatic.net/mLRffKQD.png] (https://i.sstatic.net/mLRffKQD.png)\n\n\n\n\nObviously there are different IVP methods that can do even better per iteration. For instance, the Bogacki-Shampine (https://www.sciencedirect.com/science/article/pii/0893965989900797) form of Runge-Kutta order 3(2) is extremely stable for this application; shown over 1000 years:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = -G*M_sun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n jac = np.array((\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ))\n\n return jac\n\n\nout = scipy.integrate.solve_ivp(\n method='RK23', fun=ddt, rtol=1e-5, dense_output=True,\n # jac=d2dt2, # not used by Runge-Kutta\n t_span=(0, 1000), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\n\nassert out.success, out.message\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: RK32; source: https://i.sstatic.net/DgMDrx4E.png] (https://i.sstatic.net/DgMDrx4E.png)", "answer_url": "https://scicomp.stackexchange.com/a/45490", "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-07-13T01:47:13+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": 45487, "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-07-13T01:47:13+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "06EC415F-DC78-49A5-97D0-ED020CE6C74F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/06EC415F-DC78-49A5-97D0-ED020CE6C74F/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-07-13T03:28:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "88B016CA-5B2E-46C7-99DA-7F374A3A0853", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/88B016CA-5B2E-46C7-99DA-7F374A3A0853/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-07-13T21:27:38+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "51F9060A-E0B8-4FC6-AAA1-D61ED8331962", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/51F9060A-E0B8-4FC6-AAA1-D61ED8331962/view-source"}], "score": 6, "updated_at": "2026-07-13T21:27:38+00:00"}, {"answer_html": "When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.
\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!
\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)
\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods "symplectic integrators", because they preserve energy and impulse better, but my memory may be leaky.
\n", "answer_id": 45491, "answer_text": "When comparing numerical methods, we usually look up the order of the method (i.e. the upper bound of how the errors scale). This is only a very broad description of what is happening.\n\n\n\n\nEach method may have its own biases of how this error occurs and how it reflects in the different metrics you are interested in. For orbital mechanics you may be interested in that the method preserves the kinetic and potential energies of the bodies, while the exact spatial position is of low interest (or vice versa). Also, the order of the error makes no statement about the absoulte size of the error!\n\n\n\n\nWhat you could do is to verify if the errors of each implementation of your methods actually scale the way you expect them to, by plotting the absolute error of each method after a few timesteps under different refinements. If you are confident the scaling is right (strong, but not sufficient signal for correct implementation), then you can dig deeper into it:-)\n\n\n\n\nFrom the top of my head orbital mechanics are often solved with implicit euler-like methods \"symplectic integrators\", because they preserve energy and impulse better, but my memory may be leaky.", "answer_url": "https://scicomp.stackexchange.com/a/45491", "author": "MPIchael", "author_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T06:50:20+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": 45487, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "MPIchael", "profile_url": "https://scicomp.stackexchange.com/users/28636/mpichael", "user_type": "registered"}, "created_at": "2026-07-13T06:50:20+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/6AC38EDB-7E81-4D4A-9023-CF4D31E3AB6E/view-source"}], "score": 7, "updated_at": "2026-07-13T06:50:20+00:00"}, {"answer_html": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.
\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.
\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method
\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6
\nThe original comment was:
\n\n\n", "answer_id": 45503, "answer_text": "The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.\n\n\n\n\nIn fact, I realized that I was updating the velocity before the position. This means I was not implementing the standard (explicit) Euler method, but the symplectic Euler (also known as semi-implicit Euler) method.\n\n\n\n\nFor anyone interested, here is the corresponding Wikipedia article:\nhttps://en.wikipedia.org/wiki/Semi-implicit_Euler_method (https://en.wikipedia.org/wiki/Semi-implicit_Euler_method)\n\n\n\n\nAnd here is an excellent video explaining the method:\nhttps://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6 (https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6)\n\n\n\n\nThe original comment was:\n\n\n\n\n\n\n\nCongratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).\n\n\n\n\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.\n\n\n\n\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.", "answer_url": "https://scicomp.stackexchange.com/a/45503", "author": "Omar Osman Mahamoud", "author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-29T16:42:27+00:00", "is_accepted": true, "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": 45487, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-29T16:42:27+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DD32D002-9E3F-4398-BC22-FB7FBF667951", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DD32D002-9E3F-4398-BC22-FB7FBF667951/view-source"}], "score": 2, "updated_at": "2026-07-29T16:42:27+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Semi-implicit_Euler_method", "https://i.sstatic.net/DgMDrx4E.png", "https://i.sstatic.net/ZOXbZlmS.png", "https://i.sstatic.net/mLRffKQD.png", "https://www.sciencedirect.com/science/article/pii/0893965989900797", "https://youtu.be/nCg3aXn5F3M?si=2dt1c9v5bBPWWuT6"], "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": "Omar Osman Mahamoud", "question_author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "question_author_user_type": "registered", "question_created_at": "2026-07-12T12:23:53+00:00", "question_html": "Congratulations, you rediscovered the symplectic Euler method—a common outcome when the Euler step is implemented incorrectly for kinematic systems. As a result, your Euler and Verlet methods differ only by terms of order ( \\Delta t^2 ).
\nYour RK2 implementation is not actually a second-order Runge–Kutta method, since it contains the same mistake that turned your Euler implementation into the symplectic Euler method.
\nMy advice is to implement numerical integrators for general first-order systems, and then express the kinematic equations as a first-order system as well. This approach also makes it clear that symplectic integrators are specialized methods designed specifically for Hamiltonian (or kinematic) systems.
\n
I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.
\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.
\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?
\nHere are the three implementations.
\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?
\n", "question_id": 45487, "question_license": "CC BY-SA 4.0", "question_score": 7, "question_text": "I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.\n\n\n\n\nHowever, in my simulation, the opposite seems to happen: the RK2 and Velocity Verlet trajectories appear less accurate than the Euler trajectory.\n\n\n\n\nI've checked the implementations several times but I can't find any obvious mistakes. Could someone point out whether I've implemented one of these methods incorrectly or explain why this behavior might occur?\n\n\n\n\nHere are the three implementations.\n\n\n\n\ndef euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ax_earth * dt\n vy_earth += ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt\n y_earth += vy_earth * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Runge_kutta_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n x_earth_mid = x_earth + vx_earth * (dt / 2)\n y_earth_mid = y_earth + vy_earth * (dt / 2)\n\n vx_earth_mid = vx_earth + ax_earth * (dt / 2)\n vy_earth_mid = vy_earth + ay_earth * (dt / 2)\n\n ax_earth_mid = -(G * M_sun) * x_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth_mid / ((x_earth_mid**2 + y_earth_mid**2)**0.5)**3\n\n vx_earth += ax_earth_mid * dt\n vy_earth += ay_earth_mid * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth_mid * dt\n y_earth += vy_earth_mid * dt\n\n return xpos, ypos\n\n\n\n\n\ndef Verlet_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth += vx_earth * dt + ax_earth * (dt / 2)**2\n y_earth += vy_earth * dt + ay_earth * (dt / 2)**2\n\n ax_earth_mid = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth_mid = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth += ((ax_earth_mid + ax_earth) / 2) * dt\n vy_earth += ((ay_earth_mid + ay_earth) / 2) * dt\n\n return xpos, ypos\n\n\n\n\n\nWhat am I missing? Is there an error in one (or more) of these implementations, or is there another reason why RK2 and Velocity Verlet would appear less accurate than Euler?", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-12T12:23:53+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "D3AC3DA9-7794-465F-AF03-B877C6C0EF0D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/D3AC3DA9-7794-465F-AF03-B877C6C0EF0D/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-07-13T01:54:39+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "8CA42130-747B-47CA-BB4D-D7CD4CD70CC8", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/8CA42130-747B-47CA-BB4D-D7CD4CD70CC8/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lutz Lehmann", "profile_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "user_type": "registered"}, "created_at": "2026-07-13T09:09:11+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "3FEC6861-FADA-4330-8FB0-12A8839B955D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3FEC6861-FADA-4330-8FB0-12A8839B955D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-15T23:49:16+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "7914AE3D-629C-4FCA-BF96-6D9824005EDC", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/7914AE3D-629C-4FCA-BF96-6D9824005EDC/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-16T00:10:59+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "62C0155C-4F90-4C15-8CFB-EDCF7BC7548E", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/62C0155C-4F90-4C15-8CFB-EDCF7BC7548E/view-source"}, {"content_license": null, "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-16T11:22:30+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "BAF51E0F-7B50-4443-B0DF-BC44A34EF5BE", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/BAF51E0F-7B50-4443-B0DF-BC44A34EF5BE/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45487/why-do-my-rk2-and-velocity-verlet-implementations-produce-less-accurate-orbits-t", "split": "train", "split_group": "e3c4c48d2016f7277be3216b64a0dd6deac291a4bba983d1b0acef890102a34a", "tags": ["python", "simulation", "runge-kutta", "physics"], "thread_id": "scicomp:45487", "title": "Why do my RK2 and Velocity Verlet implementations produce less accurate orbits than Euler?"}} {"accepted_answer": {"answer_html": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.
\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.
\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.
\n", "answer_id": 45492, "answer_text": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.\n\n\n\n\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.\n\n\n\n\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.", "answer_url": "https://scicomp.stackexchange.com/a/45492", "author": "Lutz Lehmann", "author_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T16:52:52+00:00", "is_accepted": true, "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": 45488, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lutz Lehmann", "profile_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "user_type": "registered"}, "created_at": "2026-07-13T16:52:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A/view-source"}], "score": 6, "updated_at": "2026-07-13T16:52:52+00:00"}, "code_blocks": [{"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1\nn_steps = 10**3\n\nxpos = []\nypos = []\n\nx_earth = 1.5\ny_earth = 0\n\nvx_earth = 0\nvy_earth = v_earth\n\nfor i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth = vx_earth + ax_earth * dt\n vy_earth = vy_earth + ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth = x_earth + vx_earth * dt\n y_earth = y_earth + vy_earth * dt\n\nplt.plot(xpos, ypos, color=\"green\")\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45488, "sha256": "29098e66448020fa60ce6a91831d46a6b9403f2e88a3a639a5e298caa2a96612", "source_url": "https://scicomp.stackexchange.com/questions/45488/why-do-these-two-python-implementations-of-the-same-algorithm-give-different-out"}, {"block_index": 1, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nG=4*(np.pi)**2\nM_sun=1 # masse solaire\ndistance=1 # UA\ntemps=1 # Année\nM_earth=3.002513826043238e-06 # masse solaire\nv_earth=(2*np.pi) # UA/Année\ndt=0.1\nn_steps=10**3\n\n\nx_earth=np.zeros(n_steps)\ny_earth=np.zeros(n_steps)\n\nvx_earth=np.zeros(n_steps)\nvy_earth=np.zeros(n_steps)\n\n\nx_earth[0]=1.5\nvy_earth[0]=v_earth\n\nfor i in range(n_steps-1):\n ax_earth=-(G*M_sun)*x_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n ay_earth=-(G*M_sun)*y_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n \n\n vx_earth[i+1]=vx_earth[i]+ax_earth*dt\n vy_earth[i+1]=vy_earth[i]+ay_earth*dt\n\n x_earth[i+1]=x_earth[i]+vx_earth[i]*dt\n y_earth[i+1]=y_earth[i]+vy_earth[i]*dt\n\n\nplt.plot(x_earth,y_earth, color='green')\n\nplt.show()\n\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45488, "sha256": "366f1e96b6f89a37850e16fa5ea865fc24548f235ddec9e4dc27467658dd34a5", "source_url": "https://scicomp.stackexchange.com/questions/45488/why-do-these-two-python-implementations-of-the-same-algorithm-give-different-out"}, {"block_index": 0, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45489, "sha256": "279d1d4e50b4e9bc5ece09985d31e55e079e25b1831affda48b09a8e4c244d89", "source_url": "https://scicomp.stackexchange.com/a/45489"}, {"block_index": 1, "code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45489, "sha256": "66befcd4aaf54a2524fc9549c2ecf654793aedbe892f014947d4721bb37a8e2c", "source_url": "https://scicomp.stackexchange.com/a/45489"}, {"block_index": 2, "code_text": "import time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\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": 45489, "sha256": "db1869b930dcad78727f6acb5716fd94e75923783771588824f838bbf9d7d4b4", "source_url": "https://scicomp.stackexchange.com/a/45489"}], "other_answers": [{"answer_html": "I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n\n\nBut of course expressing this as a proper IVP is more stable:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n\n\nAs a more fulsome demo, note that for an ODE state vector of
\n$$\n[ x, y, \\dot x, \\dot y ]\n$$
\nthe Jacobian is
\n$$\n\\begin{bmatrix}\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1 \\\\\n \\frac{-G m_{sun}(y^2 - 2x^2)} {||p||^5} \n& \\frac{-G m_{sun}(-3xy)} {||p||^5} & 0 & 0 \\\\\n \\frac{-G m_{sun}(-3xy)} {||p||^5} \n& \\frac{-G m_{sun}(x^2 - 2y^2)} {||p||^5} & 0 & 0 \n\\end{bmatrix}\n$$
\nimport time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n", "answer_id": 45489, "answer_text": "I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n\n\n\n\n\n[image: plot; source: https://i.sstatic.net/Tq7uPZJj.png] (https://i.sstatic.net/Tq7uPZJj.png)\n\n\n\n\nBut of course expressing this as a proper IVP is more stable:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: ivp; source: https://i.sstatic.net/KnVXs58G.png] (https://i.sstatic.net/KnVXs58G.png)\n\n\n\n\n\n\n\nAs a more fulsome demo, note that for an ODE state vector of\n\n\n\n\n$$\n[ x, y, \\dot x, \\dot y ]\n$$\n\n\n\n\nthe Jacobian is\n\n\n\n\n$$\n\\begin{bmatrix}\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1 \\\\\n \\frac{-G m_{sun}(y^2 - 2x^2)} {||p||^5} \n& \\frac{-G m_{sun}(-3xy)} {||p||^5} & 0 & 0 \\\\\n \\frac{-G m_{sun}(-3xy)} {||p||^5} \n& \\frac{-G m_{sun}(x^2 - 2y^2)} {||p||^5} & 0 & 0 \n\\end{bmatrix}\n$$\n\n\n\n\nimport time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45489", "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-07-13T00:25:35+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": 45488, "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-07-13T00:25:35+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "C9922D8C-A590-4B1E-94CA-B97A778DA7B4", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C9922D8C-A590-4B1E-94CA-B97A778DA7B4/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-07-13T01:06:34+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "43E7D35E-D810-41D3-9F12-FDE31BF65860", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/43E7D35E-D810-41D3-9F12-FDE31BF65860/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-26T19:23:41+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "9970817B-8E8F-4EAC-BE66-46090CDC3BB0", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9970817B-8E8F-4EAC-BE66-46090CDC3BB0/view-source"}], "score": 8, "updated_at": "2026-09-26T19:23:41+00:00"}], "product": "code_qa", "question": "Can someone please tell me why these two codes don't give the same answer?\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1\nn_steps = 10**3\n\nxpos = []\nypos = []\n\nx_earth = 1.5\ny_earth = 0\n\nvx_earth = 0\nvy_earth = v_earth\n\nfor i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth = vx_earth + ax_earth * dt\n vy_earth = vy_earth + ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth = x_earth + vx_earth * dt\n y_earth = y_earth + vy_earth * dt\n\nplt.plot(xpos, ypos, color=\"green\")\nplt.show()\n\n\n\n\n\n[image: it's image; source: https://i.sstatic.net/mLgbrUlD.png] (https://i.sstatic.net/mLgbrUlD.png)\n\n\n\n\nand\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nG=4*(np.pi)**2\nM_sun=1 # masse solaire\ndistance=1 # UA\ntemps=1 # Année\nM_earth=3.002513826043238e-06 # masse solaire\nv_earth=(2*np.pi) # UA/Année\ndt=0.1\nn_steps=10**3\n\n\nx_earth=np.zeros(n_steps)\ny_earth=np.zeros(n_steps)\n\nvx_earth=np.zeros(n_steps)\nvy_earth=np.zeros(n_steps)\n\n\nx_earth[0]=1.5\nvy_earth[0]=v_earth\n\nfor i in range(n_steps-1):\n ax_earth=-(G*M_sun)*x_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n ay_earth=-(G*M_sun)*y_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n \n\n vx_earth[i+1]=vx_earth[i]+ax_earth*dt\n vy_earth[i+1]=vy_earth[i]+ay_earth*dt\n\n x_earth[i+1]=x_earth[i]+vx_earth[i]*dt\n y_earth[i+1]=y_earth[i]+vy_earth[i]*dt\n\n\nplt.plot(x_earth,y_earth, color='green')\n\nplt.show()\n\n\n\n\n\n\n[image: it's image; source: https://i.sstatic.net/XWVvnmXc.png] (https://i.sstatic.net/XWVvnmXc.png)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45488", "selected_answer": {"answer_html": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.
\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.
\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.
\n", "answer_id": 45492, "answer_text": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.\n\n\n\n\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.\n\n\n\n\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.", "answer_url": "https://scicomp.stackexchange.com/a/45492", "author": "Lutz Lehmann", "author_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T16:52:52+00:00", "is_accepted": true, "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": 45488, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lutz Lehmann", "profile_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "user_type": "registered"}, "created_at": "2026-07-13T16:52:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A/view-source"}], "score": 6, "updated_at": "2026-07-13T16:52:52+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": 45492, "answers": [{"answer_html": "I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n\n\nBut of course expressing this as a proper IVP is more stable:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n\n\nAs a more fulsome demo, note that for an ODE state vector of
\n$$\n[ x, y, \\dot x, \\dot y ]\n$$
\nthe Jacobian is
\n$$\n\\begin{bmatrix}\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1 \\\\\n \\frac{-G m_{sun}(y^2 - 2x^2)} {||p||^5} \n& \\frac{-G m_{sun}(-3xy)} {||p||^5} & 0 & 0 \\\\\n \\frac{-G m_{sun}(-3xy)} {||p||^5} \n& \\frac{-G m_{sun}(x^2 - 2y^2)} {||p||^5} & 0 & 0 \n\\end{bmatrix}\n$$
\nimport time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n", "answer_id": 45489, "answer_text": "I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\ndt = 0.1\nn_steps = 1_000\n\np_earth = np.empty((n_steps, 2))\np_earth[0] = (1.5, 0)\nv_earth = np.array((0, 2*np.pi)) # UA/Année\n\nfor i in range(n_steps - 1):\n factor = -G*M_sun/np.linalg.norm(p_earth[i])**3\n v_earth += dt*factor*p_earth[i]\n p_earth[i + 1] = p_earth[i] + v_earth*dt\n\nplt.plot(*p_earth.T)\nplt.show()\n\n\n\n\n\n[image: plot; source: https://i.sstatic.net/Tq7uPZJj.png] (https://i.sstatic.net/Tq7uPZJj.png)\n\n\n\n\nBut of course expressing this as a proper IVP is more stable:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1 # masse solaire\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = -G * M_sun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\nout = scipy.integrate.solve_ivp(\n fun=ddt, dense_output=True, rtol=1e-6,\n t_span=(0, 100), # Année\n y0=(\n 1.5, 0, # UA\n 0, 2*np.pi, # UA/Année\n ),\n)\nassert out.success, out.message\n\nplt.plot(*out.y[:2])\nplt.show()\n\n\n\n\n\n[image: ivp; source: https://i.sstatic.net/KnVXs58G.png] (https://i.sstatic.net/KnVXs58G.png)\n\n\n\n\n\n\n\nAs a more fulsome demo, note that for an ODE state vector of\n\n\n\n\n$$\n[ x, y, \\dot x, \\dot y ]\n$$\n\n\n\n\nthe Jacobian is\n\n\n\n\n$$\n\\begin{bmatrix}\n0 & 0 & 1 & 0 \\\\\n0 & 0 & 0 & 1 \\\\\n \\frac{-G m_{sun}(y^2 - 2x^2)} {||p||^5} \n& \\frac{-G m_{sun}(-3xy)} {||p||^5} & 0 & 0 \\\\\n \\frac{-G m_{sun}(-3xy)} {||p||^5} \n& \\frac{-G m_{sun}(x^2 - 2y^2)} {||p||^5} & 0 & 0 \n\\end{bmatrix}\n$$\n\n\n\n\nimport time\nimport typing\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.integrate\n\nG = 4 * np.pi**2\nM_sun = 1. # masse solaire\nGmsun = -G * M_sun\n\nuses_jacobian = frozenset({'Radau', 'BDF', 'LSODA'}).__contains__\n\n\ndef ddt(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n a = Gmsun / np.linalg.norm(p)**3 * p\n return np.concat((v, a))\n\n\ndef d2dt2(t: float, state: np.ndarray) -> np.ndarray:\n p, v = np.split(state, 2)\n\n # The Jacobian matrix has shape (n, n) and its element (i, j) is equal to d f_i / d y_j\n x, y = p\n fnorm5 = Gmsun/np.linalg.norm(p)**5\n daxdpx = fnorm5*(y**2 - 2*x**2)\n daydpy = fnorm5*(x**2 - 2*y**2)\n daxdpy = fnorm5*-3*x*y\n daydpx = daxdpy\n return scipy.sparse.csc_array([\n # /dpx /dpy /dvx /dvy\n ( 0, 0, 1, 0), # dvx\n ( 0, 0, 0, 1), # dvy\n (daxdpx, daxdpy, 0, 0), # dax\n (daydpx, daydpy, 0, 0), # day\n ])\n\n\ndef solve(\n t_max: float,\n method: typing.Literal['RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'] = 'LSODA',\n atol: float = 1e-6, rtol: float = 1e-5,\n) -> np.ndarray:\n params = {}\n if uses_jacobian(method):\n params['jac'] = d2dt2\n\n y0 = (\n 1.5, 0., # UA\n 0., 2*np.pi, # UA/Année\n )\n t_span = (0., t_max) # Année\n out = scipy.integrate.solve_ivp(\n method=method, fun=ddt, t_span=t_span, y0=y0, atol=atol, rtol=rtol, dense_output=True, **params)\n if not out.success:\n raise ValueError(out.message)\n return out.y[:2] # x,y\n\n\ndef main() -> None:\n t_max = 1_000.\n for method in ('RK45', 'RK23', 'DOP853', 'Radau', 'BDF', 'LSODA'):\n t0 = time.perf_counter()\n xy = solve(t_max, method=method)\n t1 = time.perf_counter()\n print(f'{method:8} t={t1-t0:.2f} n={xy.shape[1]}', flush=True)\n fix, ax = plt.subplots()\n ax.set_title(f'method={method}, t_max={t_max}y, dur={t1 - t0:.2f}s')\n ax.plot(*xy)\n plt.show()\n\n\nif __name__ == '__main__':\n main()", "answer_url": "https://scicomp.stackexchange.com/a/45489", "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-07-13T00:25:35+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": 45488, "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-07-13T00:25:35+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "C9922D8C-A590-4B1E-94CA-B97A778DA7B4", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/C9922D8C-A590-4B1E-94CA-B97A778DA7B4/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-07-13T01:06:34+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "43E7D35E-D810-41D3-9F12-FDE31BF65860", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/43E7D35E-D810-41D3-9F12-FDE31BF65860/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-26T19:23:41+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "9970817B-8E8F-4EAC-BE66-46090CDC3BB0", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/9970817B-8E8F-4EAC-BE66-46090CDC3BB0/view-source"}], "score": 8, "updated_at": "2026-09-26T19:23:41+00:00"}, {"answer_html": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.
\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.
\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.
\n", "answer_id": 45492, "answer_text": "The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modified from the elliptical to the hyperbolic case.\n\n\n\n\nThe first variant on the other hand modifies it to the second-order symplectic Euler method. This is more conservative to the energy level, but not necessarily to the other parameters of the Kepler ellipse. Thus the apparent perihel rotation and also perhaps some drift in the eccentricity of the ellipse.\n\n\n\n\nThese errors will of course be reduced when using smaller step sizes, or higher order methods.", "answer_url": "https://scicomp.stackexchange.com/a/45492", "author": "Lutz Lehmann", "author_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-07-13T16:52:52+00:00", "is_accepted": true, "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": 45488, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Lutz Lehmann", "profile_url": "https://scicomp.stackexchange.com/users/6839/lutz-lehmann", "user_type": "registered"}, "created_at": "2026-07-13T16:52:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/2C5B9BF1-E49C-4BE3-8AF3-F047FF98EB7A/view-source"}], "score": 6, "updated_at": "2026-07-13T16:52:52+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/KnVXs58G.png", "https://i.sstatic.net/Tq7uPZJj.png", "https://i.sstatic.net/XWVvnmXc.png", "https://i.sstatic.net/mLgbrUlD.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": "Omar Osman Mahamoud", "question_author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "question_author_user_type": "registered", "question_created_at": "2026-07-12T16:05:18+00:00", "question_html": "Can someone please tell me why these two codes don't give the same answer?
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1\nn_steps = 10**3\n\nxpos = []\nypos = []\n\nx_earth = 1.5\ny_earth = 0\n\nvx_earth = 0\nvy_earth = v_earth\n\nfor i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth = vx_earth + ax_earth * dt\n vy_earth = vy_earth + ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth = x_earth + vx_earth * dt\n y_earth = y_earth + vy_earth * dt\n\nplt.plot(xpos, ypos, color="green")\nplt.show()\n\n\nand
\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nG=4*(np.pi)**2\nM_sun=1 # masse solaire\ndistance=1 # UA\ntemps=1 # Année\nM_earth=3.002513826043238e-06 # masse solaire\nv_earth=(2*np.pi) # UA/Année\ndt=0.1\nn_steps=10**3\n\n\nx_earth=np.zeros(n_steps)\ny_earth=np.zeros(n_steps)\n\nvx_earth=np.zeros(n_steps)\nvy_earth=np.zeros(n_steps)\n\n\nx_earth[0]=1.5\nvy_earth[0]=v_earth\n\nfor i in range(n_steps-1):\n ax_earth=-(G*M_sun)*x_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n ay_earth=-(G*M_sun)*y_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n \n\n vx_earth[i+1]=vx_earth[i]+ax_earth*dt\n vy_earth[i+1]=vy_earth[i]+ay_earth*dt\n\n x_earth[i+1]=x_earth[i]+vx_earth[i]*dt\n y_earth[i+1]=y_earth[i]+vy_earth[i]*dt\n\n\nplt.plot(x_earth,y_earth, color='green')\n\nplt.show()\n\n\n\n", "question_id": 45488, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "Can someone please tell me why these two codes don't give the same answer?\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1\nn_steps = 10**3\n\nxpos = []\nypos = []\n\nx_earth = 1.5\ny_earth = 0\n\nvx_earth = 0\nvy_earth = v_earth\n\nfor i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n vx_earth = vx_earth + ax_earth * dt\n vy_earth = vy_earth + ay_earth * dt\n\n xpos.append(x_earth)\n ypos.append(y_earth)\n\n x_earth = x_earth + vx_earth * dt\n y_earth = y_earth + vy_earth * dt\n\nplt.plot(xpos, ypos, color=\"green\")\nplt.show()\n\n\n\n\n\n[image: it's image; source: https://i.sstatic.net/mLgbrUlD.png] (https://i.sstatic.net/mLgbrUlD.png)\n\n\n\n\nand\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n\nG=4*(np.pi)**2\nM_sun=1 # masse solaire\ndistance=1 # UA\ntemps=1 # Année\nM_earth=3.002513826043238e-06 # masse solaire\nv_earth=(2*np.pi) # UA/Année\ndt=0.1\nn_steps=10**3\n\n\nx_earth=np.zeros(n_steps)\ny_earth=np.zeros(n_steps)\n\nvx_earth=np.zeros(n_steps)\nvy_earth=np.zeros(n_steps)\n\n\nx_earth[0]=1.5\nvy_earth[0]=v_earth\n\nfor i in range(n_steps-1):\n ax_earth=-(G*M_sun)*x_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n ay_earth=-(G*M_sun)*y_earth[i]/((x_earth[i]**2+y_earth[i]**2)**0.5)**3\n \n\n vx_earth[i+1]=vx_earth[i]+ax_earth*dt\n vy_earth[i+1]=vy_earth[i]+ay_earth*dt\n\n x_earth[i+1]=x_earth[i]+vx_earth[i]*dt\n y_earth[i+1]=y_earth[i]+vy_earth[i]*dt\n\n\nplt.plot(x_earth,y_earth, color='green')\n\nplt.show()\n\n\n\n\n\n\n[image: it's image; source: https://i.sstatic.net/XWVvnmXc.png] (https://i.sstatic.net/XWVvnmXc.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-12T16:05:18+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "F0D7914F-24E6-41F7-BF73-8B6CAC429B71", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/F0D7914F-24E6-41F7-BF73-8B6CAC429B71/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-07-13T01:24:37+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "BC3D64B0-5C3E-43B3-B708-134F783143A0", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/BC3D64B0-5C3E-43B3-B708-134F783143A0/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45488/why-do-these-two-python-implementations-of-the-same-algorithm-give-different-out", "split": "train", "split_group": "4ff0006883a431c9705a554000147f3098c4b66f9f495d2a19d5c9d5cef4057f", "tags": ["python", "computational-physics", "simulation", "numerical-integration"], "thread_id": "scicomp:45488", "title": "Why do these two Python implementations of the same algorithm give different outputs?"}}
{"accepted_answer": {"answer_html": "\n\nWhat is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?
\n
In general, it might be difficult because stress is a symmetric second-order tensor. I do not think that there is a standard way, though. For components, you can visualize the value at each point discretely using glyphs. You could also try to make it a continuous function inside the elements using interpolation for the convex hull of your Gauss points and extrapolation for the region between the Gauss points and the nodes. Finally, you could do some kind of average between contiguous elements to get a continuous field. You can check ref 1.
\n\n\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?
\n
Not that I am aware of. But this type of visualization is quite common in discontinuous Galerkin setups. One workaround is to duplicate the nodes.
\n\n\nWhat is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?
\n
In general, it might be difficult because stress is a symmetric second-order tensor. I do not think that there is a standard way, though. For components, you can visualize the value at each point discretely using glyphs. You could also try to make it a continuous function inside the elements using interpolation for the convex hull of your Gauss points and extrapolation for the region between the Gauss points and the nodes. Finally, you could do some kind of average between contiguous elements to get a continuous field. You can check ref 1.
\n\n\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?
\n
Not that I am aware of. But this type of visualization is quite common in discontinuous Galerkin setups. One workaround is to duplicate the nodes.
\n\n\nWhat is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?
\n
In general, it might be difficult because stress is a symmetric second-order tensor. I do not think that there is a standard way, though. For components, you can visualize the value at each point discretely using glyphs. You could also try to make it a continuous function inside the elements using interpolation for the convex hull of your Gauss points and extrapolation for the region between the Gauss points and the nodes. Finally, you could do some kind of average between contiguous elements to get a continuous field. You can check ref 1.
\n\n\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?
\n
Not that I am aware of. But this type of visualization is quite common in discontinuous Galerkin setups. One workaround is to duplicate the nodes.
\nI am implementing a two-dimensional displacement-based finite element code in MATLAB.
\nFor a Q4 element, stress and strain are calculated at four (2\\times2) Gauss integration points. In my current post-processing code, I use:
\nfor i = 1:NoE\n\n nl = EL(i,1:NPE);\n\n for j = 1:NPE\n X(j,i) = ENL(nl(j),1) ...\n + scale*ENL(nl(j),4*PD+1);\n\n Y(j,i) = ENL(nl(j),2) ...\n + scale*ENL(nl(j),4*PD+2);\n end\n\n for j = 1:NPE\n val = stress(i,:,1,1);\n stress_xx(j,i) = val(1,j);\n end\nend\n\nI then use the nodal-coordinate arrays X and Y, together with stress_xx, to produce a colored element plot.
\nI now understand that this does not actually calculate stress at the nodes. It simply associates stress at Gauss point (j) with the coordinates of local node (j). The fact that Q4 has four nodes and four Gauss points made this one-to-one assignment appear reasonable, although the Gauss points and nodes have different coordinates.
\nMy supervisor also pointed out that treating stress as a unique nodal quantity is generally incorrect in a standard displacement-based FEM. Displacement is continuous across element boundaries, but its gradients, strains, and stresses are element-wise quantities and can jump across adjacent elements.
\nI am now implementing a Q8 element using (3\\times3) Gaussian integration. Therefore, every element has eight nodes but nine Gauss-point stress values. A direct assignment is no longer even numerically possible because there is no Q8 node corresponding to the center Gauss point.
\nMy questions are:
\nI want to avoid discarding the ninth Gauss-point value, arbitrarily attaching Gauss-point values to nodes, or presenting an averaged nodal stress field as though it were the original FEM stress solution.
\n", "question_id": 45493, "question_license": "CC BY-SA 4.0", "question_score": 3, "question_text": "I am implementing a two-dimensional displacement-based finite element code in MATLAB.\n\n\n\n\nFor a Q4 element, stress and strain are calculated at four (2\\times2) Gauss integration points. In my current post-processing code, I use:\n\n\n\n\nfor i = 1:NoE\n\n nl = EL(i,1:NPE);\n\n for j = 1:NPE\n X(j,i) = ENL(nl(j),1) ...\n + scale*ENL(nl(j),4*PD+1);\n\n Y(j,i) = ENL(nl(j),2) ...\n + scale*ENL(nl(j),4*PD+2);\n end\n\n for j = 1:NPE\n val = stress(i,:,1,1);\n stress_xx(j,i) = val(1,j);\n end\nend\n\n\n\n\n\nI then use the nodal-coordinate arrays X and Y, together with stress_xx, to produce a colored element plot.\n\n\n\n\nI now understand that this does not actually calculate stress at the nodes. It simply associates stress at Gauss point (j) with the coordinates of local node (j). The fact that Q4 has four nodes and four Gauss points made this one-to-one assignment appear reasonable, although the Gauss points and nodes have different coordinates.\n\n\n\n\nMy supervisor also pointed out that treating stress as a unique nodal quantity is generally incorrect in a standard displacement-based FEM. Displacement is continuous across element boundaries, but its gradients, strains, and stresses are element-wise quantities and can jump across adjacent elements.\n\n\n\n\nI am now implementing a Q8 element using (3\\times3) Gaussian integration. Therefore, every element has eight nodes but nine Gauss-point stress values. A direct assignment is no longer even numerically possible because there is no Q8 node corresponding to the center Gauss point.\n\n\n\n\nMy questions are:\n\n\n\n\n\nWhat is the standard way to visualize all nine Gauss-point stress values for a Q8 element while keeping them at their actual physical locations?\n\n\n\n\nShould I map the Gauss-point coordinates from the parent element to the physical element and plot the values directly?\n\n\n\n\nHow can I construct an element-wise contour plot that preserves possible stress jumps across element boundaries?\n\n\n\n\nIs Gauss-point-to-node extrapolation appropriate only for a recovered or smoothed visualization field, rather than for representing the original finite element stress field?\n\n\n\n\nAre there standard MATLAB approaches for plotting such discontinuous element-wise fields for curved or distorted Q8 elements?\n\n\n\n\n\nI want to avoid discarding the ninth Gauss-point value, arbitrarily attaching Gauss-point values to nodes, or presenting an averaged nodal stress field as though it were the original FEM stress solution.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Rasa R. Behboud", "profile_url": "https://scicomp.stackexchange.com/users/57047/rasa-r-behboud", "user_type": "registered"}, "created_at": "2026-07-14T08:51:19+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "0DE2EEFB-055C-46F0-8FDE-C3A7A6127CDE", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/0DE2EEFB-055C-46F0-8FDE-C3A7A6127CDE/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45493/how-should-gauss-point-stresses-be-plotted-for-q8-serendipity-finite-elements-wi", "split": "holdout", "split_group": "b2ad43a2df226c50dce366e7e7c6e8288caa19189f629674a3520e798c71fa14", "tags": ["finite-element"], "thread_id": "scicomp:45493", "title": "How should Gauss-point stresses be plotted for Q8 Serendipity finite elements without treating them as nodal values?"}} {"accepted_answer": {"answer_html": "Your loop structure to accumulate the acceleration is wrong:
\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n [...]\n\nax and ay always increase, since they are never reset to zero. In this way, you accumulate the contributions for all bodies over all time steps. Instead, you should compute the acceleration starting back from zero in each time step i.
I really don't think you should be adding your masses (if you do, you tend to eject planets from the solar system).
\nAlso, I feel the need to remind you that
\nStopping short of rewriting this as an IVP for you, the vectorised version can look like:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 201 # Step count\nyears = 0.95 # Duration (years)\ndt = years/(n-1) # Time step (years/step)\n\n# Masses expressed in solar masses, derived from kg\n# https://ssd.jpl.nasa.gov/planets/phys_par.html\nmass = np.array(( # (5,)\n 1.988475e30, # Sol\n 0.330103e24, # Mercury\n 4.867310e24, # Venus\n 5.972170e24, # Earth\n 0.641691e24, # Mars\n))/1.988475e30\n\n# Distances in astronomical units (AU)\n# 1 AU = 1.495978707e11 m\n# Positions, having an initial value set to body's semi-major axis\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nall_p = np.empty((n, mass.size, 2))\nall_p[0] = (\n (0., 0.), # Sol\n (0.387098, 0.), # Mercury\n (0.723332, 0.), # Venus\n (1., 0.), # Earth\n (1.52368055, 0.), # Mars\n)\n\n# Velocity (AU/year), derived from km/s\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nv = np.array(( # (5,2)\n (0., 0. ), # Sol\n (0., 47.36 ), # Mercury\n (0., 35.02 ), # Venus\n (0., 29.7827), # Earth\n (0., 24.07 ), # Mars\n)) * (1e3/1.495978707e11 *60*60*24*365.2425)\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * np.pi**2\n\n"""\nExclusive body interaction indices; effectively:\nfor j in; for k in; if j != k\n [[0, 0, 0, 1, 1, 2],\n [1, 2, 3, 2, 3, 3]]\n"""\nindices = np.stack(np.triu_indices(n=mass.size, m=mass.size, k=1)) # (2,10)\nj, k = indices # each (10,)\n\n"""\nInteraction matrix such that A (5,10) . ||r||^-3 (10) . r(10,2) = dv(5,2)\nExample for a smaller system with four bodies:\n jk jk jk jk jk jk\n 01 02 03 12 13 23\nj0 1 1 1 \nj1 -1 1 1\nj2 -1 -1 1\nj3 -1 -1 -1 signs are to effectively swap xy[j] - xy[k]\n\n[[-9.7e-10, -1.2e-09, -1.3e-10, -0.0e+00, -0.0e+00, -0.0e+00],\n [ 3.9e-04, -0.0e+00, -0.0e+00, -1.2e-09, -1.3e-10, -0.0e+00],\n [-0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, -0.0e+00, -1.3e-10],\n [-0.0e+00, -0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, 1.2e-09]]\n"""\nA = np.zeros((mass.size, j.size)) # (5,10)\ni = np.arange(j.size) # (10,)\ndt_G_mass = dt*G*mass # (5,)\nA[j, i] = (-dt_G_mass)[k]\nA[k, i] = (dt_G_mass)[j]\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(n-1):\n pj, pk = all_p[i, indices] # Interaction previous positions, each (10,2)\n r = pj - pk # (10,2) # Interaction displacement, effectively xy[j] - xy[k]\n\n # Interaction norms, effectively: 1/(((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n norms = np.linalg.norm(r, axis=1, keepdims=1)**-3 # (10,1)\n\n # Gravitational acceleration exerted by body k on body j\n v += A @ (norms * r) # Effectively: vxy[l] += axy[l] * dt\n all_p[i+1] = all_p[i] + v*dt # Effectively: xy[l] += vxy[l] * dt\n\nfig, ax = plt.subplots()\nfor name, data in zip(\n ('Sol', 'Mercury', 'Venus', 'Earth', 'Mars'),\n all_p.transpose((1, 2, 0)),\n):\n ax.plot(*data, label=name)\nax.legend()\nplt.show()\n\n\n\n", "answer_id": 45501, "answer_text": "I really don't think you should be adding your masses (if you do, you tend to eject planets from the solar system).\n\n\n\n\nAlso, I feel the need to remind you that\n\n\n\n\n\nyou need to vectorise - Python is inherently brutally slow, so it doesn't surprise me that you're worrying about printing simulation time;\n\n\n\n\nyou should be treating this as an IVP and leveraging a good library, which will (for our purposes) always do better than a naive implementation.\n\n\n\n\n\nStopping short of rewriting this as an IVP for you, the vectorised version can look like:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 201 # Step count\nyears = 0.95 # Duration (years)\ndt = years/(n-1) # Time step (years/step)\n\n# Masses expressed in solar masses, derived from kg\n# https://ssd.jpl.nasa.gov/planets/phys_par.html\nmass = np.array(( # (5,)\n 1.988475e30, # Sol\n 0.330103e24, # Mercury\n 4.867310e24, # Venus\n 5.972170e24, # Earth\n 0.641691e24, # Mars\n))/1.988475e30\n\n# Distances in astronomical units (AU)\n# 1 AU = 1.495978707e11 m\n# Positions, having an initial value set to body's semi-major axis\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nall_p = np.empty((n, mass.size, 2))\nall_p[0] = (\n (0., 0.), # Sol\n (0.387098, 0.), # Mercury\n (0.723332, 0.), # Venus\n (1., 0.), # Earth\n (1.52368055, 0.), # Mars\n)\n\n# Velocity (AU/year), derived from km/s\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nv = np.array(( # (5,2)\n (0., 0. ), # Sol\n (0., 47.36 ), # Mercury\n (0., 35.02 ), # Venus\n (0., 29.7827), # Earth\n (0., 24.07 ), # Mars\n)) * (1e3/1.495978707e11 *60*60*24*365.2425)\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * np.pi**2\n\n\"\"\"\nExclusive body interaction indices; effectively:\nfor j in; for k in; if j != k\n [[0, 0, 0, 1, 1, 2],\n [1, 2, 3, 2, 3, 3]]\n\"\"\"\nindices = np.stack(np.triu_indices(n=mass.size, m=mass.size, k=1)) # (2,10)\nj, k = indices # each (10,)\n\n\"\"\"\nInteraction matrix such that A (5,10) . ||r||^-3 (10) . r(10,2) = dv(5,2)\nExample for a smaller system with four bodies:\n jk jk jk jk jk jk\n 01 02 03 12 13 23\nj0 1 1 1 \nj1 -1 1 1\nj2 -1 -1 1\nj3 -1 -1 -1 signs are to effectively swap xy[j] - xy[k]\n\n[[-9.7e-10, -1.2e-09, -1.3e-10, -0.0e+00, -0.0e+00, -0.0e+00],\n [ 3.9e-04, -0.0e+00, -0.0e+00, -1.2e-09, -1.3e-10, -0.0e+00],\n [-0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, -0.0e+00, -1.3e-10],\n [-0.0e+00, -0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, 1.2e-09]]\n\"\"\"\nA = np.zeros((mass.size, j.size)) # (5,10)\ni = np.arange(j.size) # (10,)\ndt_G_mass = dt*G*mass # (5,)\nA[j, i] = (-dt_G_mass)[k]\nA[k, i] = (dt_G_mass)[j]\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(n-1):\n pj, pk = all_p[i, indices] # Interaction previous positions, each (10,2)\n r = pj - pk # (10,2) # Interaction displacement, effectively xy[j] - xy[k]\n\n # Interaction norms, effectively: 1/(((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n norms = np.linalg.norm(r, axis=1, keepdims=1)**-3 # (10,1)\n\n # Gravitational acceleration exerted by body k on body j\n v += A @ (norms * r) # Effectively: vxy[l] += axy[l] * dt\n all_p[i+1] = all_p[i] + v*dt # Effectively: xy[l] += vxy[l] * dt\n\nfig, ax = plt.subplots()\nfor name, data in zip(\n ('Sol', 'Mercury', 'Venus', 'Earth', 'Mars'),\n all_p.transpose((1, 2, 0)),\n):\n ax.plot(*data, label=name)\nax.legend()\nplt.show()\n\n\n\n\n\n[image: orbit; source: https://i.sstatic.net/LhxHLqTd.png] (https://i.sstatic.net/LhxHLqTd.png)\n\n\n\n\n[image: detail; source: https://i.sstatic.net/4hfjqDYL.png] (https://i.sstatic.net/4hfjqDYL.png)", "answer_url": "https://scicomp.stackexchange.com/a/45501", "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-07-26T21:58:33+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": 45499, "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-07-26T21:58:33+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "EF321E57-4E53-4FF8-8A71-168FCE2ABCEA", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/EF321E57-4E53-4FF8-8A71-168FCE2ABCEA/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-07-26T22:17:48+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "3395FCAD-0F42-401F-82C1-7A4A3F6DD667", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3395FCAD-0F42-401F-82C1-7A4A3F6DD667/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-07-26T23:16:40+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "B57EC924-2004-47BD-8F48-18BF4689A68A", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B57EC924-2004-47BD-8F48-18BF4689A68A/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-07-26T23:59:54+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "24BECCC5-5481-4A1E-9914-5605FB3E7FBA", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/24BECCC5-5481-4A1E-9914-5605FB3E7FBA/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-07-27T00:13:00+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "100FC7CD-8D17-4210-AF56-663AB1987016", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/100FC7CD-8D17-4210-AF56-663AB1987016/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-07-27T22:23:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "0A4D6874-4E2E-4411-82AD-5833BB738B39", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/0A4D6874-4E2E-4411-82AD-5833BB738B39/view-source"}], "score": 4, "updated_at": "2026-07-27T22:23:55+00:00"}], "product": "code_qa", "question": "I implemented the following code to simulate an $N$-body gravitational system (here: the Sun, Earth, and Mars).\n\n\n\n\nThe code is:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport winsound as ws\nfrom matplotlib.animation import FuncAnimation\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * (np.pi)**2\n\n# Distance from the Sun in astronomical units (AU)\n# 1 AU ≈ 149.6 million km\n\n# Initial x coordinates\nx = [\n 1, # Earth\n 1.5237, # Mars\n 0 # Sun\n]\n\n# Initial y coordinates\ny = [\n 0, # Earth\n 0, # Mars\n 0 # Sun\n]\n\n# Lists storing the x coordinates during the simulation\nxpos = [[], [], []]\n\n# Lists storing the y coordinates during the simulation\nypos = [[], [], []]\n\n# Initial velocity components (AU/year)\nvx = [0, 0, 0]\n\n# Initial tangential velocities (AU/year)\nvy = [\n 6.281991687112502, # Earth\n 5.0867271316753815, # Mars \n 0 # Sun\n]\n\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n# Masses expressed in solar masses\nmass = [\n 3.002513826043238e-06, # Earth\n 3.2267471091000503e-07, # Mars \n 1 # Sun\n]\n\n# Time step (years)\ndt = 0.00001\n\nstart_time = time.time()\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n for l in range(len(x)):\n\n # Velocity update\n vx[l] += ax[l] * dt\n vy[l] += ay[l] * dt\n\n # Store trajectory\n xpos[l].append(x[l])\n ypos[l].append(y[l])\n\n # Position update\n x[l] += vx[l] * dt\n y[l] += vy[l] * dt\n\nend_time = time.time()\n\nprint(f\"Simulation time: {end_time-start_time:.2f} s\")\n\n# Audible notification when the simulation is finished\nws.Beep(400, 1000)\n\nplt.plot(xpos[0], ypos[0], label=\"Earth\", color=\"green\")\nplt.plot(xpos[1], ypos[1], label=\"mars\", color=\"violet\")\nplt.plot(xpos[2], ypos[2], label=\"sun\", color=\"red\")\n\nplt.legend()\nplt.show()\n\n\n\n\n\nThis produces the following result:\n\n\n\n\n[image: The resulte of the code above; source: https://i.sstatic.net/f5j0wZO6.png] (https://i.sstatic.net/f5j0wZO6.png)\n\n\n\n\nAt first glance, one might think the problem comes from the fact that I overwrite the acceleration instead of accumulating the contributions from all the other bodies.\n\n\n\n\nSo I changed\n\n\n\n\nax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])\n\n\n\n\n\nto\n\n\n\n\nax[j] += -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] += -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n\n\n\n\nsince the total acceleration acting on body j should be the sum of the accelerations produced by every other body.\n\n\n\n\nHowever, this actually makes the simulation even worse. The result becomes:\n\n\n\n\n[image: the result of the modified code; source: https://i.sstatic.net/cWWHipMg.png] (https://i.sstatic.net/cWWHipMg.png)\n\n\n\n\nSo I feel that I am missing something more fundamental.\n\n\n\n\nAnother thing I do not understand is the behavior of the Sun in the first version. Since the acceleration is overwritten, the Sun ends up accelerating only because of the last body processed in the loop (Mars). However, the Sun is much more massive than either Earth or Mars (1 >> 3.0025e-6 and 1 >> 3.2267e-7), so I would not expect such a large acceleration. Why does this happen?\n\n\n\n\nLikewise, why does the += version diverge so quickly instead of improving the simulation?\n\n\n\n\nMy ultimate goal is to simulate the Solar System (the Sun and the eight planets) using this double loop, but if the simulation is already unstable with only three bodies, I am clearly doing something wrong.\n\n\n\n\nFinally, I intentionally initialized the Sun with zero position, zero velocity, and zero acceleration because I wanted it to remain fixed at the origin, assuming that the Solar System barycenter is approximately at the center of the Sun.", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45499", "selected_answer": {"answer_html": "Your loop structure to accumulate the acceleration is wrong:
\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n [...]\n\nax and ay always increase, since they are never reset to zero. In this way, you accumulate the contributions for all bodies over all time steps. Instead, you should compute the acceleration starting back from zero in each time step i.
Your loop structure to accumulate the acceleration is wrong:
\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n[...]\n\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n [...]\n\nax and ay always increase, since they are never reset to zero. In this way, you accumulate the contributions for all bodies over all time steps. Instead, you should compute the acceleration starting back from zero in each time step i.
I really don't think you should be adding your masses (if you do, you tend to eject planets from the solar system).
\nAlso, I feel the need to remind you that
\nStopping short of rewriting this as an IVP for you, the vectorised version can look like:
\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 201 # Step count\nyears = 0.95 # Duration (years)\ndt = years/(n-1) # Time step (years/step)\n\n# Masses expressed in solar masses, derived from kg\n# https://ssd.jpl.nasa.gov/planets/phys_par.html\nmass = np.array(( # (5,)\n 1.988475e30, # Sol\n 0.330103e24, # Mercury\n 4.867310e24, # Venus\n 5.972170e24, # Earth\n 0.641691e24, # Mars\n))/1.988475e30\n\n# Distances in astronomical units (AU)\n# 1 AU = 1.495978707e11 m\n# Positions, having an initial value set to body's semi-major axis\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nall_p = np.empty((n, mass.size, 2))\nall_p[0] = (\n (0., 0.), # Sol\n (0.387098, 0.), # Mercury\n (0.723332, 0.), # Venus\n (1., 0.), # Earth\n (1.52368055, 0.), # Mars\n)\n\n# Velocity (AU/year), derived from km/s\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nv = np.array(( # (5,2)\n (0., 0. ), # Sol\n (0., 47.36 ), # Mercury\n (0., 35.02 ), # Venus\n (0., 29.7827), # Earth\n (0., 24.07 ), # Mars\n)) * (1e3/1.495978707e11 *60*60*24*365.2425)\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * np.pi**2\n\n"""\nExclusive body interaction indices; effectively:\nfor j in; for k in; if j != k\n [[0, 0, 0, 1, 1, 2],\n [1, 2, 3, 2, 3, 3]]\n"""\nindices = np.stack(np.triu_indices(n=mass.size, m=mass.size, k=1)) # (2,10)\nj, k = indices # each (10,)\n\n"""\nInteraction matrix such that A (5,10) . ||r||^-3 (10) . r(10,2) = dv(5,2)\nExample for a smaller system with four bodies:\n jk jk jk jk jk jk\n 01 02 03 12 13 23\nj0 1 1 1 \nj1 -1 1 1\nj2 -1 -1 1\nj3 -1 -1 -1 signs are to effectively swap xy[j] - xy[k]\n\n[[-9.7e-10, -1.2e-09, -1.3e-10, -0.0e+00, -0.0e+00, -0.0e+00],\n [ 3.9e-04, -0.0e+00, -0.0e+00, -1.2e-09, -1.3e-10, -0.0e+00],\n [-0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, -0.0e+00, -1.3e-10],\n [-0.0e+00, -0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, 1.2e-09]]\n"""\nA = np.zeros((mass.size, j.size)) # (5,10)\ni = np.arange(j.size) # (10,)\ndt_G_mass = dt*G*mass # (5,)\nA[j, i] = (-dt_G_mass)[k]\nA[k, i] = (dt_G_mass)[j]\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(n-1):\n pj, pk = all_p[i, indices] # Interaction previous positions, each (10,2)\n r = pj - pk # (10,2) # Interaction displacement, effectively xy[j] - xy[k]\n\n # Interaction norms, effectively: 1/(((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n norms = np.linalg.norm(r, axis=1, keepdims=1)**-3 # (10,1)\n\n # Gravitational acceleration exerted by body k on body j\n v += A @ (norms * r) # Effectively: vxy[l] += axy[l] * dt\n all_p[i+1] = all_p[i] + v*dt # Effectively: xy[l] += vxy[l] * dt\n\nfig, ax = plt.subplots()\nfor name, data in zip(\n ('Sol', 'Mercury', 'Venus', 'Earth', 'Mars'),\n all_p.transpose((1, 2, 0)),\n):\n ax.plot(*data, label=name)\nax.legend()\nplt.show()\n\n\n\n", "answer_id": 45501, "answer_text": "I really don't think you should be adding your masses (if you do, you tend to eject planets from the solar system).\n\n\n\n\nAlso, I feel the need to remind you that\n\n\n\n\n\nyou need to vectorise - Python is inherently brutally slow, so it doesn't surprise me that you're worrying about printing simulation time;\n\n\n\n\nyou should be treating this as an IVP and leveraging a good library, which will (for our purposes) always do better than a naive implementation.\n\n\n\n\n\nStopping short of rewriting this as an IVP for you, the vectorised version can look like:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nn = 201 # Step count\nyears = 0.95 # Duration (years)\ndt = years/(n-1) # Time step (years/step)\n\n# Masses expressed in solar masses, derived from kg\n# https://ssd.jpl.nasa.gov/planets/phys_par.html\nmass = np.array(( # (5,)\n 1.988475e30, # Sol\n 0.330103e24, # Mercury\n 4.867310e24, # Venus\n 5.972170e24, # Earth\n 0.641691e24, # Mars\n))/1.988475e30\n\n# Distances in astronomical units (AU)\n# 1 AU = 1.495978707e11 m\n# Positions, having an initial value set to body's semi-major axis\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nall_p = np.empty((n, mass.size, 2))\nall_p[0] = (\n (0., 0.), # Sol\n (0.387098, 0.), # Mercury\n (0.723332, 0.), # Venus\n (1., 0.), # Earth\n (1.52368055, 0.), # Mars\n)\n\n# Velocity (AU/year), derived from km/s\n# https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System\nv = np.array(( # (5,2)\n (0., 0. ), # Sol\n (0., 47.36 ), # Mercury\n (0., 35.02 ), # Venus\n (0., 29.7827), # Earth\n (0., 24.07 ), # Mars\n)) * (1e3/1.495978707e11 *60*60*24*365.2425)\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * np.pi**2\n\n\"\"\"\nExclusive body interaction indices; effectively:\nfor j in; for k in; if j != k\n [[0, 0, 0, 1, 1, 2],\n [1, 2, 3, 2, 3, 3]]\n\"\"\"\nindices = np.stack(np.triu_indices(n=mass.size, m=mass.size, k=1)) # (2,10)\nj, k = indices # each (10,)\n\n\"\"\"\nInteraction matrix such that A (5,10) . ||r||^-3 (10) . r(10,2) = dv(5,2)\nExample for a smaller system with four bodies:\n jk jk jk jk jk jk\n 01 02 03 12 13 23\nj0 1 1 1 \nj1 -1 1 1\nj2 -1 -1 1\nj3 -1 -1 -1 signs are to effectively swap xy[j] - xy[k]\n\n[[-9.7e-10, -1.2e-09, -1.3e-10, -0.0e+00, -0.0e+00, -0.0e+00],\n [ 3.9e-04, -0.0e+00, -0.0e+00, -1.2e-09, -1.3e-10, -0.0e+00],\n [-0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, -0.0e+00, -1.3e-10],\n [-0.0e+00, -0.0e+00, 3.9e-04, -0.0e+00, 9.7e-10, 1.2e-09]]\n\"\"\"\nA = np.zeros((mass.size, j.size)) # (5,10)\ni = np.arange(j.size) # (10,)\ndt_G_mass = dt*G*mass # (5,)\nA[j, i] = (-dt_G_mass)[k]\nA[k, i] = (dt_G_mass)[j]\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(n-1):\n pj, pk = all_p[i, indices] # Interaction previous positions, each (10,2)\n r = pj - pk # (10,2) # Interaction displacement, effectively xy[j] - xy[k]\n\n # Interaction norms, effectively: 1/(((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n norms = np.linalg.norm(r, axis=1, keepdims=1)**-3 # (10,1)\n\n # Gravitational acceleration exerted by body k on body j\n v += A @ (norms * r) # Effectively: vxy[l] += axy[l] * dt\n all_p[i+1] = all_p[i] + v*dt # Effectively: xy[l] += vxy[l] * dt\n\nfig, ax = plt.subplots()\nfor name, data in zip(\n ('Sol', 'Mercury', 'Venus', 'Earth', 'Mars'),\n all_p.transpose((1, 2, 0)),\n):\n ax.plot(*data, label=name)\nax.legend()\nplt.show()\n\n\n\n\n\n[image: orbit; source: https://i.sstatic.net/LhxHLqTd.png] (https://i.sstatic.net/LhxHLqTd.png)\n\n\n\n\n[image: detail; source: https://i.sstatic.net/4hfjqDYL.png] (https://i.sstatic.net/4hfjqDYL.png)", "answer_url": "https://scicomp.stackexchange.com/a/45501", "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-07-26T21:58:33+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": 45499, "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-07-26T21:58:33+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "EF321E57-4E53-4FF8-8A71-168FCE2ABCEA", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/EF321E57-4E53-4FF8-8A71-168FCE2ABCEA/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-07-26T22:17:48+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "3395FCAD-0F42-401F-82C1-7A4A3F6DD667", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/3395FCAD-0F42-401F-82C1-7A4A3F6DD667/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-07-26T23:16:40+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "B57EC924-2004-47BD-8F48-18BF4689A68A", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B57EC924-2004-47BD-8F48-18BF4689A68A/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-07-26T23:59:54+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "24BECCC5-5481-4A1E-9914-5605FB3E7FBA", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/24BECCC5-5481-4A1E-9914-5605FB3E7FBA/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-07-27T00:13:00+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "100FC7CD-8D17-4210-AF56-663AB1987016", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/100FC7CD-8D17-4210-AF56-663AB1987016/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-07-27T22:23:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "0A4D6874-4E2E-4411-82AD-5833BB738B39", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/0A4D6874-4E2E-4411-82AD-5833BB738B39/view-source"}], "score": 4, "updated_at": "2026-07-27T22:23:55+00:00"}], "domain": "computational_science", "external_links": ["https://en.wikipedia.org/wiki/Category:Planets_of_the_Solar_System", "https://i.sstatic.net/4hfjqDYL.png", "https://i.sstatic.net/LhxHLqTd.png", "https://i.sstatic.net/cWWHipMg.png", "https://i.sstatic.net/f5j0wZO6.png", "https://ssd.jpl.nasa.gov/planets/phys_par.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": "Omar Osman Mahamoud", "question_author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "question_author_user_type": "registered", "question_created_at": "2026-07-26T12:32:03+00:00", "question_html": "I implemented the following code to simulate an $N$-body gravitational system (here: the Sun, Earth, and Mars).
\nThe code is:
\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport winsound as ws\nfrom matplotlib.animation import FuncAnimation\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * (np.pi)**2\n\n# Distance from the Sun in astronomical units (AU)\n# 1 AU ≈ 149.6 million km\n\n# Initial x coordinates\nx = [\n 1, # Earth\n 1.5237, # Mars\n 0 # Sun\n]\n\n# Initial y coordinates\ny = [\n 0, # Earth\n 0, # Mars\n 0 # Sun\n]\n\n# Lists storing the x coordinates during the simulation\nxpos = [[], [], []]\n\n# Lists storing the y coordinates during the simulation\nypos = [[], [], []]\n\n# Initial velocity components (AU/year)\nvx = [0, 0, 0]\n\n# Initial tangential velocities (AU/year)\nvy = [\n 6.281991687112502, # Earth\n 5.0867271316753815, # Mars \n 0 # Sun\n]\n\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n# Masses expressed in solar masses\nmass = [\n 3.002513826043238e-06, # Earth\n 3.2267471091000503e-07, # Mars \n 1 # Sun\n]\n\n# Time step (years)\ndt = 0.00001\n\nstart_time = time.time()\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n for l in range(len(x)):\n\n # Velocity update\n vx[l] += ax[l] * dt\n vy[l] += ay[l] * dt\n\n # Store trajectory\n xpos[l].append(x[l])\n ypos[l].append(y[l])\n\n # Position update\n x[l] += vx[l] * dt\n y[l] += vy[l] * dt\n\nend_time = time.time()\n\nprint(f"Simulation time: {end_time-start_time:.2f} s")\n\n# Audible notification when the simulation is finished\nws.Beep(400, 1000)\n\nplt.plot(xpos[0], ypos[0], label="Earth", color="green")\nplt.plot(xpos[1], ypos[1], label="mars", color="violet")\nplt.plot(xpos[2], ypos[2], label="sun", color="red")\n\nplt.legend()\nplt.show()\n\nThis produces the following result:
\n\nAt first glance, one might think the problem comes from the fact that I overwrite the acceleration instead of accumulating the contributions from all the other bodies.
\nSo I changed
\nax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])\n\nto
\nax[j] += -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] += -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\nsince the total acceleration acting on body j should be the sum of the accelerations produced by every other body.
\nHowever, this actually makes the simulation even worse. The result becomes:
\n\nSo I feel that I am missing something more fundamental.
\nAnother thing I do not understand is the behavior of the Sun in the first version. Since the acceleration is overwritten, the Sun ends up accelerating only because of the last body processed in the loop (Mars). However, the Sun is much more massive than either Earth or Mars (1 >> 3.0025e-6 and 1 >> 3.2267e-7), so I would not expect such a large acceleration. Why does this happen?
\nLikewise, why does the += version diverge so quickly instead of improving the simulation?
\nMy ultimate goal is to simulate the Solar System (the Sun and the eight planets) using this double loop, but if the simulation is already unstable with only three bodies, I am clearly doing something wrong.
\nFinally, I intentionally initialized the Sun with zero position, zero velocity, and zero acceleration because I wanted it to remain fixed at the origin, assuming that the Solar System barycenter is approximately at the center of the Sun.
\n", "question_id": 45499, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I implemented the following code to simulate an $N$-body gravitational system (here: the Sun, Earth, and Mars).\n\n\n\n\nThe code is:\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport winsound as ws\nfrom matplotlib.animation import FuncAnimation\n\n# Universal gravitational constant in AU^3/(solar mass * year^2)\nG = 4 * (np.pi)**2\n\n# Distance from the Sun in astronomical units (AU)\n# 1 AU ≈ 149.6 million km\n\n# Initial x coordinates\nx = [\n 1, # Earth\n 1.5237, # Mars\n 0 # Sun\n]\n\n# Initial y coordinates\ny = [\n 0, # Earth\n 0, # Mars\n 0 # Sun\n]\n\n# Lists storing the x coordinates during the simulation\nxpos = [[], [], []]\n\n# Lists storing the y coordinates during the simulation\nypos = [[], [], []]\n\n# Initial velocity components (AU/year)\nvx = [0, 0, 0]\n\n# Initial tangential velocities (AU/year)\nvy = [\n 6.281991687112502, # Earth\n 5.0867271316753815, # Mars \n 0 # Sun\n]\n\n# Acceleration components\nax = [0] * 3\nay = [0] * 3\n\n# Masses expressed in solar masses\nmass = [\n 3.002513826043238e-06, # Earth\n 3.2267471091000503e-07, # Mars \n 1 # Sun\n]\n\n# Time step (years)\ndt = 0.00001\n\nstart_time = time.time()\n\n# Symplectic Euler integration for the N-body gravitational problem\nfor i in range(10**5):\n for j in range(len(x)):\n for k in range(len(x)):\n if j != k: # so that a body doesn't interact with its self\n # Gravitational acceleration exerted by body k on body j\n ax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n ay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n for l in range(len(x)):\n\n # Velocity update\n vx[l] += ax[l] * dt\n vy[l] += ay[l] * dt\n\n # Store trajectory\n xpos[l].append(x[l])\n ypos[l].append(y[l])\n\n # Position update\n x[l] += vx[l] * dt\n y[l] += vy[l] * dt\n\nend_time = time.time()\n\nprint(f\"Simulation time: {end_time-start_time:.2f} s\")\n\n# Audible notification when the simulation is finished\nws.Beep(400, 1000)\n\nplt.plot(xpos[0], ypos[0], label=\"Earth\", color=\"green\")\nplt.plot(xpos[1], ypos[1], label=\"mars\", color=\"violet\")\nplt.plot(xpos[2], ypos[2], label=\"sun\", color=\"red\")\n\nplt.legend()\nplt.show()\n\n\n\n\n\nThis produces the following result:\n\n\n\n\n[image: The resulte of the code above; source: https://i.sstatic.net/f5j0wZO6.png] (https://i.sstatic.net/f5j0wZO6.png)\n\n\n\n\nAt first glance, one might think the problem comes from the fact that I overwrite the acceleration instead of accumulating the contributions from all the other bodies.\n\n\n\n\nSo I changed\n\n\n\n\nax[j] = -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] = -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])\n\n\n\n\n\nto\n\n\n\n\nax[j] += -G * (mass[j] + mass[k]) * (x[j] - x[k]) / (((x[j]-x[k])**2 + (y[j]- y[k])**2)**0.5)**3\nay[j] += -G * (mass[j] + mass[k]) * (y[j] - y[k]) / (((x[j]-x[k])**2 + (y[j]-y[k])**2)**0.5)**3\n\n\n\n\n\nsince the total acceleration acting on body j should be the sum of the accelerations produced by every other body.\n\n\n\n\nHowever, this actually makes the simulation even worse. The result becomes:\n\n\n\n\n[image: the result of the modified code; source: https://i.sstatic.net/cWWHipMg.png] (https://i.sstatic.net/cWWHipMg.png)\n\n\n\n\nSo I feel that I am missing something more fundamental.\n\n\n\n\nAnother thing I do not understand is the behavior of the Sun in the first version. Since the acceleration is overwritten, the Sun ends up accelerating only because of the last body processed in the loop (Mars). However, the Sun is much more massive than either Earth or Mars (1 >> 3.0025e-6 and 1 >> 3.2267e-7), so I would not expect such a large acceleration. Why does this happen?\n\n\n\n\nLikewise, why does the += version diverge so quickly instead of improving the simulation?\n\n\n\n\nMy ultimate goal is to simulate the Solar System (the Sun and the eight planets) using this double loop, but if the simulation is already unstable with only three bodies, I am clearly doing something wrong.\n\n\n\n\nFinally, I intentionally initialized the Sun with zero position, zero velocity, and zero acceleration because I wanted it to remain fixed at the origin, assuming that the Solar System barycenter is approximately at the center of the Sun.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-07-26T12:32:03+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "61294F33-1CB8-459E-AB4B-4941AD8D2670", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/61294F33-1CB8-459E-AB4B-4941AD8D2670/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-07-27T11:52:44+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "3F7393D0-FAE5-408C-BCD8-32B84FC1BD39", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/3F7393D0-FAE5-408C-BCD8-32B84FC1BD39/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45499/n-body-gravitation", "split": "holdout", "split_group": "45d6b72512daab67fd2b92518c117829c50d23b2add0374b0be035746ba7ae04", "tags": ["python", "computational-physics", "simulation", "numerical-integration", "physics"], "thread_id": "scicomp:45499", "title": "N-body gravitation"}} {"accepted_answer": {"answer_html": "You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.
Let ufft be your current solution in frequency space, then:
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.
You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.
Let ufft be your current solution in frequency space, then:
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.
You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term (Au)**3 to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it should also become apparent.
Let ufft be your current solution in frequency space, then:
ureal = ifft(ufft).real # real part of the real space solution\nnlterm = fft(ureal**3) * mask # nonlinear term transformed to frequency space, then dealias\n[update formula for all terms in frequency space, ending with updating ufft again]\n\nI'm not sure how you got sensible looking solutions with your original code since that (Au)**3 term should've induced some very sharp transitions on the 0/1 boundaries. The energy should've also increased from that and the kinetics of course being all wrong. I'd suggest you check any further developments with exact known solutions like a phase vanishing under mean curvature flow. Set a circular phase and observe that its area decreases linearly in time. You can figure out the right prefactor for your PDE by transforming into a curvilinear system and doing some approximations, see e.g. 10.1103/PhysRevB.78.024113 "Grain boundary velocity". Depending on what your goals are you might also want to use pre-made phase-field software.
I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods. Accordingly, I have implemented the scheme as follows::
\n# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n u_t = np.fft.ifft2(fft)\n cubed = (u_t.real*freq_mask) ** 3\n cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n\nThe code is working pretty well and I have tried various initial conditions and it gives the classic island evaporation behavior to reach a stable solution of a homogeneous solution or a kink. The problem arises if I run the solution more than 7000 steps (roughly). After that the stable state becomes unstable and the field values blow up to NaN. I am very new to this field, so I consulted with a LLM and according to it the problem is with some imaginary value errors slowly creeping in. To prevent it the fft is to be again updated with a fresh value by doing an ifft of u_t [fft = np.fft.fft2(u_t.real)]. This prevents the blowup but I am not sure what is the proper logic behind this fix. Can someone please explain how is this fix working.
\n", "question_id": 45510, "question_license": "CC BY-SA 4.0", "question_score": 2, "question_text": "I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods (https://open.umich.edu/sites/default/files/downloads/2012-parallel-spectral-numerical-methods.pdf). Accordingly, I have implemented the scheme as follows::\n\n\n\n\n# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit - Explicit Method\ncubed = u_0 ** 3\ncubed_fft = np.fft.fft2(cubed)\nfft = np.fft.fft2(u_0)\n\n\nfor t in tqdm(range(timesteps)):\n\n fft = (fft*(1 + 1/delta) - cubed_fft) / (epsilon*mag_sqr + 1/delta)\n u_t = np.fft.ifft2(fft)\n cubed = (u_t.real*freq_mask) ** 3\n cubed_fft = np.fft.fft2(cubed)*freq_mask\n\nu_t = np.fft.ifft2(fft)\n\n\n\n\n\nThe code is working pretty well and I have tried various initial conditions and it gives the classic island evaporation behavior to reach a stable solution of a homogeneous solution or a kink. The problem arises if I run the solution more than 7000 steps (roughly). After that the stable state becomes unstable and the field values blow up to NaN. I am very new to this field, so I consulted with a LLM and according to it the problem is with some imaginary value errors slowly creeping in. To prevent it the fft is to be again updated with a fresh value by doing an ifft of u_t [fft = np.fft.fft2(u_t.real)]. This prevents the blowup but I am not sure what is the proper logic behind this fix. Can someone please explain how is this fix working.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Manav Jalan", "profile_url": "https://scicomp.stackexchange.com/users/57116/manav-jalan", "user_type": "registered"}, "created_at": "2026-08-05T11:30:29+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "89E117A0-D17A-486B-9AB6-3BFCFC57C353", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/89E117A0-D17A-486B-9AB6-3BFCFC57C353/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-06T12:01:54+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "669E53D8-1766-46EB-8CA1-42CE9017157D", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/669E53D8-1766-46EB-8CA1-42CE9017157D/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio", "split": "train", "split_group": "6d0c54a4e8c7f952e689a3d4b5202b082d3107c2394fe7cc81a815a1a0401dc5", "tags": ["computational-physics", "spectral-method", "pseudospectral"], "thread_id": "scicomp:45510", "title": "Allen Cahn Psuedospectral solver blowup even after reaching steady state solution"}} {"accepted_answer": {"answer_html": "Your calculation
\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\nis wrong. Notice your typo in the last vector term.
\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.
\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\ncbcf = 88.56°\nabaf = 88.56°\n\nFinally:
\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$
\n
This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,
\nfor n in range(5, 21, 2):\n # ...\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.
\n", "answer_id": 45524, "answer_text": "Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\nYour calculation
\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\nis wrong. Notice your typo in the last vector term.
\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.
\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\ncbcf = 88.56°\nabaf = 88.56°\n\nFinally:
\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$
\n
This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,
\nfor n in range(5, 21, 2):\n # ...\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.
\n", "answer_id": 45524, "answer_text": "Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\nYour calculation
\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\nis wrong. Notice your typo in the last vector term.
\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no -
<source>: In function 'main':\n<source>:7:12: error: unused variable 'pid' [-Werror=unused-variable]\n 7 | double pid;\n | ^~~\n<source>:38:23: error: 'vece' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:33:12: note: 'vece' declared here\n 33 | double vece[2];\n | ^~~~\n<source>:38:31: error: 'vecd' is used uninitialized [-Werror=uninitialized]\n 38 | vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n | ~~~~^~~\n<source>:29:12: note: 'vecd' declared here\n 29 | double vecd[2];\n | ^~~~\ncc1: all warnings being treated as errors\nCompiler returned: 1\n\nMore broadly, C is simply the wrong choice for this application. Use Octave, Python, or something better-suited to math prototyping.
\nimport numpy as np\nfrom numpy.linalg import norm\n\nn = 7\n\n# Clockwise from north\nangles = np.linspace(start=0.5*np.pi, stop=2*np.pi*(1/n - 0.75), num=n)\nvertices = np.stack((np.cos(angles), np.sin(angles)), axis=-1)\n\na, b, c, d, e = vertices[[-1, 0, 1, n//2, n//2 + 1]]\nf = np.array((0, e[1]))\n\ncb = b - c\ncf = f - c\ncbcf = np.acos(cb.dot(cf)/norm(cb)/norm(cf))\nprint(f'cbcf = {np.rad2deg(cbcf):.2f}°')\n\nab = b - a\naf = f - a\nabaf = np.acos(ab.dot(af)/norm(ab)/norm(af))\nprint(f'abaf = {np.rad2deg(abaf):.2f}°')\n\ncbcf = 88.56°\nabaf = 88.56°\n\nFinally:
\n\n\nthe angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$
\n
This is not a coincidence, and has essentially nothing to do with you using a heptagon in particular. For increasing polygon sides,
\nfor n in range(5, 21, 2):\n # ...\n\nn = 5\ncbcf = 85.61°\nabaf = 85.61°\n\nn = 7\ncbcf = 88.56°\nabaf = 88.56°\n\nn = 9\ncbcf = 89.35°\nabaf = 89.35°\n\nn = 11\ncbcf = 89.65°\nabaf = 89.65°\n\nn = 13\ncbcf = 89.79°\nabaf = 89.79°\n\nn = 15\ncbcf = 89.87°\nabaf = 89.87°\n\nn = 17\ncbcf = 89.91°\nabaf = 89.91°\n\nn = 19\ncbcf = 89.93°\nabaf = 89.93°\n\nYou can prove that $\\lim \\limits_{n \\to \\infty } \\angle{BAF} = \\frac \\pi 2$.
\n", "answer_id": 45524, "answer_text": "Your calculation\n\n\n\n\nvecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n\n\n\n\n\nis wrong. Notice your typo in the last vector term.\n\n\n\n\nBut also... your code listing does not make sense, because vecf is calculated before its dependencies. Any sane C warning configuration would prevent this from compiling. For example, see https://godbolt.org/z/xaT1cx7no (https://godbolt.org/z/xaT1cx7no) -\n\n\n\n\nI am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:
\n\n\nI tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:
\nDouble: acos(-1.0) 3.141592653589793 \nDouble: vec cb dot vec cf 0.376510198141266\nDouble: vec ab dot vec af 0.611260466978158\nDouble: coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble: cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n\nHow can I debug the C program to arrive at reasonable values for the calculated angles?
\nThe source code was updated taking the suggestions from Reinderien's answer. After that, it yields similar answers to: "Figure. Regular Heptagon Image taken from a Math Stack Exchange Question", shown below. The problem is that questioner was assuming that angle\n$\\angle BCF=90^{\\circ}$ and that $\\angle BCF \\ne \\angle BAF$ when in actuality $\\angle BCF=\\angle BAF = 88.562883841784526^{\\circ}$.
\nI am very thankful for Reinderien's answer, and I am now giving him an upvote and check mark. For reference, the newest output from my latest version of the C code is here, which is entirely consistent with his except with more decimal places of precision. Note: the C programming language, when properly used, has a history of being used for very important scientific calculations, including for a Journal Contribution that I made in 1991. In any case the newest results are below:
\nRegular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble: vec cb dot vec cf 0.037286231168214\nDouble: vec ab dot vec af 0.037286231168214\nDouble: coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble: cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n\nI was hoping that the angles would turn out somewhat similar to the figure from the below figure from the Stack Exchange Math Figure. And the actual results are similar, but computationally different than the premise in that question about the right angle drawn in the petitioner's figure. That is because the petitioner's figure is incorrect, as indeed there is no right angle at the top right as how he had drawn it.
\n\n\nFrom the question "What could be this unknown angle in this regular\nheptagon?"
\nThere is the image drawn of a Regular Heptagon:
\n\n\n\n
![]()
Figure. Regular Heptagon Image taken from a\nMath Stack Exchange Question
On the site: https://www.onlinegdb.com/online_c_compiler
\n#include <stdio.h>\n#include <math.h>\n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double pid;\n // pid=acos(-1);\n // double DegreesToRadians = 3.14159265358979323846/180.0;\n // double DegreesToRadians = pid/180.0;\n // const double DegreesToRadians=3.14159265358979323846/180.0;\n double DegreesToRadians=acos(-1.0)/180.0;\n \n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n // 3. Print Results\n // %lf is the format specifier for double, %f is for float\n // printf("Double: cos(%.1lf degrees) = %lf\\n", degrees_d, result_double);\n // printf("Float: cos(%.1f degrees) = %f\\n", degrees_f, result_float);\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n\n printf("Double: acos(-1.0) %.15lf \\n",acos(-1.0));\n printf("Double: vec cb dot vec cf %0.15lf\\n", cbdotcf);\n printf("Double: vec ab dot vec af %0.15lf\\n", abdotaf);\n printf("Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf("Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n\n return 0;\n}\n\nTaking the suggestions from Reinderien's answer, the source code was updated. Using the online c compiler https://www.onlinegdb.com/online_c_compiler, the below source code compiled fine and yielded angles very consistent with Reinderien's answer quoted below, with instead of 2 digits precision, 15 digit precision:
\n\n\n\n
n = 7\ncbcf = 88.56°\nabaf = 88.56°
#include <stdio.h>\n#include <math.h>\n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double DegreesToRadians = 3.14159265358979323846/180.0;\n\n //setup vector angles a,b,c,d,e, and f needs to be calculated later\n //setup veca angle to calculate veca vector later with 1 unit radius\n const double veca_angle = (90.0+360.0/7.0)*DegreesToRadians;\n double veca[2];\n\n //setup vecb angle to calculate vecb vector later with 1 unit radius\n const double vecb_angle = (90.0)*DegreesToRadians;\n double vecb[2];\n \n //setup vecc angle to calculate vecc vector later with 1 unit radius\n const double vecc_angle = (90.0-360.0/7.0)*DegreesToRadians;\n double vecc[2];\n\n //setup vecd angle to calculate vecd vector later with 1 unit radius\n const double vecd_angle = (90.0-360.0/7.0*3.0)*DegreesToRadians;\n double vecd[2];\n\n //setup vece angle to calculate vecd vector later with 1 unit radius\n const double vece_angle = (90.0+360.0/7.0*3.0)*DegreesToRadians;\n double vece[2];\n\n //compute cooordinate vectors a through e\n veca[0]=cos(veca_angle); veca[1]=sin(veca_angle);\n vecb[0]=cos(vecb_angle); vecb[1]=sin(vecb_angle);\n vecc[0]=cos(vecc_angle); vecc[1]=sin(vecc_angle);\n vecd[0]=cos(vecd_angle); vecd[1]=sin(vecd_angle);\n vece[0]=cos(vece_angle); vece[1]=sin(vece_angle);\n\n\n //vector vecf needs to be calculated later as half vece + vecd\n double vecf[2];\n //compute cooordinate vector f as 0.5*(e+d)\n vecf[0]=0.5 *(vece[0]+vecd[0]); vecf[1]=0.5 *(vece[1]+vecd[1]);\n\n //vector veccb needs to be calculated later as vector B - vector C\n double veccb[2];\n veccb[0]=vecb[0]-vecc[0]; veccb[1]=vecb[1]-vecc[1];\n\n //vector vecab needs to be calculated later as vector B - vector A\n double vecab[2];\n vecab[0]=vecb[0]-veca[0]; vecab[1]=vecb[1]-veca[1];\n\n //vector vecaf needs to be calculated later as vector F - vector A\n double vecaf[2];\n vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-veca[1];\n\n //vector veccf needs to be calculated later as vector F - vector C\n double veccf[2];\n veccf[0]=vecf[0]-vecc[0]; veccf[1]=vecf[1]-vecc[1];\n\n //Calculate the necessary dot products\n double cbdotcf;\n cbdotcf=veccb[0]*veccf[0]+veccb[1]*veccf[1];\n double abdotaf;\n abdotaf=vecab[0]*vecaf[0]+vecab[1]*vecaf[1];\n double coscbcf = cbdotcf/sqrt(veccb[0]*veccb[0]+veccb[1]*veccb[1])\n /sqrt(veccf[0]*veccf[0]+veccf[1]*veccf[1]);\n double cosabaf = abdotaf/sqrt(vecab[0]*vecab[0]+vecab[1]*vecab[1])\n /sqrt(vecaf[0]*vecaf[0]+vecaf[1]*vecaf[1]);\n // Print Results\n // %lf is the format specifier for double %l.15 is for 15 digits to the right\n // That amount of precision is consistant with the constant PI as a double float\n printf("Regular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \\n");\n printf("Double: acos(-1.0) = %.15lf \\n",acos(-1.0));\n printf("Constant 3.14159265358979323846 = %.15lf \\n",3.14159265358979323846);\n printf("Double: acos(-1.0)/180.0 = %.15lf \\n",acos(-1.0)/180.0);\n printf("Double: 3.14159265358979323846/180.0 = %.15lf \\n",3.14159265358979323846/180.0);\n printf("Double: vec cb dot vec cf %0.15lf\\n", cbdotcf);\n printf("Double: vec ab dot vec af %0.15lf\\n", abdotaf);\n printf("Double: coscbcf = %.15lf and cbcf= %0.15lf Degrees\\n",coscbcf,\n 180.0/acos(-1.0)*acos(coscbcf));\n printf("Double: cosabaf = %.15lf and abaf= %0.15lf Degrees\\n",cosabaf,\n 180.0/acos(-1.0)*acos(cosabaf));\n return 0;\n}\n\n", "question_id": 45523, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "I am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:\n\n\n\n\nHow can the Referenced Regular Heptagon inscribed within a Unit Circle, with its center coinciding, be drawn using PostScript Programming Language? (https://scicomp.stackexchange.com/questions/45518/how-can-the-referenced-regular-heptagon-inscribed-within-a-unit-circle-with-its)\n\n\n\n\n[image: Image of the Regular Heptagon; source: https://i.sstatic.net/z1YPOvX5.png] (https://i.sstatic.net/z1YPOvX5.png)\n\n\n\n\nI tried using double precision floating numbers to eliminate numerical resolution errors as the problem. Also with the Postscript Programming Language Resulting Figure, the angles $\\angle{BCV}$ and $\\angle{BAF}$ seem very nearly to be $90^{\\circ}$. But from my C program, I am getting the following result that does not make any sense:\n\n\n\n\nDouble: acos(-1.0) 3.141592653589793 \nDouble: vec cb dot vec cf 0.376510198141266\nDouble: vec ab dot vec af 0.611260466978158\nDouble: coscbcf = 0.433883739117558 and cbcf= 64.285714285714292 Degrees\nDouble: cosabaf = 0.900968867902419 and abaf= 25.714285714285726 Degrees\n\n\n\n\n\nThe Question: Where Are my C calculations Going Wrong?\n\n\n\n\nHow can I debug the C program to arrive at reasonable values for the calculated angles?\n\n\n\n\nUpdate: Answer Calculated, but Angles $\\angle BCF$ and\n$\\angle BAF$ are equal, but not $90^{\\circ}$\n\n\n\n\nThe source code was updated taking the suggestions from Reinderien's answer. After that, it yields similar answers to: \"Figure. Regular Heptagon Image taken from a Math Stack Exchange Question\", shown below. The problem is that questioner was assuming that angle\n$\\angle BCF=90^{\\circ}$ and that $\\angle BCF \\ne \\angle BAF$ when in actuality $\\angle BCF=\\angle BAF = 88.562883841784526^{\\circ}$.\n\n\n\n\nI am very thankful for Reinderien's answer, and I am now giving him an upvote and check mark. For reference, the newest output from my latest version of the C code is here, which is entirely consistent with his except with more decimal places of precision. Note: the C programming language, when properly used, has a history of being used for very important scientific calculations, including for a Journal Contribution that I made in 1991. In any case the newest results are below:\n\n\n\n\nRegular Heptagon 7 Equally Sided Figure Long Calculations to 15 significat digits: \nDouble: acos(-1.0) = 3.141592653589793 \nConstant 3.14159265358979323846 = 3.141592653589793 \nDouble: acos(-1.0)/180.0 = 0.017453292519943 \nDouble: 3.14159265358979323846/180.0 = 0.017453292519943 \nDouble: vec cb dot vec cf 0.037286231168214\nDouble: vec ab dot vec af 0.037286231168214\nDouble: coscbcf = 0.025079778772834 and cbcf= 88.562883841784526 Degrees\nDouble: cosabaf = 0.025079778772834 and abaf= 88.562883841784526 Degrees\n\n\n\n\n\nI was hoping that the angles would turn out somewhat similar to the figure from the below figure from the Stack Exchange Math Figure. And the actual results are similar, but computationally different than the premise in that question about the right angle drawn in the petitioner's figure. That is because the petitioner's figure is incorrect, as indeed there is no right angle at the top right as how he had drawn it.\n\n\n\n\n\n\n\nFrom the question \"What could be this unknown angle in this regular\nheptagon?\" (https://math.stackexchange.com/questions/5146710/what-could-be-this-unknown-angle-in-this-regular-heptagon/5146818#5146818)\n\n\n\n\nThere is the image drawn of a Regular Heptagon:\n\n\n\n\n\n\n\n[image: Regular Heptagon Image taken from a Math Stack Exchange Question; source: https://i.sstatic.net/JpG0VRI2.jpg] (https://i.sstatic.net/JpG0VRI2.jpg) \nFigure. Regular Heptagon Image taken from a\nMath Stack Exchange Question\n\n\n\n\n\n\n\n\n\n\n\nAppendix: C Programming Language Source Code to Calculate Angles for a Regular Heptagon\n\n\n\n\nOn the site: https://www.onlinegdb.com/online_c_compiler (https://www.onlinegdb.com/online_c_compiler)\n\n\n\n\n#include I'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for $f = 1 - 2x$.
\nHere is an example code which solves $(\\nabla u, v) = (1 - 2 x,v)$ with $u(1) = 0$ symbolically. It uses a second order H1 Lagrange space.
\nimport sympy\nimport math\n\nxi = sympy.Symbol("xi")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n math.prod(\n [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n )\n for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n [\n [\n sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n for j in range(len(nodes))\n ]\n for i in range(len(nodes))\n ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n A[\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n ] += Aelem\n\nx = sympy.Symbol("x")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n for j in range(len(nodes)):\n\n b[(len(nodes) - 1) * i + j, 0] += (\n sympy.integrate(\n basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n )\n * detJ\n )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n\n\nHere are a few finite element specific resources:
\nFor how to analyze the general stability of numerical discretizations:
\nI'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for $f = 1 - 2x$.
\nHere is an example code which solves $(\\nabla u, v) = (1 - 2 x,v)$ with $u(1) = 0$ symbolically. It uses a second order H1 Lagrange space.
\nimport sympy\nimport math\n\nxi = sympy.Symbol("xi")\nL = sympy.Rational(1, 1)\nnodes = [sympy.Rational(-1, 1), sympy.Rational(0, 1), sympy.Rational(1, 1)]\nxmin = sympy.Rational(0, 1)\nxmax = L\nnelems = 5\ndx = (xmax - xmin) / nelems\ndetJ = dx / 2\nbasis = [\n math.prod(\n [(xi - nodes[j]) / (nodes[j] - nodes[i]) for j in range(len(nodes)) if j != i]\n )\n for i in range(len(nodes))\n]\nAelem = sympy.Matrix(\n [\n [\n sympy.integrate(basis[i] * sympy.diff(basis[j], xi), (xi, -1, 1))\n for j in range(len(nodes))\n ]\n for i in range(len(nodes))\n ]\n)\nndofs = (len(nodes) - 1) * nelems + 1\nA = sympy.zeros(ndofs, ndofs)\nfor i in range(nelems):\n A[\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n (len(nodes) - 1) * i : (len(nodes) - 1) * (i + 1) + 1,\n ] += Aelem\n\nx = sympy.Symbol("x")\nf = 1 - 2 * x\nb = sympy.zeros(ndofs, 1)\n\nfor i in range(nelems):\n for j in range(len(nodes)):\n\n b[(len(nodes) - 1) * i + j, 0] += (\n sympy.integrate(\n basis[j] * f.subs(x, (xi + 1) * detJ + xmin + dx * i), (xi, -1, 1)\n )\n * detJ\n )\n\n# BC\nA[-1, :] *= 0\nA[-1, -1] = 1\nb[-1, 0] = 0\n\nsol = A.inv() @ b\n\n\nHere are a few finite element specific resources:
\nFor how to analyze the general stability of numerical discretizations:
\nI need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled "Finite Element Method", so I'll assume an FEM book will cover it, but do any of them also go over how to obtain this form for various differential equations of various orders? The reason I need something that covers constructing these forms comes from my attempt at solving a first-order ODE from its Galerkin, however the results were unstable. I tried the following first-order ODE:\n$$\\frac{du}{dx} = f(x) \\ \\ \\ \\ 0\\le x \\le L \\\\ u(L) = 0.$$\nFrom my PDEs textbook, I learned to find the Galerkin by convoluting both sides with a test function $v$\n$$\\int_0^L v\\frac{du}{dx}dx = \\int_0^L fv dx.$$\nHowever, testing this form -- using Fenics on a 1D mesh (interval) from 0 to L -- resulted in infinity everywhere, meaning this form is unstable. So, a different variational form that is stable needs to be found, and I do not know how to derive one outside of simply convoluting with $v$.
\nWould a topic like finding variational/weak/Galerkin forms for various differential equations like 1st-order problems be covered in an introductory book on finite element methods? Any recommendations?
\nEdit: commented code provided below for example $f(x) = 1-2x$, and boundary condition $u(L) = 0$. Exact solution is $u = x(1-x)$. Image of solution values contained in solution array obtained by code is also provided
\nfrom dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = "Lagrange" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure("dx", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = "preonly" # Preconditioning Matrix Option\nsolver_type = "lu" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix="first_order_ODE", bcs = [bc], petsc_options={"ksp_type": ksp_type, "pc_type": solver_type})\nu_sol = problem.solve()\n\n\nwe can see the solution is infinity at all node values of the functionspace.
\n", "question_id": 45530, "question_license": "CC BY-SA 4.0", "question_score": 4, "question_text": "I need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled \"Finite Element Method\", so I'll assume an FEM book will cover it, but do any of them also go over how to obtain this form for various differential equations of various orders? The reason I need something that covers constructing these forms comes from my attempt at solving a first-order ODE from its Galerkin, however the results were unstable. I tried the following first-order ODE:\n$$\\frac{du}{dx} = f(x) \\ \\ \\ \\ 0\\le x \\le L \\\\ u(L) = 0.$$\nFrom my PDEs textbook, I learned to find the Galerkin by convoluting both sides with a test function $v$\n$$\\int_0^L v\\frac{du}{dx}dx = \\int_0^L fv dx.$$\nHowever, testing this form -- using Fenics on a 1D mesh (interval) from 0 to L -- resulted in infinity everywhere, meaning this form is unstable. So, a different variational form that is stable needs to be found, and I do not know how to derive one outside of simply convoluting with $v$.\n\n\n\n\nWould a topic like finding variational/weak/Galerkin forms for various differential equations like 1st-order problems be covered in an introductory book on finite element methods? Any recommendations?\n\n\n\n\n\n\n\nEdit: commented code provided below for example $f(x) = 1-2x$, and boundary condition $u(L) = 0$. Exact solution is $u = x(1-x)$. Image of solution values contained in solution array obtained by code is also provided\n\n\n\n\nfrom dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at x = 1\nmesh_1D = df.mesh.create_interval(comm, nx=nx, points = [start_point,L]) #1D line segment\nx = ufl.SpatialCoordinate(mesh_1D)[0] # x and y coordinates. Symbolic expressions \n\n\n# --- Define Functionspace ---\nfamily = \"Lagrange\" # The type of functionspace used\ndegree = 2 # The degree of the polynomial used to interpolate data to\nV1D = df.fem.functionspace(mesh_1D, (family, degree))\n\n\n# --- Define Galerkin of 1st-order ODE ---\n# ODE: du/dx = 1-2x; u(1) = 0\n# Galerkin: int_0^L [v du/dx] dx = int_0^L [fv] dx\nu = ufl.TrialFunction(V1D) \nv = ufl.TestFunction(V1D)\nf = 1-2*x\n\n# bilinear term: a(u,v) = int_0^L [v du/dx] dx\ndx = ufl.Measure(\"dx\", mesh_1D) #defines differential along mesh\na = ufl.inner(v,u.dx(0)) * dx\n# Linear term: L(u) = int_0^L [fv] dx\nL_ = ufl.inner(f,v) * dx\n# boundary condition: u(0) = 0\nbc = df.fem.dirichletbc(value=0.0, dofs = df.fem.locate_dofs_geometrical(V1D, lambda x: np.isclose(x[0],L)), V = V1D) # Assigns dirichlet values to degree of freedom at x = L\n\n\n# --- Solve ---\nksp_type = \"preonly\" # Preconditioning Matrix Option\nsolver_type = \"lu\" #LU factorization (a direct solver)\n\nproblem = LinearProblem(a = a, L = L_, petsc_options_prefix=\"first_order_ODE\", bcs = [bc], petsc_options={\"ksp_type\": ksp_type, \"pc_type\": solver_type})\nu_sol = problem.solve()\n\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/8M1U5hQT.png] (https://i.sstatic.net/8M1U5hQT.png)\n\n\n\n\nwe can see the solution is infinity at all node values of the functionspace.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Researcher R", "profile_url": "https://scicomp.stackexchange.com/users/53321/researcher-r", "user_type": "registered"}, "created_at": "2026-08-30T03:46:19+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "8A694B8D-C740-489D-AB57-AFCBA245C49D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/8A694B8D-C740-489D-AB57-AFCBA245C49D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Researcher R", "profile_url": "https://scicomp.stackexchange.com/users/53321/researcher-r", "user_type": "registered"}, "created_at": "2026-08-30T23:41:50+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "AAFE31F6-C5AA-4701-A6C2-3D86B0B411A6", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/AAFE31F6-C5AA-4701-A6C2-3D86B0B411A6/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2026-08-31T23:54:34+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "74C46D09-5EAB-4E08-B7C7-43D0DFCFBBE8", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://scicomp.stackexchange.com/revisions/74C46D09-5EAB-4E08-B7C7-43D0DFCFBBE8/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45530/are-there-any-resources-which-cover-finding-stable-weak-forms-to-1st-order-diffe", "split": "train", "split_group": "38a212b64b791c4e49567a55cdb42224036c90a0d764070d65bb8936af2fe336", "tags": ["finite-element", "reference-request", "least-squares", "galerkin", "weak-solution"], "thread_id": "scicomp:45530", "title": "Are there any resources which cover finding stable weak forms to 1st-order differential equations"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "k_max = 250\nphi_0 = +0.0\nstd_dev = 0.05\n\nu_0_rand = np.random.randn(N,N)*std_dev + phi_0\nu_0_filter = u_0_rand # Please ignore the names of the variable\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45532, "sha256": "f40592e672522d5411963bc86e0bbe1592feb49f5dada74f8814a3c3b9b2c352", "source_url": "https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"}, {"block_index": 1, "code_text": "delta_x = 0.75\nhalf_length = delta_x * N/2\n\n#Grid Construction\ngrid_1d = np.linspace(-half_length,half_length,N, endpoint=False)\nX, Y = np.meshgrid(grid_1d, grid_1d, indexing='ij')\ngrid = np.stack((X, Y))\n\n#Frequency Grid\nfreq_1d = np.fft.fftfreq(N, delta_x) * 2 * np.pi \nfreq_X, freq_Y = np.meshgrid(freq_1d, freq_1d, indexing='ij')\nfreq_grid = np.stack((freq_X, freq_Y))\n\n# Create mask to zero out frequencies\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nif dealiasing_mask:\n k_cutoff = (N / 4) * (2*np.pi / (N*delta_x))\n freq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\nelse:\n freq_mask = np.ones(k_x.shape)\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45532, "sha256": "ec379444a6721a5231aebe08d7e169930c9add7bfbb99a32c99e4239ddc360ea", "source_url": "https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"}, {"block_index": 3, "code_text": "def radial_average(image, center):\n \n assert image.shape[-2] == image.shape[-1], \"The image is not a square matrix\"\n \n y, x = np.indices(image.shape)\n cy, cx = center\n\n r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)\n \n mask = (r < (image.shape[-1]//2 - 1))\n \n radial_sum = np.bincount(\n r[mask].ravel(),\n weights=image[mask].ravel()\n )\n\n radial_count = np.bincount(r[mask].ravel())\n\n radial_average = radial_sum / radial_count\n\n return np.arange(len(radial_average)), radial_average\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45532, "sha256": "9f3ce8c6b10cd45e7f2b7ca3d87f386103b6b4a5eaa910551cb1fe652de70560", "source_url": "https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"}, {"block_index": 4, "code_text": "# Simulation Controls\ndelta_t = 0.5\ntimesteps = 5000\nk_2 = k_x**2 + k_y**2\nzero_freq_masking = False\nhardening = False\n\n# History\nt_spacing = 20\nu_history = []\nfft_history = []\nrec_time_hist = []\navg_domain_size = []\nradial_S_k_history = []\nradial_corr_history = []\n\n# Initialize\nfft = np.fft.fft2(u_0_filter.real)\nfor t in tqdm(range(timesteps)):\n \n u_t_masked = np.fft.ifft2(fft * freq_mask).real\n cubed = u_t_masked ** 3\n cubed_fft = np.fft.fft2(cubed) * freq_mask\n \n \n # IMEX Update Step\n num = (fft - M*beta*k_2*delta_t*cubed_fft) + noise_increment\n denm = 1 + M*delta_t*k_2*(alpha - gamma*k_2)\n fft = num/denm\n \n #Projection to real space\n u_t = np.fft.ifft2(fft).real\n fft = np.fft.fft2(u_t)\n \n # History update\n if t%t_spacing == 0:\n \n u_t_snap = u_t.copy()\n if hardening:\n u_t_snap[u_t_snap>0] = +1\n u_t_snap[u_t_snap<0] = -1\n fft_snap = np.fft.fft2(u_t_snap)\n else:\n fft_snap = fft.copy()\n \n fft_history.append(fft_snap)\n u_history.append(u_t_snap.real)\n rec_time_hist.append((t+1)*delta_t)\n \n # Domain Size calculation\n S_k = np.abs(fft_snap)**2 / N**2\n shifted_S_k = np.fft.fftshift(S_k)\n \n r_val ,radial_S = radial_average(shifted_S_k, center=(N//2,N//2))\n radial_S_k_history.append(radial_S)\n \n # Converting the bin indices to frequency\n k_val = r_val * 2 * np.pi / (N * delta_x)\n if zero_freq_masking:\n mask = (k_val>0)\n avg_k = np.sum(radial_S[mask] * k_val[mask]) / np.sum(radial_S[mask])\n else:\n avg_k = np.sum(radial_S * k_val) / np.sum(radial_S)\n domain_size = np.pi / avg_k\n avg_domain_size.append(domain_size)\n \n # Azimuthally averaged correlation function\n corr_2d = np.fft.fftshift(np.fft.ifft2(S_k))\n r_val , radial_corr = radial_average(corr_2d.real, center=(N//2,N//2))\n radial_corr_history.append(radial_corr)\n \n# Converting the r_val from indices units to real units\nr_val = delta_x*r_val\n \nu_final_spectral = np.fft.ifft2(fft).real\nu_history = np.array(u_history)\nfft_history = np.array(fft_history)\n\n# Plotting \nfig, ax = plt.subplots(1, 2, figsize=(9, 4), constrained_layout=True)\nlevels = np.linspace(-1.5, 1.5, 100)\nim1 = ax[0].contourf(X, Y, u_0_filter.real , levels=levels, cmap=\"bwr\")\nim2 = ax[1].contourf(X, Y, u_final_spectral, levels=levels, cmap=\"bwr\")\nax[0].set_title(\"Initial State\")\nax[1].set_title(\"IMEX Spectral Result\")\nfig.colorbar(im2, ax=ax, ticks=[-1.5, 0, 1.5])\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45532, "sha256": "36883faddc429ff294899e4ad411886dc0693ea138fe351621b56d8d314abd2f", "source_url": "https://scicomp.stackexchange.com/questions/45532/oscillations-weird-patterns-in-cahn-hilliard-imex-solver"}], "other_answers": [], "product": "code_qa", "question": "I am trying to simulate the cahn-hilliard system using a psuedospectral solver. I am using the following scheme:\n$$\\widetilde{\\phi}_{k}^{\\,t+1}=\\frac{\\widetilde{\\phi}_{k}^{\\,t}-M\\beta k^2\\Delta\\widetilde{\\phi_{k}^{\\,3}}^{\\,t}}{1+M\\Delta k^2\\left(\\alpha-\\gamma k^2\\right)}$$ for the equation $$ \\frac{d\\phi}{\\mathrm{d}t}\\;=\\;M\\;\\nabla^2\\left(\\alpha\\cdot\\phi\\;+\\;\\beta\\cdot\\phi^3\\;+\\;\\gamma\\cdot\\nabla^2\\phi\\right)\n$$\nwhere $\\triangle$ is the time spacing.\nThe code is as follows:\n\n\n\n\nk_max = 250\nphi_0 = +0.0\nstd_dev = 0.05\n\nu_0_rand = np.random.randn(N,N)*std_dev + phi_0\nu_0_filter = u_0_rand # Please ignore the names of the variable\n\n\n\n\n\ndelta_x = 0.75\nhalf_length = delta_x * N/2\n\n#Grid Construction\ngrid_1d = np.linspace(-half_length,half_length,N, endpoint=False)\nX, Y = np.meshgrid(grid_1d, grid_1d, indexing='ij')\ngrid = np.stack((X, Y))\n\n#Frequency Grid\nfreq_1d = np.fft.fftfreq(N, delta_x) * 2 * np.pi \nfreq_X, freq_Y = np.meshgrid(freq_1d, freq_1d, indexing='ij')\nfreq_grid = np.stack((freq_X, freq_Y))\n\n# Create mask to zero out frequencies\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nif dealiasing_mask:\n k_cutoff = (N / 4) * (2*np.pi / (N*delta_x))\n freq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\nelse:\n freq_mask = np.ones(k_x.shape)\n\n\n\n\n\n# d(phi)/ dt = M lap( alpha*phi + beta*phi^3 + gamma*lap(phi))\nalpha = -1\nbeta = 1\ngamma = -1\nM = 1\nk_b = 1\n\n\n\n\n\ndef radial_average(image, center):\n \n assert image.shape[-2] == image.shape[-1], \"The image is not a square matrix\"\n \n y, x = np.indices(image.shape)\n cy, cx = center\n\n r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)\n \n mask = (r < (image.shape[-1]//2 - 1))\n \n radial_sum = np.bincount(\n r[mask].ravel(),\n weights=image[mask].ravel()\n )\n\n radial_count = np.bincount(r[mask].ravel())\n\n radial_average = radial_sum / radial_count\n\n return np.arange(len(radial_average)), radial_average\n\n\n\n\n\n# Simulation Controls\ndelta_t = 0.5\ntimesteps = 5000\nk_2 = k_x**2 + k_y**2\nzero_freq_masking = False\nhardening = False\n\n# History\nt_spacing = 20\nu_history = []\nfft_history = []\nrec_time_hist = []\navg_domain_size = []\nradial_S_k_history = []\nradial_corr_history = []\n\n# Initialize\nfft = np.fft.fft2(u_0_filter.real)\nfor t in tqdm(range(timesteps)):\n \n u_t_masked = np.fft.ifft2(fft * freq_mask).real\n cubed = u_t_masked ** 3\n cubed_fft = np.fft.fft2(cubed) * freq_mask\n \n \n # IMEX Update Step\n num = (fft - M*beta*k_2*delta_t*cubed_fft) + noise_increment\n denm = 1 + M*delta_t*k_2*(alpha - gamma*k_2)\n fft = num/denm\n \n #Projection to real space\n u_t = np.fft.ifft2(fft).real\n fft = np.fft.fft2(u_t)\n \n # History update\n if t%t_spacing == 0:\n \n u_t_snap = u_t.copy()\n if hardening:\n u_t_snap[u_t_snap>0] = +1\n u_t_snap[u_t_snap<0] = -1\n fft_snap = np.fft.fft2(u_t_snap)\n else:\n fft_snap = fft.copy()\n \n fft_history.append(fft_snap)\n u_history.append(u_t_snap.real)\n rec_time_hist.append((t+1)*delta_t)\n \n # Domain Size calculation\n S_k = np.abs(fft_snap)**2 / N**2\n shifted_S_k = np.fft.fftshift(S_k)\n \n r_val ,radial_S = radial_average(shifted_S_k, center=(N//2,N//2))\n radial_S_k_history.append(radial_S)\n \n # Converting the bin indices to frequency\n k_val = r_val * 2 * np.pi / (N * delta_x)\n if zero_freq_masking:\n mask = (k_val>0)\n avg_k = np.sum(radial_S[mask] * k_val[mask]) / np.sum(radial_S[mask])\n else:\n avg_k = np.sum(radial_S * k_val) / np.sum(radial_S)\n domain_size = np.pi / avg_k\n avg_domain_size.append(domain_size)\n \n # Azimuthally averaged correlation function\n corr_2d = np.fft.fftshift(np.fft.ifft2(S_k))\n r_val , radial_corr = radial_average(corr_2d.real, center=(N//2,N//2))\n radial_corr_history.append(radial_corr)\n \n# Converting the r_val from indices units to real units\nr_val = delta_x*r_val\n \nu_final_spectral = np.fft.ifft2(fft).real\nu_history = np.array(u_history)\nfft_history = np.array(fft_history)\n\n# Plotting \nfig, ax = plt.subplots(1, 2, figsize=(9, 4), constrained_layout=True)\nlevels = np.linspace(-1.5, 1.5, 100)\nim1 = ax[0].contourf(X, Y, u_0_filter.real , levels=levels, cmap=\"bwr\")\nim2 = ax[1].contourf(X, Y, u_final_spectral, levels=levels, cmap=\"bwr\")\nax[0].set_title(\"Initial State\")\nax[1].set_title(\"IMEX Spectral Result\")\nfig.colorbar(im2, ax=ax, ticks=[-1.5, 0, 1.5])\nplt.show()\n\n\n\n\n\nThe projection part to real space is done to improve stability. I am also introducing hardening to remove finite interfaces so that one can clearly observe the $k^{-3}$ porod's tail decay.\n\n\n\n\nThe following results are obtained without hardening:\nFirst, I have turned on the dealiasing mask. This gives me the following solution:\n[image: Solution with dealiasing mask; source: https://i.sstatic.net/12z0CS3L.png] (https://i.sstatic.net/12z0CS3L.png)\n\n\n\n\nThe domain growth is also well obtained and follows the theoretical 1/3 law.\n[image: domain growth; source: https://i.sstatic.net/655HZFjB.png] (https://i.sstatic.net/655HZFjB.png)\n\n\n\n\nThe problem comes in the structure factor collapse:\n[image: Structure factor collapse; source: https://i.sstatic.net/xVZy72zi.png] (https://i.sstatic.net/xVZy72zi.png)\n\n\n\n\nDue to dealiasing, the high frequency modes are getting supressed completely as the $u^3$ term is not contributing anything. Also, the bigger problem is the oscillations present in the solutions. The faint waves present in the solution. I am suspecting the abrupt cutoff to cause this problem.\n\n\n\n\nNext, I tried with no dealiasing filter. This time the problem of structure factor is removed because contributions of the $u^3$ term is present.\n[image: Structure factor collapse; source: https://i.sstatic.net/TMxN8G8J.png] (https://i.sstatic.net/TMxN8G8J.png)\n\n\n\n\nWith hardening the slope also comes around to -3. But the problem of oscillation still remains.\n[image: Oscillations in the solution; source: https://i.sstatic.net/3KkMyklD.png] (https://i.sstatic.net/3KkMyklD.png)\n\n\n\n\nI have also plotted the regions which are outside the [-1,1] value range.\n[image: Mass pileup; source: https://i.sstatic.net/65RiIZsB.png] (https://i.sstatic.net/65RiIZsB.png)\n\n\n\n\nThere is clear mass pileup which was also present in the case with dealiasing filter. My best guess is the aliasing is causing some of the oscillations but I have no clue why there is mass pileup (However, the relative magnitude is small. The maximum mass is roughly +1.15 and minimum mass is -1.15).\n\n\n\n\nThe main doubts are:\n\n\n\n\n\nWhy is there mass pileup?\n\n\n\n\nWhy is there oscillations in both cases?\n\n\n\n\nHow to prevent this? Is it a common problem in psuedospectral implementations? I have seen few PREs and PRRs where they have used psuedospectral solvers with dealiasing filter but none has reported such problems. Is it only specific to my implementation, has someone ever faced this issue?", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45532", "selected_answer": {"answer_html": "Even when using an IMEX scheme, you have to consider that the explicit part still imposes a stability restriction on $\\Delta t$. In your implementation, you have to consider something like:
\n$$\n\\Delta t \\le \\frac{2\\,\\mathrm{CFL}}{3M\\beta k_{\\max}^2}, \\quad \\text{with} \\quad \\text{CFL}=1.\n$$
\nA larger CFL number permits a larger time step and reduces the computational cost, but choosing it too large (CFL>1) can lead to numerical instability.
\nExample: left stable, right unstable
\n\n", "answer_id": 45536, "answer_text": "Even when using an IMEX scheme, you have to consider that the explicit part still imposes a stability restriction on $\\Delta t$. In your implementation, you have to consider something like:\n\n\n\n\n$$\n\\Delta t \\le \\frac{2\\,\\mathrm{CFL}}{3M\\beta k_{\\max}^2}, \\quad \\text{with} \\quad \\text{CFL}=1.\n$$\n\n\n\n\nA larger CFL number permits a larger time step and reduces the computational cost, but choosing it too large (CFL>1) can lead to numerical instability.\n\n\n\n\nExample: left stable, right unstable\n\n\n\n\n[image: CFL < 1; source: https://i.sstatic.net/oJcmKuaA.gif] (https://i.sstatic.net/oJcmKuaA.gif) [image: CFL > 1; source: https://i.sstatic.net/jj2j0EFd.gif] (https://i.sstatic.net/jj2j0EFd.gif)", "answer_url": "https://scicomp.stackexchange.com/a/45536", "author": "ConvexHull", "author_url": "https://scicomp.stackexchange.com/users/36512/convexhull", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-05T20:38:57+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": 45532, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ConvexHull", "profile_url": "https://scicomp.stackexchange.com/users/36512/convexhull", "user_type": "registered"}, "created_at": "2026-09-05T20:38:57+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "FAFB8920-4950-4612-A439-2940A54D031D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/FAFB8920-4950-4612-A439-2940A54D031D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ConvexHull", "profile_url": "https://scicomp.stackexchange.com/users/36512/convexhull", "user_type": "registered"}, "created_at": "2026-09-05T20:49:24+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "A2D91D1E-0B9E-429A-85F4-6DAD1D377E64", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A2D91D1E-0B9E-429A-85F4-6DAD1D377E64/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ConvexHull", "profile_url": "https://scicomp.stackexchange.com/users/36512/convexhull", "user_type": "registered"}, "created_at": "2026-09-05T21:02:30+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "CFDD8DBF-0E0B-4760-A1AF-0EB8A794BDA9", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/CFDD8DBF-0E0B-4760-A1AF-0EB8A794BDA9/view-source"}], "score": 5, "updated_at": "2026-09-05T21:02:30+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Even when using an IMEX scheme, you have to consider that the explicit part still imposes a stability restriction on $\\Delta t$. In your implementation, you have to consider something like:
\n$$\n\\Delta t \\le \\frac{2\\,\\mathrm{CFL}}{3M\\beta k_{\\max}^2}, \\quad \\text{with} \\quad \\text{CFL}=1.\n$$
\nA larger CFL number permits a larger time step and reduces the computational cost, but choosing it too large (CFL>1) can lead to numerical instability.
\nExample: left stable, right unstable
\n\n", "answer_id": 45536, "answer_text": "Even when using an IMEX scheme, you have to consider that the explicit part still imposes a stability restriction on $\\Delta t$. In your implementation, you have to consider something like:\n\n\n\n\n$$\n\\Delta t \\le \\frac{2\\,\\mathrm{CFL}}{3M\\beta k_{\\max}^2}, \\quad \\text{with} \\quad \\text{CFL}=1.\n$$\n\n\n\n\nA larger CFL number permits a larger time step and reduces the computational cost, but choosing it too large (CFL>1) can lead to numerical instability.\n\n\n\n\nExample: left stable, right unstable\n\n\n\n\n[image: CFL < 1; source: https://i.sstatic.net/oJcmKuaA.gif] (https://i.sstatic.net/oJcmKuaA.gif) [image: CFL > 1; source: https://i.sstatic.net/jj2j0EFd.gif] (https://i.sstatic.net/jj2j0EFd.gif)", "answer_url": "https://scicomp.stackexchange.com/a/45536", "author": "ConvexHull", "author_url": "https://scicomp.stackexchange.com/users/36512/convexhull", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2026-09-05T20:38:57+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": 45532, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ConvexHull", "profile_url": "https://scicomp.stackexchange.com/users/36512/convexhull", "user_type": "registered"}, "created_at": "2026-09-05T20:38:57+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "FAFB8920-4950-4612-A439-2940A54D031D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/FAFB8920-4950-4612-A439-2940A54D031D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ConvexHull", "profile_url": "https://scicomp.stackexchange.com/users/36512/convexhull", "user_type": "registered"}, "created_at": "2026-09-05T20:49:24+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "A2D91D1E-0B9E-429A-85F4-6DAD1D377E64", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/A2D91D1E-0B9E-429A-85F4-6DAD1D377E64/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "ConvexHull", "profile_url": "https://scicomp.stackexchange.com/users/36512/convexhull", "user_type": "registered"}, "created_at": "2026-09-05T21:02:30+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "CFDD8DBF-0E0B-4760-A1AF-0EB8A794BDA9", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/CFDD8DBF-0E0B-4760-A1AF-0EB8A794BDA9/view-source"}], "score": 5, "updated_at": "2026-09-05T21:02:30+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/12z0CS3L.png", "https://i.sstatic.net/3KkMyklD.png", "https://i.sstatic.net/655HZFjB.png", "https://i.sstatic.net/65RiIZsB.png", "https://i.sstatic.net/TMxN8G8J.png", "https://i.sstatic.net/jj2j0EFd.gif", "https://i.sstatic.net/oJcmKuaA.gif", "https://i.sstatic.net/xVZy72zi.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": "Manav Jalan", "question_author_url": "https://scicomp.stackexchange.com/users/57116/manav-jalan", "question_author_user_type": "registered", "question_created_at": "2026-09-02T16:06:42+00:00", "question_html": "I am trying to simulate the cahn-hilliard system using a psuedospectral solver. I am using the following scheme:\n$$\\widetilde{\\phi}_{k}^{\\,t+1}=\\frac{\\widetilde{\\phi}_{k}^{\\,t}-M\\beta k^2\\Delta\\widetilde{\\phi_{k}^{\\,3}}^{\\,t}}{1+M\\Delta k^2\\left(\\alpha-\\gamma k^2\\right)}$$ for the equation $$ \\frac{d\\phi}{\\mathrm{d}t}\\;=\\;M\\;\\nabla^2\\left(\\alpha\\cdot\\phi\\;+\\;\\beta\\cdot\\phi^3\\;+\\;\\gamma\\cdot\\nabla^2\\phi\\right)\n$$\nwhere $\\triangle$ is the time spacing.\nThe code is as follows:
\nk_max = 250\nphi_0 = +0.0\nstd_dev = 0.05\n\nu_0_rand = np.random.randn(N,N)*std_dev + phi_0\nu_0_filter = u_0_rand # Please ignore the names of the variable\n\ndelta_x = 0.75\nhalf_length = delta_x * N/2\n\n#Grid Construction\ngrid_1d = np.linspace(-half_length,half_length,N, endpoint=False)\nX, Y = np.meshgrid(grid_1d, grid_1d, indexing='ij')\ngrid = np.stack((X, Y))\n\n#Frequency Grid\nfreq_1d = np.fft.fftfreq(N, delta_x) * 2 * np.pi \nfreq_X, freq_Y = np.meshgrid(freq_1d, freq_1d, indexing='ij')\nfreq_grid = np.stack((freq_X, freq_Y))\n\n# Create mask to zero out frequencies\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nif dealiasing_mask:\n k_cutoff = (N / 4) * (2*np.pi / (N*delta_x))\n freq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\nelse:\n freq_mask = np.ones(k_x.shape)\n\n# d(phi)/ dt = M lap( alpha*phi + beta*phi^3 + gamma*lap(phi))\nalpha = -1\nbeta = 1\ngamma = -1\nM = 1\nk_b = 1\n\ndef radial_average(image, center):\n \n assert image.shape[-2] == image.shape[-1], "The image is not a square matrix"\n \n y, x = np.indices(image.shape)\n cy, cx = center\n\n r = np.sqrt((x - cx)**2 + (y - cy)**2).astype(int)\n \n mask = (r < (image.shape[-1]//2 - 1))\n \n radial_sum = np.bincount(\n r[mask].ravel(),\n weights=image[mask].ravel()\n )\n\n radial_count = np.bincount(r[mask].ravel())\n\n radial_average = radial_sum / radial_count\n\n return np.arange(len(radial_average)), radial_average\n\n# Simulation Controls\ndelta_t = 0.5\ntimesteps = 5000\nk_2 = k_x**2 + k_y**2\nzero_freq_masking = False\nhardening = False\n\n# History\nt_spacing = 20\nu_history = []\nfft_history = []\nrec_time_hist = []\navg_domain_size = []\nradial_S_k_history = []\nradial_corr_history = []\n\n# Initialize\nfft = np.fft.fft2(u_0_filter.real)\nfor t in tqdm(range(timesteps)):\n \n u_t_masked = np.fft.ifft2(fft * freq_mask).real\n cubed = u_t_masked ** 3\n cubed_fft = np.fft.fft2(cubed) * freq_mask\n \n \n # IMEX Update Step\n num = (fft - M*beta*k_2*delta_t*cubed_fft) + noise_increment\n denm = 1 + M*delta_t*k_2*(alpha - gamma*k_2)\n fft = num/denm\n \n #Projection to real space\n u_t = np.fft.ifft2(fft).real\n fft = np.fft.fft2(u_t)\n \n # History update\n if t%t_spacing == 0:\n \n u_t_snap = u_t.copy()\n if hardening:\n u_t_snap[u_t_snap>0] = +1\n u_t_snap[u_t_snap<0] = -1\n fft_snap = np.fft.fft2(u_t_snap)\n else:\n fft_snap = fft.copy()\n \n fft_history.append(fft_snap)\n u_history.append(u_t_snap.real)\n rec_time_hist.append((t+1)*delta_t)\n \n # Domain Size calculation\n S_k = np.abs(fft_snap)**2 / N**2\n shifted_S_k = np.fft.fftshift(S_k)\n \n r_val ,radial_S = radial_average(shifted_S_k, center=(N//2,N//2))\n radial_S_k_history.append(radial_S)\n \n # Converting the bin indices to frequency\n k_val = r_val * 2 * np.pi / (N * delta_x)\n if zero_freq_masking:\n mask = (k_val>0)\n avg_k = np.sum(radial_S[mask] * k_val[mask]) / np.sum(radial_S[mask])\n else:\n avg_k = np.sum(radial_S * k_val) / np.sum(radial_S)\n domain_size = np.pi / avg_k\n avg_domain_size.append(domain_size)\n \n # Azimuthally averaged correlation function\n corr_2d = np.fft.fftshift(np.fft.ifft2(S_k))\n r_val , radial_corr = radial_average(corr_2d.real, center=(N//2,N//2))\n radial_corr_history.append(radial_corr)\n \n# Converting the r_val from indices units to real units\nr_val = delta_x*r_val\n \nu_final_spectral = np.fft.ifft2(fft).real\nu_history = np.array(u_history)\nfft_history = np.array(fft_history)\n\n# Plotting \nfig, ax = plt.subplots(1, 2, figsize=(9, 4), constrained_layout=True)\nlevels = np.linspace(-1.5, 1.5, 100)\nim1 = ax[0].contourf(X, Y, u_0_filter.real , levels=levels, cmap="bwr")\nim2 = ax[1].contourf(X, Y, u_final_spectral, levels=levels, cmap="bwr")\nax[0].set_title("Initial State")\nax[1].set_title("IMEX Spectral Result")\nfig.colorbar(im2, ax=ax, ticks=[-1.5, 0, 1.5])\nplt.show()\n\nThe projection part to real space is done to improve stability. I am also introducing hardening to remove finite interfaces so that one can clearly observe the $k^{-3}$ porod's tail decay.
\nThe following results are obtained without hardening:\nFirst, I have turned on the dealiasing mask. This gives me the following solution:\n
The domain growth is also well obtained and follows the theoretical 1/3 law.\n
The problem comes in the structure factor collapse:\n
Due to dealiasing, the high frequency modes are getting supressed completely as the $u^3$ term is not contributing anything. Also, the bigger problem is the oscillations present in the solutions. The faint waves present in the solution. I am suspecting the abrupt cutoff to cause this problem.
\nNext, I tried with no dealiasing filter. This time the problem of structure factor is removed because contributions of the $u^3$ term is present.\n
With hardening the slope also comes around to -3. But the problem of oscillation still remains.\n
I have also plotted the regions which are outside the [-1,1] value range.\n
There is clear mass pileup which was also present in the case with dealiasing filter. My best guess is the aliasing is causing some of the oscillations but I have no clue why there is mass pileup (However, the relative magnitude is small. The maximum mass is roughly +1.15 and minimum mass is -1.15).
\nThe main doubts are:
\nThe key insight (also reflected in this comment) 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$).
\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,
\nFor small bounding box count, it's very frequent that an axis intersection is selected:
\n\nFor 90 bounding boxes, we see a non-axis intersection being selected:
\n\nOn my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.
\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()\n\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": "The key insight (also reflected in this comment) 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$).
\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,
\nFor small bounding box count, it's very frequent that an axis intersection is selected:
\n\nFor 90 bounding boxes, we see a non-axis intersection being selected:
\n\nOn my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.
\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()\n\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": "I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.
\nIs there a known algorithm for this problem?
\nThanks.
\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"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.zeros(500)\nfor i in range(500):\n somme = 0\n # print(\"t = \", i)\n for j in range(1,n+1):\n # print(\"n = \", j)\n somme+=(A/j*np.pi)*(np.sin(j*tau)*np.cos(j*i)+(1-np.cos(j*tau))*np.sin(j*i))\n f_t[i-1]= c+somme\nplt.plot(t, f_t)\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45541, "sha256": "ec8560746cd8ed8699dc2c11fc07f68d8e9a5474d7445fc7c73a4819a02e76aa", "source_url": "https://scicomp.stackexchange.com/questions/45541/fourier-serie-algorithm"}, {"block_index": 0, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45542, "sha256": "86f02ec052fe24ddab955b090bac125c5a7c6db1f2c4bd60e22e97daf6674a7f", "source_url": "https://scicomp.stackexchange.com/a/45542"}, {"block_index": 1, "code_text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45542, "sha256": "eed9b19202c4a48fe407d4b2a7b7936f04c96a4ae67364b7f3f275cc3c4d46e3", "source_url": "https://scicomp.stackexchange.com/a/45542"}, {"block_index": 2, "code_text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 45542, "sha256": "6a294b184211babd5e09b2cdf09509ad0fdf8c6c7f61af6b68eaf9c092a2d93a", "source_url": "https://scicomp.stackexchange.com/a/45542"}], "other_answers": [], "product": "code_qa", "question": "here is the Fourier series I'm trying to represent:\n\n\n\n\n$$\nf(t) = \\frac{A\\tau}{T} + \\frac{A}{\\pi}\\sum_{n=1}^{\\infty}\\frac{1}{n}\\left[\\sin(n\\omega\\tau)\\cos(n\\omega t) + \\left(1-\\cos(n\\omega\\tau)\\right)\\sin(n\\omega t)\\right]\n$$\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.zeros(500)\nfor i in range(500):\n somme = 0\n # print(\"t = \", i)\n for j in range(1,n+1):\n # print(\"n = \", j)\n somme+=(A/j*np.pi)*(np.sin(j*tau)*np.cos(j*i)+(1-np.cos(j*tau))*np.sin(j*i))\n f_t[i-1]= c+somme\nplt.plot(t, f_t)\nplt.show()\n\n\n\n\n\ncan you guys please tell me why my algorithm doesn't work properly?\nactually my teacher says I should obtain the following figure:\n\n\n\n\n[image: the correct figure according to my teacher; source: https://i.sstatic.net/QM4j9vnZ.png] (https://i.sstatic.net/QM4j9vnZ.png)\n\n\n\n\nnot the straight lines I'm obtaining with my code!! here is what I'm getting with my code:\n\n\n\n\n[image: the function I get with my code; source: https://i.sstatic.net/9Q1FTH4K.png] (https://i.sstatic.net/9Q1FTH4K.png)", "record_id": "Scientific-Code-and-Analysis-QA:scicomp:45541", "selected_answer": {"answer_html": "Assuming your math is correct, then very literally and using a broadcast sum,
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n\n\nBut as Lutz Lehmann says, you need to increase your time resolution:
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n\n\nFurther: in "real life", you would nearly never write out the Fourier series in that form. You'd use an off-the-shelf FFT implementation for efficiency:
\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()\n\n", "answer_id": 45542, "answer_text": "Assuming your math is correct, then very literally and using a broadcast sum,\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n\n\n\n\n\n[image: f(t); source: https://i.sstatic.net/YjgeAIXx.png] (https://i.sstatic.net/YjgeAIXx.png)\n\n\n\n\nBut as Lutz Lehmann says, you need to increase your time resolution:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n\n\n\n\n\n[image: f(t) hires; source: https://i.sstatic.net/Ag4Fil8J.png] (https://i.sstatic.net/Ag4Fil8J.png)\n\n\n\n\nFurther: in \"real life\", you would nearly never write out the Fourier series in that form. You'd use an off-the-shelf FFT implementation for efficiency:\n\n\n\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()", "answer_url": "https://scicomp.stackexchange.com/a/45542", "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-20T17:18:55+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": 45541, "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-20T17:18:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "62E18C62-347B-4371-A12B-7026926DDD8F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/62E18C62-347B-4371-A12B-7026926DDD8F/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-21T01:55:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DB2CC339-A8C8-44D8-816A-B9919DFBB2BE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DB2CC339-A8C8-44D8-816A-B9919DFBB2BE/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-27T18:44:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "5CA547D4-1223-44E9-9049-12894162675F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/5CA547D4-1223-44E9-9049-12894162675F/view-source"}], "score": 3, "updated_at": "2026-09-27T18:44:52+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "train", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Assuming your math is correct, then very literally and using a broadcast sum,
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n\n\nBut as Lutz Lehmann says, you need to increase your time resolution:
\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n\n\nFurther: in "real life", you would nearly never write out the Fourier series in that form. You'd use an off-the-shelf FFT implementation for efficiency:
\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()\n\n", "answer_id": 45542, "answer_text": "Assuming your math is correct, then very literally and using a broadcast sum,\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt = np.arange(1, 11)\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n*(\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\nf = A*τ/T + A/π*terms.sum(axis=0)\n\nfig, ax = plt.subplots()\nax.plot(t, f)\nax.set_xlabel('t')\nax.set_ylabel('f')\nplt.show()\n\n\n\n\n\n[image: f(t); source: https://i.sstatic.net/YjgeAIXx.png] (https://i.sstatic.net/YjgeAIXx.png)\n\n\n\n\nBut as Lutz Lehmann says, you need to increase your time resolution:\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 2*π/T\nt = np.linspace(start=0, stop=8, num=501)\nn = np.arange(1, 1 + 15)[:, np.newaxis]\nnωt = n*ω*t\nnωτ = n*ω*τ\nterms = 1/n * (\n sin(nωτ)*cos(nωt) + (1 - cos(nωτ))*sin(nωt)\n)\n\nfig, ax = plt.subplots()\nax.set_xlabel('t')\nax.set_ylabel('f')\nfor N in (1, 5, 15):\n f = A*τ/T + A/π*terms[:N+1].sum(axis=0)\n ax.plot(t, f, label=f'N={N}')\n\nax.legend()\nplt.show()\n\n\n\n\n\n[image: f(t) hires; source: https://i.sstatic.net/Ag4Fil8J.png] (https://i.sstatic.net/Ag4Fil8J.png)\n\n\n\n\nFurther: in \"real life\", you would nearly never write out the Fourier series in that form. You'd use an off-the-shelf FFT implementation for efficiency:\n\n\n\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nt = np.linspace(start=0, stop=2*np.pi, num=501)\nyt = np.full_like(t, fill_value=2)\nyt[(t >= np.pi) & (t < 2*np.pi)] = 0\nyf = np.fft.rfft(yt, norm='forward')\nf = np.fft.rfftfreq(n=yt.size, d=t[1])\n\nfig, (ax_time, ax_freq) = plt.subplots(nrows=2)\nax_freq.semilogy(f, np.abs(yf))\nax_freq.set_xlabel('f')\nax_freq.set_ylabel('|Y(f)|')\n\nax_time.step(t, yt, label='input')\nax_time.set_xlabel('t')\nax_time.set_ylabel('y(t)')\nfor n in (15, 5, 1):\n yf[n + 1:] = 0\n ytapprox = np.fft.irfft(yf, n=yt.size, norm='forward')\n ax_time.plot(t, ytapprox, label=f'n={n}')\nax_time.legend()\n\nplt.show()", "answer_url": "https://scicomp.stackexchange.com/a/45542", "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-20T17:18:55+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": 45541, "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-20T17:18:55+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "62E18C62-347B-4371-A12B-7026926DDD8F", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/62E18C62-347B-4371-A12B-7026926DDD8F/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-21T01:55:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "DB2CC339-A8C8-44D8-816A-B9919DFBB2BE", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/DB2CC339-A8C8-44D8-816A-B9919DFBB2BE/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-27T18:44:52+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "5CA547D4-1223-44E9-9049-12894162675F", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/5CA547D4-1223-44E9-9049-12894162675F/view-source"}], "score": 3, "updated_at": "2026-09-27T18:44:52+00:00"}], "domain": "computational_science", "external_links": ["https://i.sstatic.net/9Q1FTH4K.png", "https://i.sstatic.net/Ag4Fil8J.png", "https://i.sstatic.net/QM4j9vnZ.png", "https://i.sstatic.net/YjgeAIXx.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": "Omar Osman Mahamoud", "question_author_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "question_author_user_type": "registered", "question_created_at": "2026-09-20T09:43:07+00:00", "question_html": "here is the Fourier series I'm trying to represent:
\n$$\nf(t) = \\frac{A\\tau}{T} + \\frac{A}{\\pi}\\sum_{n=1}^{\\infty}\\frac{1}{n}\\left[\\sin(n\\omega\\tau)\\cos(n\\omega t) + \\left(1-\\cos(n\\omega\\tau)\\right)\\sin(n\\omega t)\\right]\n$$
\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.zeros(500)\nfor i in range(500):\n somme = 0\n # print("t = ", i)\n for j in range(1,n+1):\n # print("n = ", j)\n somme+=(A/j*np.pi)*(np.sin(j*tau)*np.cos(j*i)+(1-np.cos(j*tau))*np.sin(j*i))\n f_t[i-1]= c+somme\nplt.plot(t, f_t)\nplt.show()\n\ncan you guys please tell me why my algorithm doesn't work properly?\nactually my teacher says I should obtain the following figure:
\n\nnot the straight lines I'm obtaining with my code!! here is what I'm getting with my code:
\n\n", "question_id": 45541, "question_license": "CC BY-SA 4.0", "question_score": 1, "question_text": "here is the Fourier series I'm trying to represent:\n\n\n\n\n$$\nf(t) = \\frac{A\\tau}{T} + \\frac{A}{\\pi}\\sum_{n=1}^{\\infty}\\frac{1}{n}\\left[\\sin(n\\omega\\tau)\\cos(n\\omega t) + \\left(1-\\cos(n\\omega\\tau)\\right)\\sin(n\\omega t)\\right]\n$$\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.zeros(500)\nfor i in range(500):\n somme = 0\n # print(\"t = \", i)\n for j in range(1,n+1):\n # print(\"n = \", j)\n somme+=(A/j*np.pi)*(np.sin(j*tau)*np.cos(j*i)+(1-np.cos(j*tau))*np.sin(j*i))\n f_t[i-1]= c+somme\nplt.plot(t, f_t)\nplt.show()\n\n\n\n\n\ncan you guys please tell me why my algorithm doesn't work properly?\nactually my teacher says I should obtain the following figure:\n\n\n\n\n[image: the correct figure according to my teacher; source: https://i.sstatic.net/QM4j9vnZ.png] (https://i.sstatic.net/QM4j9vnZ.png)\n\n\n\n\nnot the straight lines I'm obtaining with my code!! here is what I'm getting with my code:\n\n\n\n\n[image: the function I get with my code; source: https://i.sstatic.net/9Q1FTH4K.png] (https://i.sstatic.net/9Q1FTH4K.png)", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-09-20T09:43:07+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "8716CC99-7DA9-4A6F-911C-FAACA954CAA2", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/8716CC99-7DA9-4A6F-911C-FAACA954CAA2/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-09-20T19:27:14+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "B66CE3FA-A844-4670-A363-F672A05FC4D7", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/B66CE3FA-A844-4670-A363-F672A05FC4D7/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Omar Osman Mahamoud", "profile_url": "https://scicomp.stackexchange.com/users/57039/omar-osman-mahamoud", "user_type": "registered"}, "created_at": "2026-09-21T17:20:10+00:00", "raw_file": "raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json", "raw_sha256": "798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7", "revision_guid": "514285A3-DDCE-4F58-8678-1757D1975928", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://scicomp.stackexchange.com/revisions/514285A3-DDCE-4F58-8678-1757D1975928/view-source"}], "source_site": "scicomp", "source_url": "https://scicomp.stackexchange.com/questions/45541/fourier-serie-algorithm", "split": "train", "split_group": "08ece08d441adfb76f86f3181bf0940ebff42417bb75c43be3a5da1104c05c94", "tags": ["python", "algorithms", "fourier-analysis", "fourier-transform"], "thread_id": "scicomp:45541", "title": "Fourier Serie algorithm"}} {"accepted_answer": null, "code_blocks": [{"block_index": 0, "code_text": "# association/dissociation kinetics\nkinetic_sim = function(k_on, k_off, a, b) {\n ab = 0\n ab_ts = c()\n a_ts = c()\n b_ts = c()\n for (i in 1:1000) {\n ab_old = ab\n ab = ab * (1 - k_off) + k_on * (a * b)\n a = a - a*b*k_on + ab_old * k_off\n b = b - a*b*k_on + ab_old * k_off\n #cat(i, a, b, ab, k_on*a*b, k_off*ab, \"\\n\", sep=\" \")\n ab_ts = append(ab_ts, ab)\n a_ts = append(a_ts, a)\n b_ts = append(b_ts, b)\n \n }\n return(list(ab_ts, a_ts, b_ts))\n}\nout = kinetic_sim(.1, .2, 1, 1)\nplot(out[[1]] / (out[[2]] * out[[3]]), ylab=\"[AB] / ([A] * [B])\", xlab=\"time step\")\nplot(out[[1]], ylab=\"[AB]\", xlab=\"time step\")\n", "language": "unspecified", "language_note": "Syntax-screened scientific code; language not asserted; not executed", "post_id": 114769, "sha256": "143c41078127d0b31175ff50791e4323b515819dfcc512e426aafe449e85c7ea", "source_url": "https://biology.stackexchange.com/a/114769"}], "other_answers": [{"answer_html": "Update: As noted by commenter, the example stated in the question is not actually Michaelis-Menten but is rather an example of binding kinetics. See also the other answer, which is likely more relevant.
\nI would suggest, if you would like to find the steady-state concentration of $[AB]$, that you can solve this yourself mathematically. Try differentiating and setting the $\\Delta [AB]$ side of the equation to zero, and solving. You will find:
\n$ \\Delta [AB] = (k_{on}[A][B] - k_{off}[AB])\\Delta t$
\n$ 0 = (k_{on}[A][B] - k_{off}[AB])\\Delta t$
\nRearranging:
\n$k_{on}[A][B] = k_{off}[AB] $
\nAnd finally:
\n$\\frac{[AB]}{[A][B]} = \\frac{k_{on}}{k_{off}}$
\nNote that if the $k$ are constant, this amounts to the law of mass action.
\nYou can also do a forward simulation (see R code):
\n# association/dissociation kinetics\nkinetic_sim = function(k_on, k_off, a, b) {\n ab = 0\n ab_ts = c()\n a_ts = c()\n b_ts = c()\n for (i in 1:1000) {\n ab_old = ab\n ab = ab * (1 - k_off) + k_on * (a * b)\n a = a - a*b*k_on + ab_old * k_off\n b = b - a*b*k_on + ab_old * k_off\n #cat(i, a, b, ab, k_on*a*b, k_off*ab, "\\n", sep=" ")\n ab_ts = append(ab_ts, ab)\n a_ts = append(a_ts, a)\n b_ts = append(b_ts, b)\n \n }\n return(list(ab_ts, a_ts, b_ts))\n}\nout = kinetic_sim(.1, .2, 1, 1)\nplot(out[[1]] / (out[[2]] * out[[3]]), ylab="[AB] / ([A] * [B])", xlab="time step")\nplot(out[[1]], ylab="[AB]", xlab="time step")\n\n\nYou can see that both the ratio and the final concentration equilibrate.
\n", "answer_id": 114769, "answer_text": "Update: As noted by commenter, the example stated in the question is not actually Michaelis-Menten but is rather an example of binding kinetics. See also the other answer, which is likely more relevant.\n\n\n\n\nI would suggest, if you would like to find the steady-state concentration of $[AB]$, that you can solve this yourself mathematically. Try differentiating and setting the $\\Delta [AB]$ side of the equation to zero, and solving. You will find:\n\n\n\n\n$ \\Delta [AB] = (k_{on}[A][B] - k_{off}[AB])\\Delta t$\n\n\n\n\n$ 0 = (k_{on}[A][B] - k_{off}[AB])\\Delta t$\n\n\n\n\nRearranging:\n\n\n\n\n$k_{on}[A][B] = k_{off}[AB] $\n\n\n\n\nAnd finally:\n\n\n\n\n$\\frac{[AB]}{[A][B]} = \\frac{k_{on}}{k_{off}}$\n\n\n\n\nNote that if the $k$ are constant, this amounts to the law of mass action.\n\n\n\n\nYou can also do a forward simulation (see R code):\n\n\n\n\n# association/dissociation kinetics\nkinetic_sim = function(k_on, k_off, a, b) {\n ab = 0\n ab_ts = c()\n a_ts = c()\n b_ts = c()\n for (i in 1:1000) {\n ab_old = ab\n ab = ab * (1 - k_off) + k_on * (a * b)\n a = a - a*b*k_on + ab_old * k_off\n b = b - a*b*k_on + ab_old * k_off\n #cat(i, a, b, ab, k_on*a*b, k_off*ab, \"\\n\", sep=\" \")\n ab_ts = append(ab_ts, ab)\n a_ts = append(a_ts, a)\n b_ts = append(b_ts, b)\n \n }\n return(list(ab_ts, a_ts, b_ts))\n}\nout = kinetic_sim(.1, .2, 1, 1)\nplot(out[[1]] / (out[[2]] * out[[3]]), ylab=\"[AB] / ([A] * [B])\", xlab=\"time step\")\nplot(out[[1]], ylab=\"[AB]\", xlab=\"time step\")\n\n\n\n\n\n[image: concentration of ratio [AB]:[A]*[B] over time; source: https://i.sstatic.net/Lw4hnYdr.png] (https://i.sstatic.net/Lw4hnYdr.png)\n[image: concentration of ratio [AB] over time; source: https://i.sstatic.net/pzN8ZZif.png] (https://i.sstatic.net/pzN8ZZif.png)\n\n\n\n\nYou can see that both the ratio and the final concentration equilibrate.", "answer_url": "https://biology.stackexchange.com/a/114769", "author": "Maximilian Press", "author_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2024-05-27T18:34:26+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:03:27.977583+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/1cbf95322a17dce0fd00a109179063ffe60bcd4bddc6e720f0ca398ee7aa9da8_0.json", "raw_sha256": "a096c86028a279b01346143890b4827bd8ed05afc0a76bd7c8bcb840211dc20e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/114983;114969;114966;114963;114939;114936;114918;114909;114904;114899;114888;114885;114881;114875;114874;114873;114872;114864;114857;114850;114846;114841;114834;114827;114821;114819;114813;114804;114791;114784;114768;114765;114762;114760;114758;114755;114745;114741;114739;114738;114732;114730;114726;114714;114706;114695;114691;114690;114686;114683;114677;114675;114666;114660;114656;114653;114642;114641;114632;114628;114620;114618;114613;114601;114599;114597;114581;114577;114573;114567;114558;114555;114553;114552;114547;114545;114543;114542;114541;114539;114529;114524;114516;114502;114501;114498;114495;114492;114481;114476;114474;114470;114453;114451;114449;114448;114446;114440;114438;114435/answers?filter=withbody&order=asc&page=1&pagesize=100&site=biology&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 114768, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-27T18:34:26+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "2F432EEF-5BF3-4FFE-B7E3-7AB1C8116BB1", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/2F432EEF-5BF3-4FFE-B7E3-7AB1C8116BB1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-27T19:01:38+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "F76C5C34-436D-4C68-9446-B7AA8D46C53D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/F76C5C34-436D-4C68-9446-B7AA8D46C53D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-27T23:07:19+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "66A6E2A9-6D6D-44A5-9689-4CA42FD819D5", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/66A6E2A9-6D6D-44A5-9689-4CA42FD819D5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "TAR86", "profile_url": "https://biology.stackexchange.com/users/32467/tar86", "user_type": "registered"}, "created_at": "2024-05-28T18:28:08+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "F6B6E1D3-9103-4319-8C45-5BA53EDE0E07", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/F6B6E1D3-9103-4319-8C45-5BA53EDE0E07/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-29T15:54:51+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "F7F491C7-A6AE-4CC7-A285-9BCB342B71FB", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/F7F491C7-A6AE-4CC7-A285-9BCB342B71FB/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-29T16:02:07+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "7B9A63C5-69E0-473A-8EB0-676C7D3E95EC", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/7B9A63C5-69E0-473A-8EB0-676C7D3E95EC/view-source"}], "score": 4, "updated_at": "2024-05-29T16:02:07+00:00"}], "product": "code_qa", "question": "I would like to understand the classic kinetic model of association / dissociation that tries to describe the concentration of a compound $[\\ce{AB}]$.\nLet's say we have a model:\n\n\n\n\n$\\ce{A + B} \\xrightleftharpoons[k_{\\text{off}}]{k_{\\text{on}}} \\ce{AB}$\n\n\n\n\nSo $k_{\\text{on}}$ is the rate of binding and $k_{\\text{off}}$ is the rate of unbinding and the rate equation is:\n\n\n\n\n$\\frac{d[\\ce{AB}]}{dt}=k_{\\text{on}}[\\ce{A}][\\ce{B}]-k_{\\text{off}}[\\ce{AB}]$\n\n\n\n\nI don't understand why texts say that if $k_{\\text{on}}$ and $k_{\\text{off}}$ are both constant then we reach a steady state, i.e., $k_{\\text{on}}\\ce{AB}=k_{\\text{off}}[\\ce{AB}]$ I mean: if, for example, the rate of binding, is greater then the rate of unbinding, shouldn't the concentration of the final compound increase up to infinity? What I have in mind is: we produce 4 proteins per second and degrade 2 proteins per second, then the net production is 2 proteins per second so, as time goes by, the concentration should increase and doesn't reach a plateau.\n\n\n\n\nWhy do we instead reach a plateau in the final concentration? I can understand the plateau in the plot of the reaction velocity but still, if the velocity is constant, still the concentration of the final compound should increase.", "record_id": "Scientific-Code-and-Analysis-QA:biology:114768", "selected_answer": {"answer_html": "There is a misunderstanding here that is very common when first learning about chemical kinetics. First you say:
\n\n\nif $k_{\\rm on}$ and $k_{\\rm off}$ are both constant
\n
but then:
\n\n\nif the velocity is constant
\n
This is not one and the same!
\n$k$ is the rate constant of reaction.* The actual reaction rate (i.e., the change in concentration over time) is given in your example by:
\n$v_{\\rm on} = k_{\\rm on}[A][B]$ for the forward (binding) reaction, and
\n$v_{\\rm off} = k_{\\rm off}[AB]$ for the reverse (unbinding) reaction.
\nSuppose that $k_{\\rm on} > k_{\\rm off}$. Then at first $v_{\\rm on} > v_{\\rm off}$ and the product AB is produced faster than it degrades. Therefore the concentration of AB increases. On the other hand, A and B are consumed in the reaction, so their concentrations decrease.
\nNow look at the equations for reaction rates above! The rate of the forward reaction, $v_{\\rm on}$, depends on concentrations of starting materials, $[A][B]$; and the rate of the reverse reaction, $v_{\\rm off}$, depends on the concentration of product, $[AB]$. Therefore, as the reaction proceeds, $v_{\\rm on}$ must decrease and $v_{\\rm off}$ must increase until they reach equilibrium where both rates are equal.
\n* Note: As a convention, reaction rate constants are usually denoted by lowercase $k$. Uppercase $K$ is reserved for equilibrium constants, or the Michaelis constant $K_M$, or a number of other constants.
\n", "answer_id": 114774, "answer_text": "There is a misunderstanding here that is very common when first learning about chemical kinetics. First you say:\n\n\n\n\n\n\n\nif $k_{\\rm on}$ and $k_{\\rm off}$ are both constant\n\n\n\n\n\n\n\nbut then:\n\n\n\n\n\n\n\nif the velocity is constant\n\n\n\n\n\n\n\nThis is not one and the same!\n\n\n\n\n$k$ is the rate constant of reaction.* The actual reaction rate (i.e., the change in concentration over time) is given in your example by:\n\n\n\n\n$v_{\\rm on} = k_{\\rm on}[A][B]$ for the forward (binding) reaction, and\n\n\n\n\n$v_{\\rm off} = k_{\\rm off}[AB]$ for the reverse (unbinding) reaction.\n\n\n\n\nSuppose that $k_{\\rm on} > k_{\\rm off}$. Then at first $v_{\\rm on} > v_{\\rm off}$ and the product AB is produced faster than it degrades. Therefore the concentration of AB increases. On the other hand, A and B are consumed in the reaction, so their concentrations decrease.\n\n\n\n\nNow look at the equations for reaction rates above! The rate of the forward reaction, $v_{\\rm on}$, depends on concentrations of starting materials, $[A][B]$; and the rate of the reverse reaction, $v_{\\rm off}$, depends on the concentration of product, $[AB]$. Therefore, as the reaction proceeds, $v_{\\rm on}$ must decrease and $v_{\\rm off}$ must increase until they reach equilibrium where both rates are equal.\n\n\n\n\n\n\n\n* Note: As a convention, reaction rate constants are usually denoted by lowercase $k$. Uppercase $K$ is reserved for equilibrium constants, or the Michaelis constant $K_M$, or a number of other constants.", "answer_url": "https://biology.stackexchange.com/a/114774", "author": "knomologs", "author_url": "https://biology.stackexchange.com/users/81058/knomologs", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2024-05-28T07:12:10+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:03:27.977583+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/1cbf95322a17dce0fd00a109179063ffe60bcd4bddc6e720f0ca398ee7aa9da8_0.json", "raw_sha256": "a096c86028a279b01346143890b4827bd8ed05afc0a76bd7c8bcb840211dc20e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/114983;114969;114966;114963;114939;114936;114918;114909;114904;114899;114888;114885;114881;114875;114874;114873;114872;114864;114857;114850;114846;114841;114834;114827;114821;114819;114813;114804;114791;114784;114768;114765;114762;114760;114758;114755;114745;114741;114739;114738;114732;114730;114726;114714;114706;114695;114691;114690;114686;114683;114677;114675;114666;114660;114656;114653;114642;114641;114632;114628;114620;114618;114613;114601;114599;114597;114581;114577;114573;114567;114558;114555;114553;114552;114547;114545;114543;114542;114541;114539;114529;114524;114516;114502;114501;114498;114495;114492;114481;114476;114474;114470;114453;114451;114449;114448;114446;114440;114438;114435/answers?filter=withbody&order=asc&page=1&pagesize=100&site=biology&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 114768, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "knomologs", "profile_url": "https://biology.stackexchange.com/users/81058/knomologs", "user_type": "registered"}, "created_at": "2024-05-28T07:12:10+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "313FA75B-43C6-4396-8899-8F5A827A0F14", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/313FA75B-43C6-4396-8899-8F5A827A0F14/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ilmari Karonen", "profile_url": "https://biology.stackexchange.com/users/239/ilmari-karonen", "user_type": "registered"}, "created_at": "2024-05-28T08:54:26+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "9D91925C-3E92-4DDA-BB75-8BF48F945F36", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/9D91925C-3E92-4DDA-BB75-8BF48F945F36/view-source"}], "score": 11, "updated_at": "2024-05-28T08:54:26+00:00"}, "selection_rule": "accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label", "split": "holdout", "thread": {"accepted_answer_id": null, "answers": [{"answer_html": "Update: As noted by commenter, the example stated in the question is not actually Michaelis-Menten but is rather an example of binding kinetics. See also the other answer, which is likely more relevant.
\nI would suggest, if you would like to find the steady-state concentration of $[AB]$, that you can solve this yourself mathematically. Try differentiating and setting the $\\Delta [AB]$ side of the equation to zero, and solving. You will find:
\n$ \\Delta [AB] = (k_{on}[A][B] - k_{off}[AB])\\Delta t$
\n$ 0 = (k_{on}[A][B] - k_{off}[AB])\\Delta t$
\nRearranging:
\n$k_{on}[A][B] = k_{off}[AB] $
\nAnd finally:
\n$\\frac{[AB]}{[A][B]} = \\frac{k_{on}}{k_{off}}$
\nNote that if the $k$ are constant, this amounts to the law of mass action.
\nYou can also do a forward simulation (see R code):
\n# association/dissociation kinetics\nkinetic_sim = function(k_on, k_off, a, b) {\n ab = 0\n ab_ts = c()\n a_ts = c()\n b_ts = c()\n for (i in 1:1000) {\n ab_old = ab\n ab = ab * (1 - k_off) + k_on * (a * b)\n a = a - a*b*k_on + ab_old * k_off\n b = b - a*b*k_on + ab_old * k_off\n #cat(i, a, b, ab, k_on*a*b, k_off*ab, "\\n", sep=" ")\n ab_ts = append(ab_ts, ab)\n a_ts = append(a_ts, a)\n b_ts = append(b_ts, b)\n \n }\n return(list(ab_ts, a_ts, b_ts))\n}\nout = kinetic_sim(.1, .2, 1, 1)\nplot(out[[1]] / (out[[2]] * out[[3]]), ylab="[AB] / ([A] * [B])", xlab="time step")\nplot(out[[1]], ylab="[AB]", xlab="time step")\n\n\nYou can see that both the ratio and the final concentration equilibrate.
\n", "answer_id": 114769, "answer_text": "Update: As noted by commenter, the example stated in the question is not actually Michaelis-Menten but is rather an example of binding kinetics. See also the other answer, which is likely more relevant.\n\n\n\n\nI would suggest, if you would like to find the steady-state concentration of $[AB]$, that you can solve this yourself mathematically. Try differentiating and setting the $\\Delta [AB]$ side of the equation to zero, and solving. You will find:\n\n\n\n\n$ \\Delta [AB] = (k_{on}[A][B] - k_{off}[AB])\\Delta t$\n\n\n\n\n$ 0 = (k_{on}[A][B] - k_{off}[AB])\\Delta t$\n\n\n\n\nRearranging:\n\n\n\n\n$k_{on}[A][B] = k_{off}[AB] $\n\n\n\n\nAnd finally:\n\n\n\n\n$\\frac{[AB]}{[A][B]} = \\frac{k_{on}}{k_{off}}$\n\n\n\n\nNote that if the $k$ are constant, this amounts to the law of mass action.\n\n\n\n\nYou can also do a forward simulation (see R code):\n\n\n\n\n# association/dissociation kinetics\nkinetic_sim = function(k_on, k_off, a, b) {\n ab = 0\n ab_ts = c()\n a_ts = c()\n b_ts = c()\n for (i in 1:1000) {\n ab_old = ab\n ab = ab * (1 - k_off) + k_on * (a * b)\n a = a - a*b*k_on + ab_old * k_off\n b = b - a*b*k_on + ab_old * k_off\n #cat(i, a, b, ab, k_on*a*b, k_off*ab, \"\\n\", sep=\" \")\n ab_ts = append(ab_ts, ab)\n a_ts = append(a_ts, a)\n b_ts = append(b_ts, b)\n \n }\n return(list(ab_ts, a_ts, b_ts))\n}\nout = kinetic_sim(.1, .2, 1, 1)\nplot(out[[1]] / (out[[2]] * out[[3]]), ylab=\"[AB] / ([A] * [B])\", xlab=\"time step\")\nplot(out[[1]], ylab=\"[AB]\", xlab=\"time step\")\n\n\n\n\n\n[image: concentration of ratio [AB]:[A]*[B] over time; source: https://i.sstatic.net/Lw4hnYdr.png] (https://i.sstatic.net/Lw4hnYdr.png)\n[image: concentration of ratio [AB] over time; source: https://i.sstatic.net/pzN8ZZif.png] (https://i.sstatic.net/pzN8ZZif.png)\n\n\n\n\nYou can see that both the ratio and the final concentration equilibrate.", "answer_url": "https://biology.stackexchange.com/a/114769", "author": "Maximilian Press", "author_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2024-05-27T18:34:26+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:03:27.977583+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/1cbf95322a17dce0fd00a109179063ffe60bcd4bddc6e720f0ca398ee7aa9da8_0.json", "raw_sha256": "a096c86028a279b01346143890b4827bd8ed05afc0a76bd7c8bcb840211dc20e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/114983;114969;114966;114963;114939;114936;114918;114909;114904;114899;114888;114885;114881;114875;114874;114873;114872;114864;114857;114850;114846;114841;114834;114827;114821;114819;114813;114804;114791;114784;114768;114765;114762;114760;114758;114755;114745;114741;114739;114738;114732;114730;114726;114714;114706;114695;114691;114690;114686;114683;114677;114675;114666;114660;114656;114653;114642;114641;114632;114628;114620;114618;114613;114601;114599;114597;114581;114577;114573;114567;114558;114555;114553;114552;114547;114545;114543;114542;114541;114539;114529;114524;114516;114502;114501;114498;114495;114492;114481;114476;114474;114470;114453;114451;114449;114448;114446;114440;114438;114435/answers?filter=withbody&order=asc&page=1&pagesize=100&site=biology&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 114768, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-27T18:34:26+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "2F432EEF-5BF3-4FFE-B7E3-7AB1C8116BB1", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/2F432EEF-5BF3-4FFE-B7E3-7AB1C8116BB1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-27T19:01:38+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "F76C5C34-436D-4C68-9446-B7AA8D46C53D", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/F76C5C34-436D-4C68-9446-B7AA8D46C53D/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-27T23:07:19+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "66A6E2A9-6D6D-44A5-9689-4CA42FD819D5", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/66A6E2A9-6D6D-44A5-9689-4CA42FD819D5/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "TAR86", "profile_url": "https://biology.stackexchange.com/users/32467/tar86", "user_type": "registered"}, "created_at": "2024-05-28T18:28:08+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "F6B6E1D3-9103-4319-8C45-5BA53EDE0E07", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/F6B6E1D3-9103-4319-8C45-5BA53EDE0E07/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-29T15:54:51+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "F7F491C7-A6AE-4CC7-A285-9BCB342B71FB", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/F7F491C7-A6AE-4CC7-A285-9BCB342B71FB/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-29T16:02:07+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "7B9A63C5-69E0-473A-8EB0-676C7D3E95EC", "revision_number": 6, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/7B9A63C5-69E0-473A-8EB0-676C7D3E95EC/view-source"}], "score": 4, "updated_at": "2024-05-29T16:02:07+00:00"}, {"answer_html": "There is a misunderstanding here that is very common when first learning about chemical kinetics. First you say:
\n\n\nif $k_{\\rm on}$ and $k_{\\rm off}$ are both constant
\n
but then:
\n\n\nif the velocity is constant
\n
This is not one and the same!
\n$k$ is the rate constant of reaction.* The actual reaction rate (i.e., the change in concentration over time) is given in your example by:
\n$v_{\\rm on} = k_{\\rm on}[A][B]$ for the forward (binding) reaction, and
\n$v_{\\rm off} = k_{\\rm off}[AB]$ for the reverse (unbinding) reaction.
\nSuppose that $k_{\\rm on} > k_{\\rm off}$. Then at first $v_{\\rm on} > v_{\\rm off}$ and the product AB is produced faster than it degrades. Therefore the concentration of AB increases. On the other hand, A and B are consumed in the reaction, so their concentrations decrease.
\nNow look at the equations for reaction rates above! The rate of the forward reaction, $v_{\\rm on}$, depends on concentrations of starting materials, $[A][B]$; and the rate of the reverse reaction, $v_{\\rm off}$, depends on the concentration of product, $[AB]$. Therefore, as the reaction proceeds, $v_{\\rm on}$ must decrease and $v_{\\rm off}$ must increase until they reach equilibrium where both rates are equal.
\n* Note: As a convention, reaction rate constants are usually denoted by lowercase $k$. Uppercase $K$ is reserved for equilibrium constants, or the Michaelis constant $K_M$, or a number of other constants.
\n", "answer_id": 114774, "answer_text": "There is a misunderstanding here that is very common when first learning about chemical kinetics. First you say:\n\n\n\n\n\n\n\nif $k_{\\rm on}$ and $k_{\\rm off}$ are both constant\n\n\n\n\n\n\n\nbut then:\n\n\n\n\n\n\n\nif the velocity is constant\n\n\n\n\n\n\n\nThis is not one and the same!\n\n\n\n\n$k$ is the rate constant of reaction.* The actual reaction rate (i.e., the change in concentration over time) is given in your example by:\n\n\n\n\n$v_{\\rm on} = k_{\\rm on}[A][B]$ for the forward (binding) reaction, and\n\n\n\n\n$v_{\\rm off} = k_{\\rm off}[AB]$ for the reverse (unbinding) reaction.\n\n\n\n\nSuppose that $k_{\\rm on} > k_{\\rm off}$. Then at first $v_{\\rm on} > v_{\\rm off}$ and the product AB is produced faster than it degrades. Therefore the concentration of AB increases. On the other hand, A and B are consumed in the reaction, so their concentrations decrease.\n\n\n\n\nNow look at the equations for reaction rates above! The rate of the forward reaction, $v_{\\rm on}$, depends on concentrations of starting materials, $[A][B]$; and the rate of the reverse reaction, $v_{\\rm off}$, depends on the concentration of product, $[AB]$. Therefore, as the reaction proceeds, $v_{\\rm on}$ must decrease and $v_{\\rm off}$ must increase until they reach equilibrium where both rates are equal.\n\n\n\n\n\n\n\n* Note: As a convention, reaction rate constants are usually denoted by lowercase $k$. Uppercase $K$ is reserved for equilibrium constants, or the Michaelis constant $K_M$, or a number of other constants.", "answer_url": "https://biology.stackexchange.com/a/114774", "author": "knomologs", "author_url": "https://biology.stackexchange.com/users/81058/knomologs", "author_user_type": "registered", "content_license": "CC BY-SA 4.0", "created_at": "2024-05-28T07:12:10+00:00", "is_accepted": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:03:27.977583+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/1cbf95322a17dce0fd00a109179063ffe60bcd4bddc6e720f0ca398ee7aa9da8_0.json", "raw_sha256": "a096c86028a279b01346143890b4827bd8ed05afc0a76bd7c8bcb840211dc20e", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/questions/114983;114969;114966;114963;114939;114936;114918;114909;114904;114899;114888;114885;114881;114875;114874;114873;114872;114864;114857;114850;114846;114841;114834;114827;114821;114819;114813;114804;114791;114784;114768;114765;114762;114760;114758;114755;114745;114741;114739;114738;114732;114730;114726;114714;114706;114695;114691;114690;114686;114683;114677;114675;114666;114660;114656;114653;114642;114641;114632;114628;114620;114618;114613;114601;114599;114597;114581;114577;114573;114567;114558;114555;114553;114552;114547;114545;114543;114542;114541;114539;114529;114524;114516;114502;114501;114498;114495;114492;114481;114476;114474;114470;114453;114451;114449;114448;114446;114440;114438;114435/answers?filter=withbody&order=asc&page=1&pagesize=100&site=biology&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_id": 114768, "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "knomologs", "profile_url": "https://biology.stackexchange.com/users/81058/knomologs", "user_type": "registered"}, "created_at": "2024-05-28T07:12:10+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "313FA75B-43C6-4396-8899-8F5A827A0F14", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/313FA75B-43C6-4396-8899-8F5A827A0F14/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Ilmari Karonen", "profile_url": "https://biology.stackexchange.com/users/239/ilmari-karonen", "user_type": "registered"}, "created_at": "2024-05-28T08:54:26+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "9D91925C-3E92-4DDA-BB75-8BF48F945F36", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/9D91925C-3E92-4DDA-BB75-8BF48F945F36/view-source"}], "score": 11, "updated_at": "2024-05-28T08:54:26+00:00"}], "domain": "biology", "external_links": ["https://i.sstatic.net/Lw4hnYdr.png", "https://i.sstatic.net/pzN8ZZif.png"], "medical_sensitive": false, "patient_specific": false, "provenance": {"attribution_required": true, "collected_at": "2026-10-01T03:03:07.165481+00:00", "license": "CC BY-SA 4.0", "license_url": "https://creativecommons.org/licenses/by-sa/4.0/", "raw_file": "raw/codex_api_v1/b97a755f39b54a1e8a057fa5e484426784aa17a1971c6ef0ca759105de983078_0.json", "raw_sha256": "4c9dcc077d306d60a8b8a237ad3f9b3144c0d5885fa62ef1bfdd55d2fbbdaf6a", "source_api": "Stack Exchange API 2.3", "source_url": "https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=6&pagesize=100&site=biology&sort=creation", "transformation": "API HTML retained; mechanical HTML-to-text; no LLM rewriting"}, "question_author": "Salmon", "question_author_url": "https://biology.stackexchange.com/users/81048/salmon", "question_author_user_type": "registered", "question_created_at": "2024-05-27T17:53:29+00:00", "question_html": "I would like to understand the classic kinetic model of association / dissociation that tries to describe the concentration of a compound $[\\ce{AB}]$.\nLet's say we have a model:
\n$\\ce{A + B} \\xrightleftharpoons[k_{\\text{off}}]{k_{\\text{on}}} \\ce{AB}$
\nSo $k_{\\text{on}}$ is the rate of binding and $k_{\\text{off}}$ is the rate of unbinding and the rate equation is:
\n$\\frac{d[\\ce{AB}]}{dt}=k_{\\text{on}}[\\ce{A}][\\ce{B}]-k_{\\text{off}}[\\ce{AB}]$
\nI don't understand why texts say that if $k_{\\text{on}}$ and $k_{\\text{off}}$ are both constant then we reach a steady state, i.e., $k_{\\text{on}}\\ce{AB}=k_{\\text{off}}[\\ce{AB}]$ I mean: if, for example, the rate of binding, is greater then the rate of unbinding, shouldn't the concentration of the final compound increase up to infinity? What I have in mind is: we produce 4 proteins per second and degrade 2 proteins per second, then the net production is 2 proteins per second so, as time goes by, the concentration should increase and doesn't reach a plateau.
\nWhy do we instead reach a plateau in the final concentration? I can understand the plateau in the plot of the reaction velocity but still, if the velocity is constant, still the concentration of the final compound should increase.
\n", "question_id": 114768, "question_license": "CC BY-SA 4.0", "question_score": 9, "question_text": "I would like to understand the classic kinetic model of association / dissociation that tries to describe the concentration of a compound $[\\ce{AB}]$.\nLet's say we have a model:\n\n\n\n\n$\\ce{A + B} \\xrightleftharpoons[k_{\\text{off}}]{k_{\\text{on}}} \\ce{AB}$\n\n\n\n\nSo $k_{\\text{on}}$ is the rate of binding and $k_{\\text{off}}$ is the rate of unbinding and the rate equation is:\n\n\n\n\n$\\frac{d[\\ce{AB}]}{dt}=k_{\\text{on}}[\\ce{A}][\\ce{B}]-k_{\\text{off}}[\\ce{AB}]$\n\n\n\n\nI don't understand why texts say that if $k_{\\text{on}}$ and $k_{\\text{off}}$ are both constant then we reach a steady state, i.e., $k_{\\text{on}}\\ce{AB}=k_{\\text{off}}[\\ce{AB}]$ I mean: if, for example, the rate of binding, is greater then the rate of unbinding, shouldn't the concentration of the final compound increase up to infinity? What I have in mind is: we produce 4 proteins per second and degrade 2 proteins per second, then the net production is 2 proteins per second so, as time goes by, the concentration should increase and doesn't reach a plateau.\n\n\n\n\nWhy do we instead reach a plateau in the final concentration? I can understand the plateau in the plot of the reaction velocity but still, if the velocity is constant, still the concentration of the final compound should increase.", "revision_attribution": [{"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Salmon", "profile_url": "https://biology.stackexchange.com/users/81048/salmon", "user_type": "registered"}, "created_at": "2024-05-27T17:53:29+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "8F6A9C82-AB24-4AAA-AEA4-4CCEC307A30D", "revision_number": 1, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/8F6A9C82-AB24-4AAA-AEA4-4CCEC307A30D/view-source"}, {"content_license": null, "contributor": {"display_name": "[deleted/unavailable user]", "profile_url": null, "user_type": "does_not_exist"}, "created_at": "2024-05-28T01:55:54+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "67E06F37-A278-489B-9151-42F43CC33901", "revision_number": null, "revision_type": "vote_based", "revision_url": "https://biology.stackexchange.com/revisions/67E06F37-A278-489B-9151-42F43CC33901/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Eonema", "profile_url": "https://biology.stackexchange.com/users/61325/eonema", "user_type": "registered"}, "created_at": "2024-05-28T18:27:34+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "1BE03709-7FDD-4B62-AC28-EA9679360587", "revision_number": 2, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/1BE03709-7FDD-4B62-AC28-EA9679360587/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "terdon", "profile_url": "https://biology.stackexchange.com/users/1306/terdon", "user_type": "moderator"}, "created_at": "2024-05-29T09:20:12+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "EA80ADAF-D374-4B5D-AD65-EB7FFB2E5272", "revision_number": 3, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/EA80ADAF-D374-4B5D-AD65-EB7FFB2E5272/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "Maximilian Press", "profile_url": "https://biology.stackexchange.com/users/22392/maximilian-press", "user_type": "registered"}, "created_at": "2024-05-29T15:57:09+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "65B6CB44-E4EC-42B0-A71E-63D9F3F3ADB1", "revision_number": 4, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/65B6CB44-E4EC-42B0-A71E-63D9F3F3ADB1/view-source"}, {"content_license": "CC BY-SA 4.0", "contributor": {"display_name": "David", "profile_url": "https://biology.stackexchange.com/users/22057/david", "user_type": "registered"}, "created_at": "2024-06-01T17:40:24+00:00", "raw_file": "raw/codex_api_v1/41500cf35bca9ae31b7ea454bad8679af7e3276d71713db5d1815d84a971bb0e_1790824088925435600_0.json", "raw_sha256": "a764902131a161e2a7978a1f607c4912689efa157d70c2752a5b31e3a042aacb", "revision_guid": "DF937FB9-3603-49F8-9865-D03B3F660F75", "revision_number": 5, "revision_type": "single_user", "revision_url": "https://biology.stackexchange.com/revisions/DF937FB9-3603-49F8-9865-D03B3F660F75/view-source"}], "source_site": "biology", "source_url": "https://biology.stackexchange.com/questions/114768/understanding-association-kinetics", "split": "holdout", "split_group": "8b0f36cc135364768cd90ac330640c6f0b50ae8f7a33283b023303c13e7f6e98", "tags": ["biochemistry", "enzymes", "kinetics"], "thread_id": "biology:114768", "title": "Understanding association kinetics"}}