RegalFire's picture
RegalFire V3: independently validated source-derived release
a3a7873 verified
Raw History Blame Contribute Delete
195 kB
{"accepted_answer":null,"answer_scores":[{"answer_id":116397,"score":1}],"answers":[{"answer_html":"<p>I would suggest instead looking at the mtDNA sequence deposited in NCBI: <a href=\"https://www.ncbi.nlm.nih.gov/nuccore/KC879692.1\" rel=\"nofollow noreferrer\">https://www.ncbi.nlm.nih.gov/nuccore/KC879692.1</a></p>\n<p>I am not sure how this was generated exactly so maybe look into that more. But as far as I can tell it's what you want:</p>\n<pre><code>LOCUS KC879692 16567 bp DNA circular PRI 24-JUN-2013\nDEFINITION Homo sapiens neanderthalensis mitochondrion, complete genome.\nACCESSION KC879692\nVERSION KC879692.1\nKEYWORDS .\nSOURCE mitochondrion Homo sapiens neanderthalensis (Neandertal)\n ORGANISM Homo sapiens neanderthalensis\n Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi;\n Mammalia; Eutheria; Euarchontoglires; Primates; Haplorrhini;\n Catarrhini; Hominidae; Homo.\nREFERENCE 1 (bases 1 to 16567)\n AUTHORS Consortium,H.C.N.G.\n TITLE The high-coverage genome sequence of a Neandertal individual from\n Denisova cave in the Altai\n JOURNAL Unpublished\nREFERENCE 2 (bases 1 to 16567)\n AUTHORS Sawyer,S.\n TITLE Direct Submission\n JOURNAL Submitted (09-APR-2013) Genetics, Max Planck Institute for\n Evolutionary Anthropology, Deutscher Platz 6, Leipzig, Saxony\n 04103, Germany\n</code></pre>\n","answer_id":116397,"answer_text":"I would suggest instead looking at the mtDNA sequence deposited in NCBI: https://www.ncbi.nlm.nih.gov/nuccore/KC879692.1 (https://www.ncbi.nlm.nih.gov/nuccore/KC879692.1)\n\n\n\n\nI am not sure how this was generated exactly so maybe look into that more. But as far as I can tell it's what you want:\n\n\n\n\nLOCUS KC879692 16567 bp DNA circular PRI 24-JUN-2013\nDEFINITION Homo sapiens neanderthalensis mitochondrion, complete genome.\nACCESSION KC879692\nVERSION KC879692.1\nKEYWORDS .\nSOURCE mitochondrion Homo sapiens neanderthalensis (Neandertal)\n ORGANISM Homo sapiens neanderthalensis\n Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi;\n Mammalia; Eutheria; Euarchontoglires; Primates; Haplorrhini;\n Catarrhini; Hominidae; Homo.\nREFERENCE 1 (bases 1 to 16567)\n AUTHORS Consortium,H.C.N.G.\n TITLE The high-coverage genome sequence of a Neandertal individual from\n Denisova cave in the Altai\n JOURNAL Unpublished\nREFERENCE 2 (bases 1 to 16567)\n AUTHORS Sawyer,S.\n TITLE Direct Submission\n JOURNAL Submitted (09-APR-2013) Genetics, Max Planck Institute for\n Evolutionary Anthropology, Deutscher Platz 6, Leipzig, Saxony\n 04103, Germany","answer_url":"https://biology.stackexchange.com/a/116397","author":"Maximilian Press","author_url":"https://biology.stackexchange.com/users/22392/maximilian-press","content_license":"CC BY-SA 4.0","created_at":"2025-04-23T00:14:09+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:19.947691+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/df693642d727b738d2a533740632235c18a06cefec7a1e337c9589214a4ec91e_0.json","raw_sha256":"9df534f437f3b2f12d33db8536999ec4e6ffa10f2f59394799d9fe01c3c1ad16","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/117606;117602;117598;117594;117585;117579;117570;117568;117565;117559;117558;117555;117552;117548;117538;117524;117523;117522;117520;117515;117510;116509;116508;116504;116499;116491;116485;116483;116461;116454;116453;116445;116441;116435;116430;116426;116425;116414;116412;116406;116401;116399;116396;116395;116394;116392;116389;116384;116370;116367;116363;116361;116352;116351;116347;116345;116343;116338;116337;116332;116331;116324;116320;116316;116314;116312;116306;116292;116290;116284;116280;116277;116271;116270;116268;116267;116257;116256;116253;116250;116249;116240;116237;116233;116219;116214;116212;116205;116204;116200;116198;116187;116184;116173;116172;116167;116162;116149;116142;116129/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":116396,"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":"2025-04-23T00:14:09+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"ADFDA359-C7DC-4A0D-8A16-F7F2B59E4E7F","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/ADFDA359-C7DC-4A0D-8A16-F7F2B59E4E7F/view-source"}],"score":1}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Maximilian Press","author_url":"https://biology.stackexchange.com/users/22392/maximilian-press","content_license":"CC BY-SA 4.0","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":"2025-04-23T00:14:09+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"ADFDA359-C7DC-4A0D-8A16-F7F2B59E4E7F","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/ADFDA359-C7DC-4A0D-8A16-F7F2B59E4E7F/view-source"}],"source_url":"https://biology.stackexchange.com/a/116397"}],"question_author":"Mehdi Saada","question_author_url":"https://biology.stackexchange.com/users/82694/mehdi-saada"},"code_blocks":[{"block_index":0,"code_text":"LOCUS KC879692 16567 bp DNA circular PRI 24-JUN-2013\nDEFINITION Homo sapiens neanderthalensis mitochondrion, complete genome.\nACCESSION KC879692\nVERSION KC879692.1\nKEYWORDS .\nSOURCE mitochondrion Homo sapiens neanderthalensis (Neandertal)\n ORGANISM Homo sapiens neanderthalensis\n Eukaryota; Metazoa; Chordata; Craniata; Vertebrata; Euteleostomi;\n Mammalia; Eutheria; Euarchontoglires; Primates; Haplorrhini;\n Catarrhini; Hominidae; Homo.\nREFERENCE 1 (bases 1 to 16567)\n AUTHORS Consortium,H.C.N.G.\n TITLE The high-coverage genome sequence of a Neandertal individual from\n Denisova cave in the Altai\n JOURNAL Unpublished\nREFERENCE 2 (bases 1 to 16567)\n AUTHORS Sawyer,S.\n TITLE Direct Submission\n JOURNAL Submitted (09-APR-2013) Genetics, Max Planck Institute for\n Evolutionary Anthropology, Deutscher Platz 6, Leipzig, Saxony\n 04103, Germany\n","post_id":116397,"sha256":"8999e8a3d26cddcd71f86bf241326194e6d6968f20ed0963be7913098bdfe07e","source_url":"https://biology.stackexchange.com/a/116397"}],"content_license":"CC BY-SA 4.0","domain":"biology","error_text_if_explicit":null,"group_id":"8909fa445a12aa523ea13f6f9f5e64165fd0bcd4bf08283e343f39fdeea0c1d6","id":"SCT-017aac528e26242f29c9e2c1","language":null,"library_or_tool":null,"problem_text":"I am looking for the HVRII locus on the Altai Neandertal sequence. Its accession number is ERP002097, but it's the raw resequencing data so it is not on NCBI. You can download the relevant file (for the mtDNA here) on http://cdna.eva.mpg.de/neandertal/altai/AltaiNeandertal/bam/ (http://cdna.eva.mpg.de/neandertal/altai/AltaiNeandertal/bam/).\nThe file is huge, needless to say, but the problem is because those are the contigs, translating it into FASTA doesn't help as I get millions of small reads, what can I do with that ?\nI have the HVRII from the OG neandertal genome, and it has the tri-thymine insertion in the polycysteine tract from the HVRII. That is what I want to check on the Altai.\nDo I have to assemble it myself to give it to Blast ?\nThank you.","provenance":{"original_provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:02.598621+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/5d480e4bd1bd45ab525a4baf3227fba404f89b6af9dad33215fd9fa7c302a211_0.json","raw_sha256":"d723c7a62c8386d143891d26ae30b2234242ed3dac9599b11f141712ea994a96","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=3&pagesize=100&site=biology&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Mehdi Saada","profile_url":"https://biology.stackexchange.com/users/82694/mehdi-saada","user_type":"registered"},"created_at":"2025-04-22T23:19:27+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"641BDAAF-0DF0-4DF6-A92F-9796B028FB47","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/641BDAAF-0DF0-4DF6-A92F-9796B028FB47/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Mehdi Saada","profile_url":"https://biology.stackexchange.com/users/82694/mehdi-saada","user_type":"registered"},"created_at":"2025-04-22T23:22:21+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"FA98BB5E-D9FA-4C7D-AB0A-E887F6F7067E","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/FA98BB5E-D9FA-4C7D-AB0A-E887F6F7067E/view-source"},{"content_license":null,"contributor":{"display_name":"Community","profile_url":"https://biology.stackexchange.com/users/-1/community","user_type":"moderator"},"created_at":"2025-05-23T01:03:20+00:00","raw_file":"raw/codex_api_v1/00f792a35cd1fe53cc744b44d1c7f5a2081648f5d4403a4e8f1d570c00e5dc95_1790824135500262400_0.json","raw_sha256":"0face46f22b53414ff8968bb035acf71d0f5c1f84da8d6f0813602f842802d98","revision_guid":"2B8DE90A-567F-4469-A500-58C9EF0A1B1D","revision_number":null,"revision_type":"vote_based","revision_url":"https://biology.stackexchange.com/revisions/2B8DE90A-567F-4469-A500-58C9EF0A1B1D/view-source"}],"source_commit":"049a9227f533c13bbc10d1a38c271e055da0ed6e","source_data_file":"dataset.jsonl","source_dataset":"RegalFire/Scientific-Biology-QA","source_license":"CC BY-SA 4.0","source_record_id":"116396","source_record_sha256":"704022626335419300b4aef24969034056a47440a2d3699ed6905796b77c6cbe","source_url":"https://biology.stackexchange.com/questions/116396/how-to-find-the-hvrii-locus-on-the-altai-neandertal","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>I am looking for the HVRII locus on the Altai Neandertal sequence. Its accession number is ERP002097, but it's the raw resequencing data so it is not on NCBI. You can download the relevant file (for the mtDNA here) on <a href=\"http://cdna.eva.mpg.de/neandertal/altai/AltaiNeandertal/bam/\" rel=\"nofollow noreferrer\">http://cdna.eva.mpg.de/neandertal/altai/AltaiNeandertal/bam/</a>.\nThe file is huge, needless to say, but the problem is because those are the contigs, translating it into FASTA doesn't help as I get millions of small reads, what can I do with that ?\nI have the HVRII from the OG neandertal genome, and it has the tri-thymine insertion in the polycysteine tract from the HVRII. That is what I want to check on the Altai.\nDo I have to assemble it myself to give it to Blast ?\nThank you.</p>\n","question_title":"How to find the HVRII locus on the Altai Neandertal","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://biology.stackexchange.com/questions/116396/how-to-find-the-hvrii-locus-on-the-altai-neandertal","split":"test"}
{"accepted_answer":null,"answer_scores":[{"answer_id":677108,"score":1}],"answers":[{"answer_html":"<p>Welcome to CV!</p>\n<p>So you want to compare 2 proportions; e.g. “<em>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?</em>”.</p>\n<p>Well, the “canonical” way to compare 2 proportions is via a <a href=\"https://en.wikipedia.org/wiki/Contingency_table\" rel=\"nofollow noreferrer\">2x2 contingency table</a> (aka crosstab). And the “canonical” tests are either a <a href=\"https://en.wikipedia.org/wiki/Chi-squared_test\" rel=\"nofollow noreferrer\">chi-square</a> test, or a <a href=\"https://en.wikipedia.org/wiki/Fisher%27s_exact_test\" rel=\"nofollow noreferrer\">Fisher-exact</a> test (aka Fisher-0Irwin test).<br />\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.<br />\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.<br />\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 <a href=\"https://cran.r-universe.dev/exact2x2/doc/exact2x2.pdf\" rel=\"nofollow noreferrer\">Blaker test</a>.</p>\n<p>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?<br />\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).</p>\n<p>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.<br />\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.<br />\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.</p>\n","answer_id":677108,"answer_text":"Welcome to CV!\n\n\n\n\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?”.\n\n\n\n\nWell, the “canonical” way to compare 2 proportions is via a 2x2 contingency table (https://en.wikipedia.org/wiki/Contingency_table) (aka crosstab). And the “canonical” tests are either a chi-square (https://en.wikipedia.org/wiki/Chi-squared_test) test, or a Fisher-exact (https://en.wikipedia.org/wiki/Fisher%27s_exact_test) test (aka Fisher-0Irwin test).\n\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.\n\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.\n\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 (https://cran.r-universe.dev/exact2x2/doc/exact2x2.pdf).\n\n\n\n\nBut 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?\n\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).\n\n\n\n\nLast, 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.\n\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.\n\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.","answer_url":"https://stats.stackexchange.com/a/677108","author":"jginestet","author_url":"https://stats.stackexchange.com/users/380096/jginestet","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-09T02:03:39+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":677095,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-09-09T02:03:39+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CCDFB1CA-F81D-4A03-BE27-16DD0ED2D9AE","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CCDFB1CA-F81D-4A03-BE27-16DD0ED2D9AE/view-source"}],"score":1,"updated_at":"2026-09-09T02:03:39+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"jginestet","author_url":"https://stats.stackexchange.com/users/380096/jginestet","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"jginestet","profile_url":"https://stats.stackexchange.com/users/380096/jginestet","user_type":"registered"},"created_at":"2026-09-09T02:03:39+00:00","raw_file":"raw/codex_api_v1/3f959895a29b33d83894e5370d82e1c0cf87f20ac57fa423ebc923738357c657_1790825253957066500_0.json","raw_sha256":"ddd8808039e410ca99f97e2a7f12c307f046c4e5c3e184683bc12f816e6f49fc","revision_guid":"CCDFB1CA-F81D-4A03-BE27-16DD0ED2D9AE","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/CCDFB1CA-F81D-4A03-BE27-16DD0ED2D9AE/view-source"}],"source_url":"https://stats.stackexchange.com/a/677108"}],"question_author":"LST","question_author_url":"https://stats.stackexchange.com/users/516373/lst"},"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","post_id":"stats:677095","sha256":"1d618fa130fbed5952b989d4c334bd6f29b52043ec44b220abbe1a7348e72701","source_url":"https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"6067403de8d4d10c98e25e84e769ee976b9bd9419586ec57b09e70ad30f14367","id":"SCT-784a774b6763d0de5331e029","language":null,"library_or_tool":null,"problem_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.","provenance":{"original_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"},"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_commit":"3f6db230c4afe97d558b23fe2bfdb56dc0010d95","source_data_file":"dataset.jsonl","source_dataset":"RegalFire/Scientific-Statistics-QA","source_license":"CC BY-SA 4.0","source_record_id":"Scientific-Statistics-QA:stats:677095","source_record_sha256":"024eb7eff7d18dacf072cca8f59943c40702d3b85cc2956093304361402edce1","source_url":"https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>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.</p>\n<p>I have individual student data, but some aggregated dummy data would be:</p>\n<pre><code>modules &lt;- c(\n &quot;MA101&quot;,&quot;MA102&quot;,&quot;MA103&quot;,&quot;MA201&quot;,&quot;MA202&quot;,&quot;MA301&quot;,&quot;MA302&quot;,\n &quot;FR101&quot;,&quot;FR102&quot;,&quot;FR104&quot;,&quot;FR201&quot;,&quot;FR202&quot;,&quot;FR203&quot;,&quot;FR301&quot;,\n &quot;EN101&quot;,&quot;EN102&quot;,&quot;EN201&quot;,&quot;EN202&quot;,&quot;EN203&quot;,&quot;EN301&quot;,&quot;EN302&quot;\n)\ntotals &lt;- sample(30:400, length(modules), replace = TRUE)\ngrade_counts &lt;- t(\n sapply(totals, function(n) {\n as.vector(rmultinom(1, n, rep(1, 5)))\n })\n)\ncolnames(grade_counts) &lt;- LETTERS[1:5]\n\ndummy_data &lt;- data.frame(\n Module = modules,\n grade_counts,\n Total = totals\n)\n</code></pre>\n<p>And the questions I would like to ask are</p>\n<ul>\n<li>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?</li>\n<li>Is 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?</li>\n</ul>\n<p>I did some reading and from <a href=\"https://moderndive.com/8-confidence-intervals.html\" rel=\"nofollow noreferrer\">Chapter 8 Bootstrapping and Confidence Intervals | Statistical Inference via Data Science</a> 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).</p>\n<p>However, having dug a bit further (e.g. <a href=\"https://www.allendowney.com/blog/2024/10/15/bootstrapping-a-proportion/\" rel=\"nofollow noreferrer\">Bootstrapping a Proportion - Probably Overthinking It,</a> <a href=\"https://corplingstats.wordpress.com/2024/12/12/bootstrap-intervals/\" rel=\"nofollow noreferrer\">Bootstrap intervals for the single proportion – corp.ling.stats</a>) it seems that bootstrapping probably wasn’t the way, and I should have instead calculated Wilson CIs.</p>\n<p>Before I go down the wrong path again, I’d love a sense check from some more experienced hands.</p>\n<ul>\n<li>Are Wilson intervals the right approach for these sorts of questions?</li>\n<li>Given that I sometimes have small numbers (&lt;30 students on a course) and rare outcomes (F grades are not common!) I think I should use a continuity correction (<a href=\"https://corplingstats.wordpress.com/2019/04/27/correcting-for-continuity/\" rel=\"nofollow noreferrer\">Correcting for continuity – corp.ling.stats</a>), is that right?</li>\n<li>Any 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)?</li>\n</ul>\n<p>I 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.</p>\n<p>Thank you.</p>\n","question_title":"Testing differences in proportions - Wilson CIs, continuity corrections and multiple comparisons","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/677095/testing-differences-in-proportions-wilson-cis-continuity-corrections-and-mult","split":"test"}
{"accepted_answer":null,"answer_scores":[{"answer_id":45186,"score":3}],"answers":[{"answer_html":"<p>I might have found the solution, of which I'm listing the main points/observations here below:</p>\n<ul>\n<li>the FFT/IFFT implementation in the code is consistent with the Fourier transform computed as <span class=\"math-container\">$\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omega t}dt$</span> and correspondingly <span class=\"math-container\">$f(t)=\\frac{1}{2\\pi}\\int^{+\\infty}_{-\\infty}\\tilde{F}(\\omega)e^{i\\omega t}dt$</span>: to be sure about this I tried with the simple case of a Gaussian, but the multiplicative constants all turned out to be ok</li>\n<li>the dispersion operator should be written in the form <span class=\"math-container\">$D_{op}(\\omega)=-\\frac i2 \\beta_2 \\omega^2-\\frac i6 \\beta_3 \\omega^3$</span> to have the correct chirp sign at the output</li>\n<li>SPM should be taken into account with the factor <span class=\"math-container\">$e^{-i\\gamma \\Delta z I}$</span> (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)</li>\n<li>a spectral phase term <span class=\"math-container\">$\\varphi(\\omega)=-\\kappa \\omega^2, \\kappa&gt;0$</span> 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)</li>\n</ul>\n<p>Of course, if you have any further comments or observations let me know!</p>\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"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Lorenzo Iori","author_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori","content_license":"CC BY-SA 4.0","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"}],"source_url":"https://scicomp.stackexchange.com/a/45186"}],"question_author":"Lorenzo Iori","question_author_url":"https://scicomp.stackexchange.com/users/54430/lorenzo-iori"},"code_blocks":[{"block_index":0,"code_text":"# 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","post_id":"scicomp:45185","sha256":"0d2b3403abb149f3932d554d6c2486b994277a374004385ddffc9f133673e9b4","source_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything"},{"block_index":1,"code_text":"GDD_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","post_id":"scicomp:45185","sha256":"ede79eca3b653fe963abc5472095cd3c0de51969188b65b546e86f4f30cabf88","source_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"bd5fd699490a197c46453cd6248b87ba2e8c956fa8b9f71ad9a2f50b5a440c08","id":"SCT-906af7b675a6b310cac98ed7","language":["python"],"library_or_tool":null,"problem_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, ...","provenance":{"original_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"},"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_commit":null,"source_data_file":"native_scicomp_source.jsonl","source_dataset":"RegalFire/Scientific-Native-Scicomp","source_license":"CC BY-SA 4.0","source_record_id":"45185","source_record_sha256":"5223204980616f3e7438fe5ec2e2fc70fc28a4270ef10902b49578dee783c8e3","source_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>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.</p>\n<p>The 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).</p>\n<p>My question basically is if the implementation is correct or if there are any inconsistencies in the code below.</p>\n<p>Here are the fundamental cells of the notebook:</p>\n<pre><code># 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</code></pre>\n<p>Moreover, when introducing GDD&lt;0 with chirped mirrors, I use the convention</p>\n<pre><code>GDD_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</code></pre>\n<p>Edit: 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, ...</p>\n","question_title":"Split-step Fourier method for ultrashort pulse propagation predicts everything, but not the spectral phase","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45185/split-step-fourier-method-for-ultrashort-pulse-propagation-predicts-everything","split":"test"}
{"accepted_answer":null,"answer_scores":[{"answer_id":45329,"score":5},{"answer_id":45343,"score":1}],"answers":[{"answer_html":"<p>this is just Monte Carlo integration with cosine-weighted sampling. that’s why it works and the others don’t.</p>\n<p>cosine 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.</p>\n<p>in 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.</p>\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":"<p>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):</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void 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&amp; result_count,\n real_type&amp; result_count_plus)\n{\n // Thread-local random number generator\n std::mt19937 local_gen(thread_seed);\n std::uniform_real_distribution&lt;real_type&gt; 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 &lt; 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 &gt;= 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 &gt; 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</code></pre>\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_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}","answer_url":"https://scicomp.stackexchange.com/a/45343","author":"shawn_halayka","author_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-01-18T14:29:37+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":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-01-18T14:29:37+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"3B011F27-08FE-4F81-9889-2BB52DA3F041","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3B011F27-08FE-4F81-9889-2BB52DA3F041/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-18T21:51:26+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"33787801-2B17-4E59-8320-A2FC503E2E22","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/33787801-2B17-4E59-8320-A2FC503E2E22/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-01-18T21:51:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"44B530A0-B124-4759-A997-8B27CEECCB3E","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/44B530A0-B124-4759-A997-8B27CEECCB3E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-03-18T17:04:23+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"0D2BA30A-7FF9-42BF-9FDD-141B1D8FE414","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0D2BA30A-7FF9-42BF-9FDD-141B1D8FE414/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-03-19T21:29:13+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"F02DA395-BFED-4987-A4F2-199B2AA19C48","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/F02DA395-BFED-4987-A4F2-199B2AA19C48/view-source"}],"score":1,"updated_at":"2026-03-19T21:29:13+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Linda Anderson","author_url":"https://scicomp.stackexchange.com/users/56218/linda-anderson","content_license":"CC BY-SA 4.0","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"}],"source_url":"https://scicomp.stackexchange.com/a/45329"},{"author":"shawn_halayka","author_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-01-18T14:29:37+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"3B011F27-08FE-4F81-9889-2BB52DA3F041","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/3B011F27-08FE-4F81-9889-2BB52DA3F041/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-18T21:51:26+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"33787801-2B17-4E59-8320-A2FC503E2E22","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/33787801-2B17-4E59-8320-A2FC503E2E22/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-01-18T21:51:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"44B530A0-B124-4759-A997-8B27CEECCB3E","revision_number":3,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/44B530A0-B124-4759-A997-8B27CEECCB3E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-03-18T17:04:23+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"0D2BA30A-7FF9-42BF-9FDD-141B1D8FE414","revision_number":4,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/0D2BA30A-7FF9-42BF-9FDD-141B1D8FE414/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2026-03-19T21:29:13+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"F02DA395-BFED-4987-A4F2-199B2AA19C48","revision_number":5,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/F02DA395-BFED-4987-A4F2-199B2AA19C48/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45343"}],"question_author":"shawn_halayka","question_author_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka"},"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_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","post_id":"scicomp:45322","sha256":"dd14afb6190985801db0b42e8ce0704e201c4af56175964f7264f111c08c55ef","source_url":"https://scicomp.stackexchange.com/questions/45322/numerical-schwarzschild-gravity"},{"block_index":0,"code_text":"void 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","post_id":45343,"sha256":"8b4ac807ee7f55790fa205570aa413ed7cef7647bcb76b29af08a9295170026d","source_url":"https://scicomp.stackexchange.com/a/45343"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"493d8f724951311e95828c562fc3793d7d7131e7cc3efc2e287086abc61195fc","id":"SCT-9b0dcf9a1e140879b5148763","language":null,"library_or_tool":null,"problem_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_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\n\n\n\n\nThank you for your time!","provenance":{"original_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"},"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"shawn_halayka","profile_url":"https://scicomp.stackexchange.com/users/48649/shawn-halayka","user_type":"registered"},"created_at":"2025-12-27T16:49:47+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"B772F06F-B869-413B-B8CD-DA295250BCD1","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/B772F06F-B869-413B-B8CD-DA295250BCD1/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-27T20:17:48+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"EE985562-6FE8-4FB6-A77E-D42F97D166EC","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EE985562-6FE8-4FB6-A77E-D42F97D166EC/view-source"}],"source_commit":null,"source_data_file":"native_scicomp_source.jsonl","source_dataset":"RegalFire/Scientific-Native-Scicomp","source_license":"CC BY-SA 4.0","source_record_id":"45322","source_record_sha256":"71bb21ea86802a70e8d66ee51503b38cf0c0c7c2827e28417687c0e2d5875a8d","source_url":"https://scicomp.stackexchange.com/questions/45322/numerical-schwarzschild-gravity","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<h2>Question</h2>\n<p><strong>What 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?</strong></p>\n<p>I 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.</p>\n<h2>Introduction</h2>\n<p>In 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 <a href=\"https://www.techrxiv.org/users/685306/articles/1250456-newtonian-gravitation-from-scratch-for-c-programmers\" rel=\"noreferrer\">Newtonian gravitation from scratch, for C++ programmers</a>.</p>\n<p>In this question, I point out a match between the numerical gravitation and the gravitational time dilation from Schwarzschild's general relativity (see the book <a href=\"https://search.worldcat.org/title/585119\" rel=\"noreferrer\">Gravitation, by Misner et al</a>).\nHere, I use an axis-aligned bounding box (AABB) as the receiver.</p>\n<p>In this question I use Planck units, where <span class=\"math-container\">$c = G = \\hbar = k = 1$</span>.</p>\n<h2>Method</h2>\n<p>Where <span class=\"math-container\">$r_{e}$</span> is the emitter's Schwarzschild radius, <span class=\"math-container\">$r_{r}$</span> is the receiver AABB radius (e.g. half of the AABB side length), and <span class=\"math-container\">$1\\mathrm{e}11$</span> and <span class=\"math-container\">$0.01$</span> are arbitrary constants:\n<span class=\"math-container\">\\begin{equation}\nr_{e} = \\sqrt{\\frac{1\\mathrm{e}11 \\log(2)}{\\pi}},\n\\end{equation}</span>\n<span class=\"math-container\">\\begin{equation}\nr_{r} = r_{e} \\times 0.01.\n\\end{equation}</span>\nThe event horizon area is:\n<span class=\"math-container\">\\begin{equation}\nA_{e} = 4 \\pi r_{e}^2.\n\\end{equation}</span>\nThe binary entropy (e.g. field line count, see the papers about the holographic principle) is:\n<span class=\"math-container\">\\begin{equation}\nn_{e} = \\frac{A_{e}}{4 \\log(2)} = 1\\mathrm{e}11.\n\\end{equation}</span>\nWhere <span class=\"math-container\">$R$</span> is the distance from the emitter's centre, the derivative is:\n<span class=\"math-container\">\\begin{equation}\n\\alpha = \\frac{\\beta(R + \\epsilon) - \\beta(R)}{\\epsilon}.\n\\end{equation}</span>\nHere <span class=\"math-container\">$\\beta$</span> is the get intersecting line density function.\nThe gradient strength is:\n<span class=\"math-container\">\\begin{equation}\ng = \\frac{-\\alpha}{r_{r}^2}.% \\approx \\frac{n_e}{2 R^3}.\n\\end{equation}</span>\nFrom this I get the Newtonian acceleration <span class=\"math-container\">$a_N$</span>, where <span class=\"math-container\">$r_e \\ll R$</span>:\n<span class=\"math-container\">\\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}</span>\nI can also get a general relativistic acceleration <span class=\"math-container\">$a_S$</span>, where <span class=\"math-container\">$r_e &lt; R$</span>:\n<span class=\"math-container\">\\begin{equation}\na_S = \\frac{g R \\log 2}{8 M_{e}},\n\\end{equation}</span>\nAt close proximity, where <span class=\"math-container\">$r_e \\approx R$</span>, the metric produced is related to the Schwarzschild metric -- curved space, curved time:\n<span class=\"math-container\">\\begin{equation}\nt = \\sqrt{1 - \\frac{r_e}{R}},\n\\end{equation}</span>\n<span class=\"math-container\">\\begin{equation}\n\\frac{dt}{dR} = \\frac{r_e}{2 t R^2}.\n\\end{equation}</span>\n<span class=\"math-container\">\\begin{equation}\na_S \\approx \\frac{dt}{dR} \\frac{2}{\\pi} = \\frac{r_e}{\\pi t R^2}.\n\\end{equation}</span>\nAt far proximity, where <span class=\"math-container\">$r_e \\ll R$</span>, <span class=\"math-container\">$t \\approx 1$</span>, and <span class=\"math-container\">$dt/dR \\approx 0$</span>, the metric produced is Newtonian -- curved space, practically flat time.</p>\n<p>Using 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 (<a href=\"https://github.com/sjhalayka/schwarzschild_falloff_field_lines\" rel=\"noreferrer\">https://github.com/sjhalayka/schwarzschild_falloff_field_lines</a>), the cosine weighted pseudorandom field lines produce the correct result, off by a factor of <span class=\"math-container\">$2 / \\pi$</span>.</p>\n<h2>Figure</h2>\n<p><a href=\"https://i.sstatic.net/XWbsh2qc.png\" rel=\"noreferrer\"><img src=\"https://i.sstatic.net/XWbsh2qc.png\" alt=\"axis-aligned bounding box\" /></a></p>\n<p>This 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).</p>\n<h2>C++ code</h2>\n<pre class=\"lang-cpp prettyprint-override\"><code>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_cast&lt;unsigned&gt;(0));\n\n for (long long unsigned int i = 0; i &lt; 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&lt;double&gt; 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</code></pre>\n<p>Thank you for your time!</p>\n","question_title":"Numerical Schwarzschild gravity?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45322/numerical-schwarzschild-gravity","split":"test"}
{"accepted_answer":null,"answer_scores":[{"answer_id":45335,"score":3},{"answer_id":45337,"score":0},{"answer_id":45341,"score":2},{"answer_id":45342,"score":1}],"answers":[{"answer_html":"<blockquote>\n<p>monothonic</p>\n</blockquote>\n<p>I'm sure you meant monotonic.</p>\n<blockquote>\n<p>I am looking for a fast way to solve the problem</p>\n</blockquote>\n<p>Are you actually? I think if you were, you would use something off-the-shelf. &quot;Simple iterative&quot; and &quot;fast&quot; don't particularly jive, here. Let's take a random stab at remodelling your problem to meet <em>some</em> of your criteria:</p>\n<ul>\n<li>Linear, not quadratic</li>\n<li>No manual iteration per se</li>\n<li>Enforce inter-reference monotonicity through simple linear constraints</li>\n<li>Model cost as being absolute error plus absolute second-order differential, the latter receiving your <span class=\"math-container\">$\\lambda$</span> weight</li>\n</ul>\n<p>A traditional LP would express the problem thus. Define the following decision vectors:</p>\n<ul>\n<li><span class=\"math-container\">$z \\in \\mathbb R^n$</span>, the fit points</li>\n<li><span class=\"math-container\">$z_p \\in \\mathbb R^n$</span>, <span class=\"math-container\">$z_p \\ge 0$</span>, positive-clipped fit error</li>\n<li><span class=\"math-container\">$z_n \\in \\mathbb R^n$</span>, <span class=\"math-container\">$z_n \\ge 0$</span>, negative-clipped fit error</li>\n<li><span class=\"math-container\">$d_p \\in \\mathbb R^{n-2}$</span>, <span class=\"math-container\">$d_p \\ge 0$</span>, positive-clipped second-order differentials</li>\n<li><span class=\"math-container\">$d_n \\in \\mathbb R^{n-2}$</span>, <span class=\"math-container\">$d_n \\ge 0$</span>, negative-clipped second-order differentials</li>\n</ul>\n<p>Find</p>\n<p><span class=\"math-container\">$$ \\min_z z_p + z_n + \\lambda ( d_p + d_n ) $$</span></p>\n<p>given the following constraints:</p>\n<p><span class=\"math-container\">$$ z_p \\ge z - y $$</span>\n<span class=\"math-container\">$$ z_n \\ge y - z $$</span>\n<span class=\"math-container\">$$ d_p \\ge \\frac {\\partial^2 z} {\\partial i^2} $$</span>\n<span class=\"math-container\">$$ d_n \\ge -\\frac {\\partial^2 z} {\\partial i^2} $$</span>\n<span class=\"math-container\">$ (z_{i+1} - z_i) \\text{sgn}( y_1 - y_0 ) \\ge 0 $</span> for every index <span class=\"math-container\">$i$</span> between every anchor point <span class=\"math-container\">$y_0$</span>, <span class=\"math-container\">$y_1$</span></p>\n<p><span class=\"math-container\">$ \\frac {\\partial^2 z} {\\partial i^2} $</span> discretised by:\n<span class=\"math-container\">$$ \\begin{bmatrix}\n1 &amp; -2 &amp; 1 \\\\\n &amp; 1 &amp; -2 &amp; 1 \\\\\n &amp; &amp; &amp; &amp; \\ddots\n\\end{bmatrix} z $$</span></p>\n<p>The problem is very sparse, and I trust that essentially no LP solvers would have any difficulty with it. HiGHS completes it quickly.</p>\n<pre class=\"lang-py prettyprint-override\"><code>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) -&gt; 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) -&gt; 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) -&gt; 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) -&gt; tuple[LinearConstraint, ...]:\n # zep &gt;= z - y: z - zep &lt;= y\n # zen &gt;= y - z: z + zen &gt;= 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) -&gt; tuple[LinearConstraint, ...]:\n # d2z/dt2 = z[i+2] - 2z[i+1] + z[i]\n # d2p &gt;= d2z/dt2: -z[i] + 2z[i+1] - z[i+2] +0 +0 + d2p &gt;= 0\n # d2n &gt;= -d2z/dt2: z[i] - 2z[i+1] + z[i+2] +0 +0 + 0 + d2n &gt;= 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) -&gt; 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.) -&gt; tuple[\n np.ndarray, tuple[LinearConstraint, ...],\n]:\n '''\n Variables:\n z, continuous unbounded (outside of ref points)\n zep, continuous, &gt;= 0, &gt;= z-y\n zen, continuous, &gt;= 0, &gt;= y-z\n d2p, n-2, continuous, &gt;= 0, &gt;= d2z/dt2\n d2n, n-2, continuous, &gt;= 0, &gt;= -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() -&gt; 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</code></pre>\n<p>Here we see that the solution does exactly what we tell it to:</p>\n<p><a href=\"https://i.sstatic.net/oTyX0oWA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/oTyX0oWA.png\" alt=\"example solution\" /></a></p>\n<p>Outside 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:</p>\n<p><a href=\"https://i.sstatic.net/cW1t1avg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/cW1t1avg.png\" alt=\"smoothing\" /></a></p>\n<p>The sparsity pattern for the problem looks like this (size reduced for visibility):</p>\n<p><a href=\"https://i.sstatic.net/UmVF5qyE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/UmVF5qyE.png\" alt=\"sparsity\" /></a></p>\n<p>Though the performance will vary based on hardware and dataset content and size, for n=1501 I see execution times of ~80 ms.</p>\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":"<p>I managed to create a prototype solver based on ADMM in MATLAB:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>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; %&lt;! Optimization variable\nvS = zeros(numInEq, 1); %&lt;! Slack variable for inequality\nvS1 = zeros(numInEq, 1); %&lt;! Preious iteration buffer\nvMu = zeros(numInEq, 1); %&lt;! Dual variable for inequality\nvNu = zeros(numEq, 1); %&lt;! 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; %&lt;! Previous iteration\n\n % Solve the Linear System\n vR = -vQ - mA.' * (paramRho * vS + vMu) + mE.' * (paramRho * vD - vNu); %&lt;! Right hand vector\n vX = sK \\ vR;\n\n % Proximal / Projection Step\n % s = -A * z with s &gt;= 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 &lt; epsAbs) &amp;&amp; (dualRes &lt; 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 &gt; paramTau) || (inv(resRatio) &gt; 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</code></pre>\n<p>I has convergence check and adaptation of the ADMM's step size parameter <span class=\"math-container\">$\\rho$</span>.<br />\nI will add mathematical formulation and a memory optimized version using Julia.</p>\n<p>On MATLAB with this naive code I could beat <code>quadprog()</code> by 30% with the same output:</p>\n<p><a href=\"https://i.sstatic.net/VC8uzUSt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/VC8uzUSt.png\" alt=\"enter image description here\" /></a></p>\n\n","answer_id":45337,"answer_text":"I managed to create a prototype solver based on ADMM in MATLAB:\n\n\n\n\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\n\n\n\n\nI has convergence check and adaptation of the ADMM's step size parameter $\\rho$.\n\nI will add mathematical formulation and a memory optimized version using Julia.\n\n\n\n\nOn MATLAB with this naive code I could beat quadprog() by 30% with the same output:\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/VC8uzUSt.png] (https://i.sstatic.net/VC8uzUSt.png)","answer_url":"https://scicomp.stackexchange.com/a/45337","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-10T16:53:59+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-10T16:53:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"62C943AA-9B1D-4A55-BEE1-9F975532FF13","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/62C943AA-9B1D-4A55-BEE1-9F975532FF13/view-source"}],"score":0,"updated_at":"2026-01-10T16:53:59+00:00"},{"answer_html":"<p>I produced an ADMM based solver which I found very efficient.</p>\n<p>The problem is given by:</p>\n<p><span class=\"math-container\">$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } &amp; \\quad &amp; \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D}^{m} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} &amp; \\quad &amp; {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n&amp; \\quad &amp; \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$</span></p>\n<p>I will use <span class=\"math-container\">$\\boldsymbol{D} = \\boldsymbol{D}^{m}$</span> to simplify notations.<br />\nThe equality constraints can be turned into matrix form and the problem becomes:</p>\n<p><span class=\"math-container\">$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } &amp; \\quad &amp; \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} &amp; \\quad &amp; \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n&amp; \\quad &amp; \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$</span></p>\n<p>The trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:</p>\n<p><span class=\"math-container\">$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } &amp; \\quad &amp; \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} &amp; \\quad &amp; \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n&amp; \\quad &amp; \\boldsymbol{A} \\boldsymbol{x} + \\boldsymbol{s} = \\boldsymbol{0} \\\\\n&amp; \\quad &amp; \\boldsymbol{s} \\geq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$</span></p>\n<p>The equality constraints are introduced by the Augmented Lagrangian:</p>\n<p><span class=\"math-container\">$$\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$$</span></p>\n<p>The steps to solve:</p>\n<ul>\n<li>Primal Update (Solve Linear System): <span class=\"math-container\">$\\boldsymbol{x}^{ \\left( k + 1 \\right)} = {\\left( \\boldsymbol{I} + \\lambda \\boldsymbol{D}^{\\top} \\boldsymbol{D} + \\rho \\boldsymbol{A}^{\\top} \\boldsymbol{A} + \\rho\\boldsymbol{E}^{\\top} \\boldsymbol{E} \\right)}^{-1} \\left( \\boldsymbol{y} - \\boldsymbol{A}^{\\top} \\left( \\rho \\boldsymbol{s}^{\\left( k \\right)} + \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) + \\boldsymbol{E}^{\\top} \\left( \\rho \\boldsymbol{d} - \\boldsymbol{\\nu}^{\\left( k \\right)} \\right) \\right)$</span>.</li>\n<li>Slack Update (Non Negative LS): <span class=\"math-container\">$\\boldsymbol{s}^{ \\left( k + 1 \\right)} = \\max \\left( \\boldsymbol{0}, - \\boldsymbol{A} \\boldsymbol{x}^{\\left( k + 1 \\right)} - {\\rho}^{-1} \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$</span>.</li>\n<li>Dual Update (Gradient Ascent) for <span class=\"math-container\">$\\boldsymbol{\\mu}$</span>: <span class=\"math-container\">$\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\rho \\left( \\boldsymbol{A} \\boldsymbol{x}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} \\right)$</span>.</li>\n<li>Dual Update (Gradient Ascent) for <span class=\"math-container\">$\\boldsymbol{\\nu}$</span>: <span class=\"math-container\">$\\boldsymbol{\\nu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\nu}^{\\left( k \\right)} + \\rho \\left( \\boldsymbol{E} \\boldsymbol{x}^{\\left( k + 1 \\right)} - \\boldsymbol{d} \\right)$</span>.</li>\n</ul>\n<p>The stopping condition is when both residuals are below a threshold:</p>\n<ul>\n<li>Primal Residual: <span class=\"math-container\">${r}^{\\left( k \\right)} = {\\left\\| \\boldsymbol{A} \\boldsymbol{x}^{\\left( k \\right)} + \\boldsymbol{s}^{\\left( k \\right)} \\right\\|}_{\\infty}$</span>.</li>\n<li>Dual Residual (OSQP Style): <span class=\"math-container\">${s}^{\\left( k \\right)} = {\\left\\| \\rho \\boldsymbol{A} \\left( \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{s}^{\\left( k - 1 \\right)} \\right) \\right\\|}_{\\infty}$</span>.</li>\n</ul>\n<p>The use of the infinity norm decouples the dimension of the problem from the thresholds.</p>\n<p>I also used OSQP style update of the <span class=\"math-container\">$\\rho$</span> parameter to accelerate convergence: <span class=\"math-container\">${\\rho}^{\\left( k \\right)} = {\\rho}^{\\left( k - 1 \\right)} \\sqrt{ \\frac{ {r}^{\\left( k \\right)} }{ {s}^{\\left( k \\right)} } }$</span>.</p>\n<p>I implemented all in Julia and compared to the <a href=\"https://github.com/embotech/ecos\" rel=\"nofollow noreferrer\">ECOS</a> / <a href=\"https://github.com/cvxgrp/scs\" rel=\"nofollow noreferrer\">SCS</a> solvers wrapped by <a href=\"https://github.com/jump-dev/Convex.jl\" rel=\"nofollow noreferrer\"><code>Convex.jl</code></a>.</p>\n<p><a href=\"https://i.sstatic.net/f5YcjFm6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/f5YcjFm6.png\" alt=\"enter image description here\" /></a></p>\n<p>Run Times:</p>\n<ul>\n<li>ECOS</li>\n</ul>\n<pre><code>BenchmarkTools.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 &lt;\n\n Memory estimate: 806.21 KiB, allocs estimate: 7886.\n</code></pre>\n<ul>\n<li>SCS</li>\n</ul>\n<pre><code>BenchmarkTools.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 &lt;\n\n Memory estimate: 694.24 KiB, allocs estimate: 7998.\n</code></pre>\n<ul>\n<li>ADMM (My code):</li>\n</ul>\n<pre><code>BenchmarkTools.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 &lt;\n\n Memory estimate: 874.89 KiB, allocs estimate: 1089.\n</code></pre>\n<p>The ADMM method is an order of magnitude faster than the generic solvers.<br />\nIt can be greatly improved as it designed for arbitrary matrix <span class=\"math-container\">$\\boldsymbol{E}$</span>. It can be farther optimized for the case of equality.</p>\n<hr />\n<p>The code is available on my <a href=\"https://github.com/RoyiAvital/StackExchangeCodes\" rel=\"nofollow noreferrer\">StackExchange Code GitHub Repository</a> (Look at the <code>ComputationalScience\\Q45334</code> folder).</p>\n","answer_id":45341,"answer_text":"I produced an ADMM based solver which I found very efficient.\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}^{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$$\n\n\n\n\nI will use $\\boldsymbol{D} = \\boldsymbol{D}^{m}$ to simplify notations.\n\nThe equality constraints can be turned into matrix form and the problem becomes:\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 & \\boldsymbol{E} \\boldsymbol{x} = \\boldsymbol{d} \\\\\n& \\quad & \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$\n\n\n\n\nThe trick to utilize the ADMM framework is to introduce a slack variable to handle the inequality constraint:\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 & \\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$$\n\n\n\n\nThe equality constraints are introduced by the Augmented Lagrangian:\n\n\n\n\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$$\n\n\n\n\nThe steps to solve:\n\n\n\n\n\nPrimal Update (Solve Linear System): $\\boldsymbol{x}^{ \\left( k + 1 \\right)} = {\\left( \\boldsymbol{I} + \\lambda \\boldsymbol{D}^{\\top} \\boldsymbol{D} + \\rho \\boldsymbol{A}^{\\top} \\boldsymbol{A} + \\rho\\boldsymbol{E}^{\\top} \\boldsymbol{E} \\right)}^{-1} \\left( \\boldsymbol{y} - \\boldsymbol{A}^{\\top} \\left( \\rho \\boldsymbol{s}^{\\left( k \\right)} + \\boldsymbol{\\mu}^{\\left( k \\right)} \\right) + \\boldsymbol{E}^{\\top} \\left( \\rho \\boldsymbol{d} - \\boldsymbol{\\nu}^{\\left( k \\right)} \\right) \\right)$.\n\n\n\n\nSlack Update (Non Negative LS): $\\boldsymbol{s}^{ \\left( k + 1 \\right)} = \\max \\left( \\boldsymbol{0}, - \\boldsymbol{A} \\boldsymbol{x}^{\\left( k + 1 \\right)} - {\\rho}^{-1} \\boldsymbol{\\mu}^{\\left( k \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent) for $\\boldsymbol{\\mu}$: $\\boldsymbol{\\mu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\mu}^{\\left( k \\right)} + \\rho \\left( \\boldsymbol{A} \\boldsymbol{x}^{\\left( k + 1 \\right)} + \\boldsymbol{s}^{\\left( k + 1 \\right)} \\right)$.\n\n\n\n\nDual Update (Gradient Ascent) for $\\boldsymbol{\\nu}$: $\\boldsymbol{\\nu}^{\\left( k + 1 \\right)} = \\boldsymbol{\\nu}^{\\left( k \\right)} + \\rho \\left( \\boldsymbol{E} \\boldsymbol{x}^{\\left( k + 1 \\right)} - \\boldsymbol{d} \\right)$.\n\n\n\n\n\nThe stopping condition is when both residuals are below a threshold:\n\n\n\n\n\nPrimal Residual: ${r}^{\\left( k \\right)} = {\\left\\| \\boldsymbol{A} \\boldsymbol{x}^{\\left( k \\right)} + \\boldsymbol{s}^{\\left( k \\right)} \\right\\|}_{\\infty}$.\n\n\n\n\nDual Residual (OSQP Style): ${s}^{\\left( k \\right)} = {\\left\\| \\rho \\boldsymbol{A} \\left( \\boldsymbol{s}^{\\left( k \\right)} - \\boldsymbol{s}^{\\left( k - 1 \\right)} \\right) \\right\\|}_{\\infty}$.\n\n\n\n\n\nThe use of the infinity norm decouples the dimension of the problem from the thresholds.\n\n\n\n\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)} } }$.\n\n\n\n\nI implemented all in Julia and compared to the ECOS (https://github.com/embotech/ecos) / SCS (https://github.com/cvxgrp/scs) solvers wrapped by Convex.jl (https://github.com/jump-dev/Convex.jl).\n\n\n\n\n[image: enter image description here; source: https://i.sstatic.net/f5YcjFm6.png] (https://i.sstatic.net/f5YcjFm6.png)\n\n\n\n\nRun Times:\n\n\n\n\n\nECOS\n\n\n\n\n\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\n\n\n\n\n\nSCS\n\n\n\n\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\n\n\n\n\n\nADMM (My code):\n\n\n\n\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\n\n\n\n\nThe ADMM method is an order of magnitude faster than the generic solvers.\n\nIt can be greatly improved as it designed for arbitrary matrix $\\boldsymbol{E}$. It can be farther optimized for the case of equality.\n\n\n\n\n\n\n\nThe code is available on my StackExchange Code GitHub Repository (https://github.com/RoyiAvital/StackExchangeCodes) (Look at the ComputationalScience\\Q45334 folder).","answer_url":"https://scicomp.stackexchange.com/a/45341","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-17T09:49:49+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-17T09:49:49+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"00755B30-2CCE-4266-8BA0-1A21879D0A39","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/00755B30-2CCE-4266-8BA0-1A21879D0A39/view-source"}],"score":2,"updated_at":"2026-01-17T09:49:49+00:00"},{"answer_html":"<p>Another formulation take advantage of the equality constraint to make the problem formulation smaller.</p>\n<p>The problem is given by:</p>\n<p><span class=\"math-container\">$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x} } &amp; \\quad &amp; \\frac{1}{2} \\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|_{2}^{2} + \\frac{\\lambda}{2} {\\left\\| \\boldsymbol{D} \\boldsymbol{x} \\right\\|}_{2}^{2} \\\\\n\\text{subject to} &amp; \\quad &amp; {x}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n&amp; \\quad &amp; \\boldsymbol{A} \\boldsymbol{x} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$</span></p>\n<p>Let <span class=\"math-container\">$\\mathcal{J} = \\left\\{ 1, 2, \\ldots, n \\right\\} \\setminus \\mathcal{I}$</span> then define:</p>\n<p><span class=\"math-container\">$$ \\boldsymbol{x} = \\begin{bmatrix} \\boldsymbol{x}_{\\mathcal{J}} \\\\ \\boldsymbol{x}_{\\mathcal{I}} \\end{bmatrix}, \\; \\boldsymbol{A} = \\begin{bmatrix} \\boldsymbol{A}_{\\mathcal{J}} &amp;&amp; \\boldsymbol{A}_{\\mathcal{I}} \\end{bmatrix}, \\boldsymbol{D} = \\begin{bmatrix} \\boldsymbol{D}_{\\mathcal{J}} &amp;&amp; \\boldsymbol{D}_{\\mathcal{I}} \\end{bmatrix}$$</span></p>\n<p>Then the above can be formulated as:</p>\n<p><span class=\"math-container\">$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{x}_{\\mathcal{J}} } &amp; \\quad &amp; \\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} &amp; \\quad &amp; \\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} \\leq \\boldsymbol{b} \\\\\n\\end{alignat*}\n$$</span></p>\n<p>Where <span class=\"math-container\">$\\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}}$</span>.</p>\n<p>This formulation reduces the number of constraints to handle.<br />\nThe inequality is treated by introducing a slack variable <span class=\"math-container\">$\\boldsymbol{s} \\geq \\boldsymbol{0}$</span> such that <span class=\"math-container\">$\\boldsymbol{A}_{\\mathcal{J}} \\boldsymbol{x}_{\\mathcal{J}} + \\boldsymbol{s} = \\boldsymbol{b}$</span>.</p>\n<p>The Augmented Lagrangian (Scaled form) is given by:</p>\n<p><span class=\"math-container\">$$\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$$</span></p>\n<p>The steps to solve:</p>\n<ul>\n<li>Primal Update (Solve Linear System): <span class=\"math-container\">$\\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)$</span>.</li>\n<li>Slack Update (Non Negative LS / Projection): <span class=\"math-container\">$\\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)$</span>.</li>\n<li>Dual Update (Gradient Ascent): <span class=\"math-container\">$\\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)$</span>.</li>\n</ul>\n<p>The rest is similar to above with the needed adjustments for the residuals calculations.</p>\n<p>This implementation reduced another 40 [Micro Sec] of the run time.</p>\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"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","content_license":"CC BY-SA 4.0","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"}],"source_url":"https://scicomp.stackexchange.com/a/45335"},{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","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-10T16:53:59+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"62C943AA-9B1D-4A55-BEE1-9F975532FF13","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/62C943AA-9B1D-4A55-BEE1-9F975532FF13/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45337"},{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","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-17T09:49:49+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"00755B30-2CCE-4266-8BA0-1A21879D0A39","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/00755B30-2CCE-4266-8BA0-1A21879D0A39/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45341"},{"author":"Royi","author_url":"https://scicomp.stackexchange.com/users/7951/royi","content_license":"CC BY-SA 4.0","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"}],"source_url":"https://scicomp.stackexchange.com/a/45342"}],"question_author":"Royi","question_author_url":"https://scicomp.stackexchange.com/users/7951/royi"},"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","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; %<! 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","post_id":45337,"sha256":"535fd63b99697fb569289a64746583e07c5d7d903898e20406ca04bde8aa5841","source_url":"https://scicomp.stackexchange.com/a/45337"},{"block_index":0,"code_text":"BenchmarkTools.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","post_id":45341,"sha256":"0b2e3243787f36b7a4743ea4db41186e03b8103ddb44694d08359b124a402f78","source_url":"https://scicomp.stackexchange.com/a/45341"},{"block_index":1,"code_text":"BenchmarkTools.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","post_id":45341,"sha256":"71a1c78a3d594c714e47b549671ad205a39c588397342cd1222d7f0374ee212d","source_url":"https://scicomp.stackexchange.com/a/45341"},{"block_index":2,"code_text":"BenchmarkTools.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","post_id":45341,"sha256":"cc617c32c3d824167c364bca08e08e70d29fa3d5e2cbafd454d004adf007d6dd","source_url":"https://scicomp.stackexchange.com/a/45341"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"15b9f73a0305336f8096de53cbd97ad5337151fb87b189a74bb035a849536f87","id":"SCT-446896929ffe977e1e13a64c","language":null,"library_or_tool":null,"problem_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.","provenance":{"original_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"},"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_commit":null,"source_data_file":"native_scicomp_source.jsonl","source_dataset":"RegalFire/Scientific-Native-Scicomp","source_license":"CC BY-SA 4.0","source_record_id":"45334","source_record_sha256":"359b817cdb7eb4f25a65d862cad899ed03718f46a543f10119a7061fcbb05a16","source_url":"https://scicomp.stackexchange.com/questions/45334/solving-regularized-least-squares-with-linear-equality-and-linear-inequality-con","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>Let a 1D curve defined by <span class=\"math-container\">$\\left\\{ {y}_{1}, {y}_{2}, \\ldots, {y}_{n} \\right\\}$</span> sampled on a uniform grid.</p>\n<p>I want to smooth the curve with the following properties:</p>\n<ol>\n<li>The result, <span class=\"math-container\">$\\left\\{ {z}_{1}, {z}_{2}, \\ldots {z}_{n} \\right\\}$</span> should be smooth like Spline based method.</li>\n<li>For a set of indices <span class=\"math-container\">$\\mathcal{I}$</span> the smoothed curve must go through the reference point, namely <span class=\"math-container\">${z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I}$</span>.</li>\n<li>The smoothed values between 2 reference points must be monotonic.</li>\n</ol>\n<p>I came up with the following model:</p>\n<p><span class=\"math-container\">$$\n\\begin{alignat*}{3}\n\\arg \\min_{ \\boldsymbol{z} } &amp; \\quad &amp; \\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} &amp; \\quad &amp; {z}_{i} = {y}_{i} \\; \\forall i \\in \\mathcal{I} \\\\\n&amp; \\quad &amp; \\boldsymbol{A} \\boldsymbol{z} \\leq \\boldsymbol{0} \\\\\n\\end{alignat*}\n$$</span></p>\n<p>Where <span class=\"math-container\">$\\boldsymbol{D}^{m}$</span> is the <span class=\"math-container\">$m$</span> -th derivative operator.</p>\n<p>I am looking for a fast way to solve the problem for the case of 50-1500 samples.</p>\n<p>I rather not use black box Quadratic Programming solvers but design a simple to implement iterative method.</p>\n","question_title":"Solving Regularized Least Squares with Linear Equality and Linear Inequality Constraints for Curve Smoothing","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45334/solving-regularized-least-squares-with-linear-equality-and-linear-inequality-con","split":"test"}
{"accepted_answer":{"answer_html":"<p>You are &quot;dealiasing&quot; in real space, not frequency space, but real space got no aliasing. You are effectively adding a term <code>(Au)**3</code> 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.</p>\n<p>Let <code>ufft</code> be your current solution in frequency space, then:</p>\n<pre><code>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</code></pre>\n<p>I'm not sure how you got sensible looking solutions with your original code since that <code>(Au)**3</code> 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 &quot;Grain boundary velocity&quot;. Depending on what your goals are you might also want to use pre-made phase-field software.</p>\n","answer_id":45511,"answer_text":"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.\n\n\n\n\nLet ufft be your current solution in frequency space, then:\n\n\n\n\nureal = 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\n\n\n\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.","answer_url":"https://scicomp.stackexchange.com/a/45511","author":"niemc","author_url":"https://scicomp.stackexchange.com/users/50632/niemc","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-06T00:18: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":45510,"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":"2026-08-06T00:18:52+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2/view-source"}],"score":2,"updated_at":"2026-08-06T00:18:52+00:00"},"answer_scores":[{"answer_id":45511,"score":2}],"answers":[{"answer_html":"<p>You are &quot;dealiasing&quot; in real space, not frequency space, but real space got no aliasing. You are effectively adding a term <code>(Au)**3</code> 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.</p>\n<p>Let <code>ufft</code> be your current solution in frequency space, then:</p>\n<pre><code>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</code></pre>\n<p>I'm not sure how you got sensible looking solutions with your original code since that <code>(Au)**3</code> 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 &quot;Grain boundary velocity&quot;. Depending on what your goals are you might also want to use pre-made phase-field software.</p>\n","answer_id":45511,"answer_text":"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.\n\n\n\n\nLet ufft be your current solution in frequency space, then:\n\n\n\n\nureal = 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\n\n\n\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.","answer_url":"https://scicomp.stackexchange.com/a/45511","author":"niemc","author_url":"https://scicomp.stackexchange.com/users/50632/niemc","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-06T00:18: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":45510,"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":"2026-08-06T00:18:52+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2/view-source"}],"score":2,"updated_at":"2026-08-06T00:18:52+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"niemc","author_url":"https://scicomp.stackexchange.com/users/50632/niemc","content_license":"CC BY-SA 4.0","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":"2026-08-06T00:18:52+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/AE5E3A3C-3E50-49C8-BAD9-6B8FD9A90EB2/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45511"}],"question_author":"Manav Jalan","question_author_url":"https://scicomp.stackexchange.com/users/57116/manav-jalan"},"code_blocks":[{"block_index":0,"code_text":"# 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","post_id":"scicomp:45510","sha256":"4b699a38ac0a60297f7571f8542df84f21ad9915d6304dbef03624cde7723cf0","source_url":"https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio"},{"block_index":0,"code_text":"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","post_id":45511,"sha256":"bf6e3c4e955925e698cefc2a1209b1e9e5d424546243235be7f9469e57224119","source_url":"https://scicomp.stackexchange.com/a/45511"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"1f34eebb11d832f228fad67a66d7d7358a50b61b08a200479243f33dd3b85141","id":"SCT-55ab89b249a9d7536656f38b","language":null,"library_or_tool":null,"problem_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.","provenance":{"original_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"},"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_commit":null,"source_data_file":"native_scicomp_source.jsonl","source_dataset":"RegalFire/Scientific-Native-Scicomp","source_license":"CC BY-SA 4.0","source_record_id":"45510","source_record_sha256":"6440d51489c2af8c0b1d243f5d9680747e3091a326007a87f31b5ea3b5179b92","source_url":"https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>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: <a href=\"https://open.umich.edu/sites/default/files/downloads/2012-parallel-spectral-numerical-methods.pdf\" rel=\"nofollow noreferrer\">Parallel Spectral Numerical Methods</a>. Accordingly, I have implemented the scheme as follows::</p>\n<pre><code># Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) &lt; k_cutoff) &amp; (np.abs(k_y) &lt; 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</code></pre>\n<p>The 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.</p>\n","question_title":"Allen Cahn Psuedospectral solver blowup even after reaching steady state solution","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45510/allen-cahn-psuedospectral-solver-blowup-even-after-reaching-steady-state-solutio","split":"test"}