RegalFire's picture
RegalFire V3: independently validated source-derived release
a3a7873 verified
Raw History Blame Contribute Delete
142 kB
{"accepted_answer":null,"answer_scores":[{"answer_id":112804,"score":5}],"answers":[{"answer_html":"<p>I know nothing about drug databases, but am familiar with Kegg. As far as I can see from the paper (and I may be wrong) The drug target database would contain the names of enzymes, the activity of which is affected by drugs. So the problem would seem to be to identify so-called Kegg ‘pathways’ in which these target enzymes occur.</p>\n<p>(I use the adjective “so-called” as Kegg pathways are not generally what a biochemist would regard as a pathway, but areas of metabolism. However this would not matter if all one is trying to do is find a correlation.)</p>\n<p>The poster would seem, therefore, to need to download a list of enzymes for each Kegg pathway. At one time all the Kegg information was available free of charge (I downloaded a considerable amount — although not the enzymes — to construct a relational database). However now one needs to purchase a license to do this — presumably what the authors of the paper did — at a cost of over $1000 pa.</p>\n<p>Unless one has grant funding or is independently wealthy, it would seem to be necessary to explore alternatives, such as MetaCyc (<a href=\"https://metacyc.org\" rel=\"nofollow noreferrer\">https://metacyc.org</a>).</p>\n<p><strong>Postscript</strong>\nThe addendum from the poster shows the UniProt IDs for the targets of the drug. These can be converted to Kegg IDs using the conversion tool on the Kegg site (<a href=\"https://www.genome.jp/kegg/tool/conv_id.html\" rel=\"nofollow noreferrer\">https://www.genome.jp/kegg/tool/conv_id.html</a>). The XML tag entitled “pathway” is not equivalent to a Kegg metabolic pathway as such, although the example seems to consist of proteins involved in blood clotting. If my interpretation is correct, it would be irrelevant to the procedure I suggest. However the original paper is sufficiently vague that I cannot be sure.</p>\n","answer_id":112804,"answer_text":"I know nothing about drug databases, but am familiar with Kegg. As far as I can see from the paper (and I may be wrong) The drug target database would contain the names of enzymes, the activity of which is affected by drugs. So the problem would seem to be to identify so-called Kegg ‘pathways’ in which these target enzymes occur.\n\n\n\n\n(I use the adjective “so-called” as Kegg pathways are not generally what a biochemist would regard as a pathway, but areas of metabolism. However this would not matter if all one is trying to do is find a correlation.)\n\n\n\n\nThe poster would seem, therefore, to need to download a list of enzymes for each Kegg pathway. At one time all the Kegg information was available free of charge (I downloaded a considerable amount — although not the enzymes — to construct a relational database). However now one needs to purchase a license to do this — presumably what the authors of the paper did — at a cost of over $1000 pa.\n\n\n\n\nUnless one has grant funding or is independently wealthy, it would seem to be necessary to explore alternatives, such as MetaCyc (https://metacyc.org (https://metacyc.org)).\n\n\n\n\nPostscript\nThe addendum from the poster shows the UniProt IDs for the targets of the drug. These can be converted to Kegg IDs using the conversion tool on the Kegg site (https://www.genome.jp/kegg/tool/conv_id.html (https://www.genome.jp/kegg/tool/conv_id.html)). The XML tag entitled “pathway” is not equivalent to a Kegg metabolic pathway as such, although the example seems to consist of proteins involved in blood clotting. If my interpretation is correct, it would be irrelevant to the procedure I suggest. However the original paper is sufficiently vague that I cannot be sure.","answer_url":"https://biology.stackexchange.com/a/112804","author":"David","author_url":"https://biology.stackexchange.com/users/22057/david","content_license":"CC BY-SA 4.0","created_at":"2023-08-13T11:37:13+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:38.885561+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/a145de97eabc007745b45919875489a41261075cbdf33d916d9640ba4ad0bd35_0.json","raw_sha256":"e7d8d4315eef8e039a452d2811869cbe305575c6ff8a6bef8f80d6dfb58c5bfd","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/112982;112980;112979;112977;112972;112967;112962;112956;112952;112948;112941;112938;112937;112936;112927;112925;112923;112919;112909;112905;112904;112898;112895;112893;112884;112881;112880;112879;112873;112872;112870;112869;112867;112850;112849;112848;112841;112835;112831;112824;112818;112811;112808;112807;112790;112789;112785;112777;112773;112770;112762;112759;112757;112756;112746;112739;112738;112737;112731;112705;112703;112700;112699;112698;112693;112691;112687;112685;112677;112671;112667;112663;112659;112653;112647;112646;112645;112636;112625;112621;112615;112614;112613;112610;112598;112593;112592;112586;112580;112575;112574;112564;112558;112552;112550;112549;112544;112539;112535;112531/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":112789,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-13T11:37:13+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"2D881A87-9785-460D-8B6A-4D609910C727","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/2D881A87-9785-460D-8B6A-4D609910C727/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-17T22:21:55+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"7E664EA3-F130-4C17-B518-C112CBD595B8","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/7E664EA3-F130-4C17-B518-C112CBD595B8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-18T07:26:03+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"2D4BC5F7-1B1B-44D3-BB31-EB109B8535CB","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/2D4BC5F7-1B1B-44D3-BB31-EB109B8535CB/view-source"}],"score":5}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"David","author_url":"https://biology.stackexchange.com/users/22057/david","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-13T11:37:13+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"2D881A87-9785-460D-8B6A-4D609910C727","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/2D881A87-9785-460D-8B6A-4D609910C727/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-17T22:21:55+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"7E664EA3-F130-4C17-B518-C112CBD595B8","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/7E664EA3-F130-4C17-B518-C112CBD595B8/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"David","profile_url":"https://biology.stackexchange.com/users/22057/david","user_type":"registered"},"created_at":"2023-08-18T07:26:03+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"2D4BC5F7-1B1B-44D3-BB31-EB109B8535CB","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/2D4BC5F7-1B1B-44D3-BB31-EB109B8535CB/view-source"}],"source_url":"https://biology.stackexchange.com/a/112804"}],"question_author":"Orca","question_author_url":"https://biology.stackexchange.com/users/76494/orca"},"code_blocks":[{"block_index":0,"code_text":"<pathways>\n <pathway>\n <smpdb-id>SMP0000278</smpdb-id>\n <name>Lepirudin Action Pathway</name>\n <category>drug_action</category>\n <drugs>\n <drug>\n <drugbank-id>DB00001</drugbank-id>\n <name>Lepirudin</name>\n </drug>\n <drug>\n <drugbank-id>DB01022</drugbank-id>\n <name>Phylloquinone</name>\n </drug>\n <drug>\n <drugbank-id>DB01373</drugbank-id>\n <name>Calcium</name>\n </drug>\n </drugs>\n <enzymes>\n <uniprot-id>P00734</uniprot-id>\n <uniprot-id>P00748</uniprot-id>\n <uniprot-id>P02452</uniprot-id>\n <uniprot-id>P03952</uniprot-id>\n <uniprot-id>P03951</uniprot-id>\n <uniprot-id>P00740</uniprot-id>\n <uniprot-id>P00451</uniprot-id>\n <uniprot-id>P12259</uniprot-id>\n <uniprot-id>P00742</uniprot-id>\n <uniprot-id>P02671</uniprot-id>\n <uniprot-id>P02675</uniprot-id>\n <uniprot-id>P02679</uniprot-id>\n <uniprot-id>P00488</uniprot-id>\n <uniprot-id>P05160</uniprot-id>\n <uniprot-id>P00747</uniprot-id>\n <uniprot-id>P00750</uniprot-id>\n <uniprot-id>P08709</uniprot-id>\n <uniprot-id>P13726</uniprot-id>\n <uniprot-id>Q9BQB6</uniprot-id>\n <uniprot-id>P38435</uniprot-id>\n </enzymes>\n </pathway>\n </pathways>\n\n```\n","post_id":"112789","sha256":"4452dea3b66a2c29df5a54e5e802e54d6339b7f0a59f86f15142323a44138d31","source_url":"https://biology.stackexchange.com/questions/112789/how-to-generate-pathway-fingerprints-of-drugs"}],"content_license":"CC BY-SA 4.0","domain":"biology","error_text_if_explicit":null,"group_id":"21341a8f8da58f78f0df843bca6c30524caaad2ffd24c0988a87895e0f6d2c2c","id":"SCT-888cccfd7708642b5b451223","language":null,"library_or_tool":null,"problem_text":"I have studied a paper that constructs the pathway fingerprint of a drug, which has a vector of $0$ and $1$, and they compare the pathway fingerprint using a similarity measure to assess how similar the drugs are.\n\n\n\n\nBut I don't know where can I download pathways and how to generate their fingerprint vector to evaluate them. I checked KEGG website (https://www.genome.jp/kegg/) but could not find anything there to download. The paper can be downloaded from: https://pubmed.ncbi.nlm.nih.gov/22426982/ (https://pubmed.ncbi.nlm.nih.gov/22426982/)\n\n\n\n\nI really appreciate answers that can help me to solve the problem.\n\n\n\n\nUpdate\nSince i am not familiar with DrugBank and biology science, when I parsed the xml file of drugbank, I find a tag with name pathway . But i am not sure that do these elements show the pathway of drug or not? Is it possible to use them to construct the pathway fingerprint vector for drugs? what does <uniprot-id>P00734</uniprot-id> mean?\n\n\n\n\nthis is the content of pathway tag for Lepirudin:\n\n\n\n\n<pathways>\n <pathway>\n <smpdb-id>SMP0000278</smpdb-id>\n <name>Lepirudin Action Pathway</name>\n <category>drug_action</category>\n <drugs>\n <drug>\n <drugbank-id>DB00001</drugbank-id>\n <name>Lepirudin</name>\n </drug>\n <drug>\n <drugbank-id>DB01022</drugbank-id>\n <name>Phylloquinone</name>\n </drug>\n <drug>\n <drugbank-id>DB01373</drugbank-id>\n <name>Calcium</name>\n </drug>\n </drugs>\n <enzymes>\n <uniprot-id>P00734</uniprot-id>\n <uniprot-id>P00748</uniprot-id>\n <uniprot-id>P02452</uniprot-id>\n <uniprot-id>P03952</uniprot-id>\n <uniprot-id>P03951</uniprot-id>\n <uniprot-id>P00740</uniprot-id>\n <uniprot-id>P00451</uniprot-id>\n <uniprot-id>P12259</uniprot-id>\n <uniprot-id>P00742</uniprot-id>\n <uniprot-id>P02671</uniprot-id>\n <uniprot-id>P02675</uniprot-id>\n <uniprot-id>P02679</uniprot-id>\n <uniprot-id>P00488</uniprot-id>\n <uniprot-id>P05160</uniprot-id>\n <uniprot-id>P00747</uniprot-id>\n <uniprot-id>P00750</uniprot-id>\n <uniprot-id>P08709</uniprot-id>\n <uniprot-id>P13726</uniprot-id>\n <uniprot-id>Q9BQB6</uniprot-id>\n <uniprot-id>P38435</uniprot-id>\n </enzymes>\n </pathway>\n </pathways>\n\n```","provenance":{"original_provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:03:12.794960+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/01e5186067e30dc1b8d7a145670ab7edd6b017797b271a481af8b7b7f55f13c2_0.json","raw_sha256":"6c3960de7e1d3d7920bb88d02e2184614c219b391f39d9bddc2a582fdc9a71e7","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/search/advanced?answers=1&filter=withbody&order=desc&page=10&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":"Orca","profile_url":"https://biology.stackexchange.com/users/76494/orca","user_type":"registered"},"created_at":"2023-08-11T06:06:32+00:00","raw_file":"raw/codex_api_v1/fe6e1ab1e4f14040deb1423c04616e4dd0e7de39b583b42e88a31f79f9375e98_1790824028764975800_0.json","raw_sha256":"08e023ccc811ec000989abb19f483814e44277588eeabf130aa5dbaf177079bf","revision_guid":"98663075-01EA-4309-B06F-A662D694541F","revision_number":1,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/98663075-01EA-4309-B06F-A662D694541F/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Brendan Darrer","profile_url":"https://biology.stackexchange.com/users/35682/brendan-darrer","user_type":"registered"},"created_at":"2023-08-12T00:08:28+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"1A1830DF-479C-4EA6-8FAB-7D151F12D14C","revision_number":2,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/1A1830DF-479C-4EA6-8FAB-7D151F12D14C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"MattDMo","profile_url":"https://biology.stackexchange.com/users/948/mattdmo","user_type":"registered"},"created_at":"2023-08-12T00:08:28+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"797A7A2D-66A0-42C2-8856-C45C3E78810C","revision_number":3,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/797A7A2D-66A0-42C2-8856-C45C3E78810C/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Orca","profile_url":"https://biology.stackexchange.com/users/76494/orca","user_type":"registered"},"created_at":"2023-08-15T09:50:04+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"7F3B7812-28EA-4085-9361-2690329DB2A0","revision_number":4,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/7F3B7812-28EA-4085-9361-2690329DB2A0/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Orca","profile_url":"https://biology.stackexchange.com/users/76494/orca","user_type":"registered"},"created_at":"2023-08-15T10:09:44+00:00","raw_file":"raw/codex_api_v1/9b8fea4e5df4051aa25c1aa90b42eca7481ee703f92ba25aeabed3d0b53e7a04_1790824026598483100_0.json","raw_sha256":"f252fc1b154815b8794116efb3b685202eda8dddb2cd870ae32ee5e82716c300","revision_guid":"51E7AEE3-B9D6-4FE6-AA59-BD33BD98B508","revision_number":5,"revision_type":"single_user","revision_url":"https://biology.stackexchange.com/revisions/51E7AEE3-B9D6-4FE6-AA59-BD33BD98B508/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":"112789","source_record_sha256":"685fe6af1a44935ae67045a2635453e5e1c3363ca9a71cc98f94fdada045bbca","source_url":"https://biology.stackexchange.com/questions/112789/how-to-generate-pathway-fingerprints-of-drugs","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>I have studied a paper that constructs the pathway fingerprint of a drug, which has a vector of <span class=\"math-container\">$0$</span> and <span class=\"math-container\">$1$</span>, and they compare the pathway fingerprint using a similarity measure to assess how similar the drugs are.</p>\n<p>But I don't know where can I download pathways and how to generate their fingerprint vector to evaluate them. I checked <a href=\"https://www.genome.jp/kegg/\" rel=\"nofollow noreferrer\">KEGG website</a> but could not find anything there to download. The paper can be downloaded from: <a href=\"https://pubmed.ncbi.nlm.nih.gov/22426982/\" rel=\"nofollow noreferrer\">https://pubmed.ncbi.nlm.nih.gov/22426982/</a></p>\n<p>I really appreciate answers that can help me to solve the problem.</p>\n<p><strong>Update</strong>\nSince i am not familiar with DrugBank and biology science, when I parsed the xml file of drugbank, I find a tag with name <code>pathway</code> . But i am not sure that do these elements show the pathway of drug or not? Is it possible to use them to construct the pathway fingerprint vector for drugs? what does <code>&lt;uniprot-id&gt;P00734&lt;/uniprot-id&gt;</code> mean?</p>\n<p>this is the content of <code>pathway</code> tag for Lepirudin:</p>\n<pre><code>&lt;pathways&gt;\n &lt;pathway&gt;\n &lt;smpdb-id&gt;SMP0000278&lt;/smpdb-id&gt;\n &lt;name&gt;Lepirudin Action Pathway&lt;/name&gt;\n &lt;category&gt;drug_action&lt;/category&gt;\n &lt;drugs&gt;\n &lt;drug&gt;\n &lt;drugbank-id&gt;DB00001&lt;/drugbank-id&gt;\n &lt;name&gt;Lepirudin&lt;/name&gt;\n &lt;/drug&gt;\n &lt;drug&gt;\n &lt;drugbank-id&gt;DB01022&lt;/drugbank-id&gt;\n &lt;name&gt;Phylloquinone&lt;/name&gt;\n &lt;/drug&gt;\n &lt;drug&gt;\n &lt;drugbank-id&gt;DB01373&lt;/drugbank-id&gt;\n &lt;name&gt;Calcium&lt;/name&gt;\n &lt;/drug&gt;\n &lt;/drugs&gt;\n &lt;enzymes&gt;\n &lt;uniprot-id&gt;P00734&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P00748&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P02452&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P03952&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P03951&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P00740&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P00451&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P12259&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P00742&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P02671&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P02675&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P02679&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P00488&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P05160&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P00747&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P00750&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P08709&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P13726&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;Q9BQB6&lt;/uniprot-id&gt;\n &lt;uniprot-id&gt;P38435&lt;/uniprot-id&gt;\n &lt;/enzymes&gt;\n &lt;/pathway&gt;\n &lt;/pathways&gt;\n\n<span class=\"math-container\">```</span>\n</code></pre>\n","question_title":"How to generate pathway fingerprints of drugs?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://biology.stackexchange.com/questions/112789/how-to-generate-pathway-fingerprints-of-drugs","split":"holdout"}
{"accepted_answer":null,"answer_scores":[{"answer_id":676936,"score":5}],"answers":[{"answer_html":"<blockquote>\n<p>is trying to use all the data a flawed concept to begin with?</p>\n</blockquote>\n<p>No. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are &quot;missing completely at random&quot; (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.</p>\n<blockquote>\n<p>is this even a valid approach to begin with...?</p>\n</blockquote>\n<p>Your most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.</p>\n<blockquote>\n<p>what is the &quot;best&quot; approach?</p>\n</blockquote>\n<p>For MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.</p>\n<p>A standard general approach is <a href=\"https://stats.stackexchange.com/tags/multiple-imputation/info\">multiple imputation</a>. Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model <em>per se</em>) to estimate the missing data <em>values</em> themselves.</p>\n<p>A single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute <em>multiple complete data sets</em> that draw from the <em>distributions</em> of the imputed values. You fit your ultimate regression model on <em>each</em> of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.</p>\n<p>Stef van Buuren's <a href=\"https://stefvanbuuren.name/fimd/\" rel=\"nofollow noreferrer\">Flexible Imputation of Missing Data</a> is a comprehensive guide to the process, which is implemented in his R <a href=\"https://cran.r-project.org/package=mice\" rel=\"nofollow noreferrer\"><code>mice</code> package</a>. <a href=\"https://hbiostat.org/rmsc/missing\" rel=\"nofollow noreferrer\">Chapter 3 of <em>Regression Modeling Strategies</em></a> by Frank Harrell also covers how to handle missing data and describes the associated functions in his <a href=\"https://cran.r-project.org/package=rms\" rel=\"nofollow noreferrer\"><code>rms</code></a> and <a href=\"https://cran.r-project.org/package=Hmisc\" rel=\"nofollow noreferrer\"><code>Hmisc</code></a> packages.</p>\n<blockquote>\n<p>Does the validity depend on the pattern of missing data?</p>\n</blockquote>\n<p>Yes, in two ways.</p>\n<p>First, multiple imputation works correctly if the data are &quot;missing at random&quot; (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.</p>\n<p>Second, the model for imputation needs to represent the patterns of association among the data values adequately.</p>\n<p>The references linked above go into much more detail.</p>\n","answer_id":676936,"answer_text":"is trying to use all the data a flawed concept to begin with?\n\n\n\n\n\n\n\nNo. On the contrary, limiting analysis only to complete-data cases is typically flawed. An exception is if the data are \"missing completely at random\" (MCAR), as in the data that you simulated. Then you get unbiased results, with the cost of higher standard errors than you would have if all of the data were available.\n\n\n\n\n\n\n\nis this even a valid approach to begin with...?\n\n\n\n\n\n\n\nYour most recent comparisons of methods show that your approach seems to trade off some increased bias against lower variance. Whether that's a good tradeoff depends on how you will apply the model in practice. As Frank Harrell noted in a comment, this type of 2-stage approach will only work for linear regression. With binary, categorical, ordinal or count outcomes, you need other methods if data are not MCAR.\n\n\n\n\n\n\n\nwhat is the \"best\" approach?\n\n\n\n\n\n\n\nFor MCAR data, complete-case analysis is certainly simplest. The question in any application is whether the MCAR assumption is close enough to valid. If not, substantial bias can ensue.\n\n\n\n\nA standard general approach is multiple imputation (https://stats.stackexchange.com/tags/multiple-imputation/info). Imputation uses a model of the available data (based on both the outcome values and data not included in the ultimate regression model per se) to estimate the missing data values themselves.\n\n\n\n\nA single imputation, however, also doesn't take into account the random error inherent in making the estimates. You impute multiple complete data sets that draw from the distributions of the imputed values. You fit your ultimate regression model on each of the imputed data sets, and combine the results in a specific way that takes the random variability of the data estimates into account.\n\n\n\n\nStef van Buuren's Flexible Imputation of Missing Data (https://stefvanbuuren.name/fimd/) is a comprehensive guide to the process, which is implemented in his R mice package (https://cran.r-project.org/package=mice). Chapter 3 of Regression Modeling Strategies (https://hbiostat.org/rmsc/missing) by Frank Harrell also covers how to handle missing data and describes the associated functions in his rms (https://cran.r-project.org/package=rms) and Hmisc (https://cran.r-project.org/package=Hmisc) packages.\n\n\n\n\n\n\n\nDoes the validity depend on the pattern of missing data?\n\n\n\n\n\n\n\nYes, in two ways.\n\n\n\n\nFirst, multiple imputation works correctly if the data are \"missing at random\" (MAR) in a technical sense. MAR holds if the available data contain all the information about the probability of a value being missing. That assumption can't be tested directly, but you can evaluate how much reasonable deviations from MAR might matter.\n\n\n\n\nSecond, the model for imputation needs to represent the patterns of association among the data values adequately.\n\n\n\n\nThe references linked above go into much more detail.","answer_url":"https://stats.stackexchange.com/a/676936","author":"EdM","author_url":"https://stats.stackexchange.com/users/28500/edm","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-08-22T20:30:48+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:27:06.169765+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/9155f81b0f1dac4b0f83fad58469033af46ad34ee8d731e569d063b41b3df6b6_1790825226563497500_0.json","raw_sha256":"cbac4b1b24e2159f1c17ea9902eaf89a0a5260344e6dba6f75790ba955f0d04b","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/677298;677295;677280;677279;677278;677275;677269;677266;677262;677256;677245;677243;677242;677226;677225;677217;677211;677201;677194;677193;677186;677183;677179;677177;677171;677169;677168;677151;677149;677147;677137;677135;677131;677129;677115;677110;677109;677101;677099;677098;677096;677095;677094;677085;677083;677079;677078;677075;677071;677066;677065;677062;677058;677045;677041;677035;677033;677023;677021;676999;676997;676991;676982;676981;676979;676977;676975;676971;676966;676961;676958;676956;676952;676947;676945;676937;676935;676933;676924;676922;676899;676898;676893;676889;676888;676879;676874;676873;676870;676867;676865;676858;676855;676850;676842;676832;676830;676824;676823;676821/answers?filter=withbody&order=asc&page=1&pagesize=100&site=stats&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":676935,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-08-22T20:30:48+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"3A662AF2-F298-45A5-889D-7BDCBFDD001E","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3A662AF2-F298-45A5-889D-7BDCBFDD001E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-08-23T17:43:21+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10/view-source"}],"score":5,"updated_at":"2026-08-23T17:43:21+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"EdM","author_url":"https://stats.stackexchange.com/users/28500/edm","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-08-22T20:30:48+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"3A662AF2-F298-45A5-889D-7BDCBFDD001E","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/3A662AF2-F298-45A5-889D-7BDCBFDD001E/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"EdM","profile_url":"https://stats.stackexchange.com/users/28500/edm","user_type":"registered"},"created_at":"2026-08-23T17:43:21+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/2EC4B878-67AD-4FF7-A28A-CBFDF9E04A10/view-source"}],"source_url":"https://stats.stackexchange.com/a/676936"}],"question_author":"A Friendly Fish","question_author_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish"},"code_blocks":[{"block_index":0,"code_text":"# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))[\"y0h\",\"Pr(>|t|)\"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))[\"r_ly0ONy2_n_h\",\"Pr(>|t|)\"]\n}\ncat(\"Multiple: \", mean(multiple < 0.05), \"\\n\")\n# Multiple: 0.0529 \ncat(\" Stage: \", mean(stage < 0.05), \"\\n\")\n# Stage: 0.0527 \n","post_id":"stats:676935","sha256":"31ee3b391b409c5129c104a44ceee4665e4ad79f9da5a4e9871a1a05341ae6ea","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"},{"block_index":1,"code_text":"\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))[\"y0rph\"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))[\"y0rph\"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (sfm)\" = sfm,\n \"Half Model (shm)\" = shm,\n \"Perfect A (shpa)\" = shpa,\n \"Perfect B (shpb)\" = shpb,\n \"Estimated B (sheb)\" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n","post_id":"stats:676935","sha256":"b6b0f012237812aeee60a934ab35cd7d57e130e125fb4b2b6e91c84b7c48ca96","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"},{"block_index":2,"code_text":"# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(\"lavaan\")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- \"\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n\"\n\ncat(\"Running\", num_sims, \"simulations. Please wait...\\n\")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = \"pairwise.complete.obs\")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == \"y0\", \"est\"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (N=40)\" = sfm,\n \"Half Model (H=20)\" = shm,\n \"Estimated B\" = sheb,\n \"Lavaan Pairwise\" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(\"\\n--- Simulation Results ---\\n\")\nprint(round(results_matrix, 5))\n","post_id":"stats:676935","sha256":"8cca68dde9586d6ddecb1ac0f5140745338cd3f8b49ea77f06aa4850b3958b9f","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how"}],"content_license":"CC BY-SA 4.0","domain":"statistics","error_text_if_explicit":null,"group_id":"03ed9cb55365330b1a43abeaaef4353dbae646c43e695d80e153e28eed85e878","id":"SCT-4e8b2ca95695adbf68f9118d","language":null,"library_or_tool":null,"problem_text":"I observe 3 variables, $y_0$, $y_1$, and $y_2$, but am missing some of the observations for $y_1$, so I only have a subsample of $h$ observations of $y_1$ and all $n$ observations of $y_0$ and $y_2$. My goal is to study the relationship between $y_0$ and $y_1$ while controlling for $y_2$ while taking full advantage of all observations. Thus, instead of using only $h$ observations to run the multiple regression ${y_1}_h \\sim {y_0}_h + {y_2}_h$ where the second subscript represents whether we are using just $h$ (or all $n$) observations, I am instead first running ${y_0}_n \\sim {y_2}_n$ and ${y_1}_h \\sim {y_2}_h$ and then regressing the residuals from these two regressions on each other: $r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$. Of course, I only use the $h$ corresponding residuals from the ${y_0}_n \\sim {y_2}_n$ regression of $n$ points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only $h$ data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where $n$ is 40 and $h$ is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the \"best\" approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?\n\n\n\n\n# R code\ndof_correction<-0.5; set.seed(0)\nnum_sims<-10^4; h<-20; n<-40\nmultiple<-stage<-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0<-rnorm(n); y0h<-y0[1:h]; y1h<-rnorm(h); y2<-rnorm(n); y2h<-y2[1:h]\n ly1ONy0y2_h<-lm(y1h ~ y0h + y2h)\n multiple[i]<-coefficients(summary(ly1ONy0y2_h))[\"y0h\",\"Pr(>|t|)\"]\n ly0ONy2_n<-lm(y0 ~ y2); r_ly0ONy2_n<-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h<-r_ly0ONy2_n[1:h]\n ly1ONy2_h<-lm(y1h ~ y2h); r_ly1ONy2_h<-residuals(ly1ONy2_h)\n lrONr<-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual <- lrONr$df.residual - dof_correction\n stage[i]<-coefficients(summary(lrONr))[\"r_ly0ONy2_n_h\",\"Pr(>|t|)\"]\n}\ncat(\"Multiple: \", mean(multiple < 0.05), \"\\n\")\n# Multiple: 0.0529 \ncat(\" Stage: \", mean(stage < 0.05), \"\\n\")\n# Stage: 0.0527 \n\n\n\n\n\nObserve that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)\n\n\n\n\nUPDATE (1/2):\nI ran simulation code to compare some of the key models, (\"Full\") one where we actually aren't missing data, (\"Half\") one where we only use $h$ observations, (\"Estimated B\") where we regress $y_0$ on $y_2$ using all data points and then use the $h$ residuals as the independent variable in a regression with the residuals of $y_1$ regressed on $y_2$ (for the $h$ $y_1$ points we observe) and (\"Perfect A\", \"Perfect B\") then two versions where I calculate the perfect residuals of $y_0$ on $y_2$ using the exactly correct slope:\n\n\n\n\n\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn <- 60\nh <- 30\nnum_sims <- 50000\n\n# Storage vectors for beta estimates\nsfm <- shm <- shpa <- shpb <- sheb <- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Half-sample subsets\n x0h <- x0[1:h]; x1h <- x1[1:h]; x2h <- x2[1:h]\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph <- y0h - 0.5 * y2h\n shpa[i] <- coef(lm(y1h ~ y0rph))[\"y0rph\"]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh <- residuals(lm(y1h ~ y2h))\n shpb[i] <- coef(lm(y1rh ~ y0rph))[\"y0rph\"]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (sfm)\" = sfm,\n \"Half Model (shm)\" = shm,\n \"Perfect A (shpa)\" = shpa,\n \"Perfect B (shpb)\" = shpb,\n \"Estimated B (sheb)\" = sheb\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n\n\n\n\n\nAs you can see in the results above, the \"Estimated B\" version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points (\"Half Model\"), but it does have a bias.\n\n\n\n\nUPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from section 1.3.2 of this book (https://stefvanbuuren.name/fimd/sec-simplesolutions.html) and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:\n\n\n\n\n\n\n\n\n\nModel\nMean\nVariance\nBias\nBias_Sq\nMSE\nValid_Runs\n\n\n\n\n\n\n\n\n\tFull Model (N=40)\n\t0.66563\n\t0.02497\n\t-0.00103\n\t0.00000\n\t0.02497\n\t9947\n\n\n\n\n\n\n\tHalf Model (H=20)\n\t0.66289\n\t0.05542\n\t-0.00377\n\t0.00001\n\t0.05543\n\t9947\n\n\n\n\n\n\n\tEstimated B\n\t0.64330\n\t0.05259\n\t-0.02337\n\t0.00055\n\t0.05313\n\t9947\n\n\n\n\n\n\n\tLavaan Pairwise\n\t0.65849\n\t0.07174\n\t-0.00818\n\t0.00007\n\t0.07180\n\t9947\n\n\n\n\n\n\n\n\n\nI am including the code i ran below:\n\n\n\n\n# Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(\"lavaan\")\nlibrary(lavaan)\n\nset.seed(123)\nn <- 40\nh <- 20\nnum_sims <- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm <- rep(NA, num_sims) # Full Model\nshm <- rep(NA, num_sims) # Half Model\nsheb <- rep(NA, num_sims) # Estimated B\nslav <- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax <- \"\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n\"\n\ncat(\"Running\", num_sims, \"simulations. Please wait...\\n\")\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 <- rnorm(n); x1 <- rnorm(n); x2 <- rnorm(n); x3 <- rnorm(n)\n y0 <- x0 + x1; y1 <- x1 + x2; y2 <- x0 + x3\n \n # Subsets for missing data\n y0h <- y0[1:h]; y1h <- y1[1:h]; y2h <- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full <- c(y1h, rep(NA, n - h))\n df <- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu <- colMeans(df, na.rm = TRUE)\n cv <- cov(df, use = \"pairwise.complete.obs\")\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit <- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params <- parameterEstimates(lav_fit)\n slav[i] <- params[params$lhs == \"y1\" & params$rhs == \"y0\", \"est\"]\n \n # Full Model (sfm)\n sfm[i] <- coef(lm(y1 ~ y0 + y2))[\"y0\"]\n \n # Half Model (shm)\n shm[i] <- coef(lm(y1h ~ y0h + y2h))[\"y0h\"]\n \n # Estimated B (sheb)\n y0re <- residuals(lm(y0 ~ y2))\n y0reh <- y0re[1:h]\n y1rh <- residuals(lm(y1h ~ y2h))\n sheb[i] <- coef(lm(y1rh ~ y0reh))[\"y0reh\"]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta <- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates <- function(estimates, truth) {\n est <- na.omit(estimates)\n m <- mean(est)\n v <- var(est)\n bias <- m - truth\n mse <- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list <- list(\n \"Full Model (N=40)\" = sfm,\n \"Half Model (H=20)\" = shm,\n \"Estimated B\" = sheb,\n \"Lavaan Pairwise\" = slav\n)\n\nresults_matrix <- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(\"\\n--- Simulation Results ---\\n\")\nprint(round(results_matrix, 5))","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":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-22T12:39:55+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"E204A8FC-AC6E-48BB-AF80-E203CBC8615E","revision_number":1,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/E204A8FC-AC6E-48BB-AF80-E203CBC8615E/view-source"},{"content_license":null,"contributor":{"display_name":"[deleted/unavailable user]","profile_url":null,"user_type":"does_not_exist"},"created_at":"2026-08-22T20:46:45+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"18F1A87E-216E-4249-8293-E060F71CC55D","revision_number":null,"revision_type":"vote_based","revision_url":"https://stats.stackexchange.com/revisions/18F1A87E-216E-4249-8293-E060F71CC55D/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-23T15:52:35+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"70469448-256D-43B2-80C1-746F337D6247","revision_number":2,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/70469448-256D-43B2-80C1-746F337D6247/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-23T16:01:52+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"8C27F26B-7F68-4C8C-AF88-BCBF88FC34D5","revision_number":3,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/8C27F26B-7F68-4C8C-AF88-BCBF88FC34D5/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-23T16:53:21+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"7CE38AE1-F9CC-4D58-8A36-87CDCD90FB30","revision_number":4,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/7CE38AE1-F9CC-4D58-8A36-87CDCD90FB30/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"A Friendly Fish","profile_url":"https://stats.stackexchange.com/users/398015/a-friendly-fish","user_type":"registered"},"created_at":"2026-08-23T17:02:49+00:00","raw_file":"raw/codex_api_v1/01ff643b5e725b2402c38de261074c3bef3326820f24db4342e17e318353268e_1790825246205492400_0.json","raw_sha256":"a0521ae83c8630be00a12499e9aaa253069e57a5e0ff902fea3e9b8e7acb810f","revision_guid":"AC468C9B-BCFF-4264-A45F-3229DC6759C1","revision_number":5,"revision_type":"single_user","revision_url":"https://stats.stackexchange.com/revisions/AC468C9B-BCFF-4264-A45F-3229DC6759C1/view-source"}],"source_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:676935","source_record_sha256":"08d2eb508fc13e87f6b6b85c899b59dbb45aaaab753996fa4f22e7f84ebc2d30","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>I observe 3 variables, <span class=\"math-container\">$y_0$</span>, <span class=\"math-container\">$y_1$</span>, and <span class=\"math-container\">$y_2$</span>, but am missing some of the observations for <span class=\"math-container\">$y_1$</span>, so I only have a subsample of <span class=\"math-container\">$h$</span> observations of <span class=\"math-container\">$y_1$</span> and all <span class=\"math-container\">$n$</span> observations of <span class=\"math-container\">$y_0$</span> and <span class=\"math-container\">$y_2$</span>. My goal is to study the relationship between <span class=\"math-container\">$y_0$</span> and <span class=\"math-container\">$y_1$</span> while controlling for <span class=\"math-container\">$y_2$</span> while taking full advantage of all observations. Thus, instead of using only <span class=\"math-container\">$h$</span> observations to run the multiple regression <span class=\"math-container\">${y_1}_h \\sim {y_0}_h + {y_2}_h$</span> where the second subscript represents whether we are using just <span class=\"math-container\">$h$</span> (or all <span class=\"math-container\">$n$</span>) observations, I am instead first running <span class=\"math-container\">${y_0}_n \\sim {y_2}_n$</span> and <span class=\"math-container\">${y_1}_h \\sim {y_2}_h$</span> and then regressing the residuals from these two regressions on each other: <span class=\"math-container\">$r_{y_1 \\sim y_2, h} \\sim r_{y_0 \\sim y_2, n}$</span>. Of course, I only use the <span class=\"math-container\">$h$</span> corresponding residuals from the <span class=\"math-container\">${y_0}_n \\sim {y_2}_n$</span> regression of <span class=\"math-container\">$n$</span> points for the second stage regression. Now typically when all three variables have the same number of observations, the degrees of freedom in the second regression of residuals is one less than it otherwise would be, but in this case, we actually lose less than 1 degree of freedom. However, I do not know the formula (if one exists), so what I am currently doing is simulating null data, and testing different degree of freedom subtractions, to see which one either A) gives the proper 5% rejection rate or B) gives the same rejection rate as the multiple regression that uses only <span class=\"math-container\">$h$</span> data points. So, I think method A is more technically correct than B, but B seems to work better. I have written some R code where <span class=\"math-container\">$n$</span> is 40 and <span class=\"math-container\">$h$</span> is 20, where I'm pretty sure the correction is 0.5 degrees of freedom, which matches better with method B instead of method A. Ultimately if there isn't a formula (one would be welcome), what is the &quot;best&quot; approach? Overall, is this even a valid approach to begin with or is trying to use all the data a flawed concept to begin with? Does the validity depend on the pattern of missing data?</p>\n<pre><code># R code\ndof_correction&lt;-0.5; set.seed(0)\nnum_sims&lt;-10^4; h&lt;-20; n&lt;-40\nmultiple&lt;-stage&lt;-numeric(num_sims) # initialize vectors for storing p-values\nfor (i in 1:num_sims) {\n y0&lt;-rnorm(n); y0h&lt;-y0[1:h]; y1h&lt;-rnorm(h); y2&lt;-rnorm(n); y2h&lt;-y2[1:h]\n ly1ONy0y2_h&lt;-lm(y1h ~ y0h + y2h)\n multiple[i]&lt;-coefficients(summary(ly1ONy0y2_h))[&quot;y0h&quot;,&quot;Pr(&gt;|t|)&quot;]\n ly0ONy2_n&lt;-lm(y0 ~ y2); r_ly0ONy2_n&lt;-residuals(ly0ONy2_n); \n r_ly0ONy2_n_h&lt;-r_ly0ONy2_n[1:h]\n ly1ONy2_h&lt;-lm(y1h ~ y2h); r_ly1ONy2_h&lt;-residuals(ly1ONy2_h)\n lrONr&lt;-lm(r_ly1ONy2_h ~ r_ly0ONy2_n_h)\n lrONr$df.residual &lt;- lrONr$df.residual - dof_correction\n stage[i]&lt;-coefficients(summary(lrONr))[&quot;r_ly0ONy2_n_h&quot;,&quot;Pr(&gt;|t|)&quot;]\n}\ncat(&quot;Multiple: &quot;, mean(multiple &lt; 0.05), &quot;\\n&quot;)\n# Multiple: 0.0529 \ncat(&quot; Stage: &quot;, mean(stage &lt; 0.05), &quot;\\n&quot;)\n# Stage: 0.0527 \n</code></pre>\n<p>Observe that using a dof correction of 0.5 gives a rejection rate (0.527) closer to that found using multiple regression (0.529) than it does to the actual theoretical rate of (0.500)</p>\n<p>UPDATE (1/2):\nI ran simulation code to compare some of the key models, (&quot;Full&quot;) one where we actually aren't missing data, (&quot;Half&quot;) one where we only use <span class=\"math-container\">$h$</span> observations, (&quot;Estimated B&quot;) where we regress <span class=\"math-container\">$y_0$</span> on <span class=\"math-container\">$y_2$</span> using all data points and then use the <span class=\"math-container\">$h$</span> residuals as the independent variable in a regression with the residuals of <span class=\"math-container\">$y_1$</span> regressed on <span class=\"math-container\">$y_2$</span> (for the <span class=\"math-container\">$h$</span> <span class=\"math-container\">$y_1$</span> points we observe) and (&quot;Perfect A&quot;, &quot;Perfect B&quot;) then two versions where I calculate the perfect residuals of <span class=\"math-container\">$y_0$</span> on <span class=\"math-container\">$y_2$</span> using the exactly correct slope:</p>\n<pre><code>\n# Simulation to Compare OLS and Residualized Regression Methods\n# Adjust n, h, and num_sims as needed\n\nset.seed(42)\nn &lt;- 60\nh &lt;- 30\nnum_sims &lt;- 50000\n\n# Storage vectors for beta estimates\nsfm &lt;- shm &lt;- shpa &lt;- shpb &lt;- sheb &lt;- numeric(num_sims)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 &lt;- rnorm(n); x1 &lt;- rnorm(n); x2 &lt;- rnorm(n); x3 &lt;- rnorm(n)\n y0 &lt;- x0 + x1; y1 &lt;- x1 + x2; y2 &lt;- x0 + x3\n \n # Half-sample subsets\n x0h &lt;- x0[1:h]; x1h &lt;- x1[1:h]; x2h &lt;- x2[1:h]\n y0h &lt;- y0[1:h]; y1h &lt;- y1[1:h]; y2h &lt;- y2[1:h]\n \n # 2. Full Model (sfm) - benchmark using full sample (N = n)\n sfm[i] &lt;- coef(lm(y1 ~ y0 + y2))[&quot;y0&quot;]\n \n # 3. Half Model (shm) - standard multiple regression on half sample (N = h)\n shm[i] &lt;- coef(lm(y1h ~ y0h + y2h))[&quot;y0h&quot;]\n \n # 4. Perfect A (shpa) - Y1 regressed on Y0 after partialing out Y2 using true population parameter (0.5)\n y0rph &lt;- y0h - 0.5 * y2h\n shpa[i] &lt;- coef(lm(y1h ~ y0rph))[&quot;y0rph&quot;]\n \n # 5. Perfect B (shpb) - Residualized Y1 (half OLS) on residualized Y0 (true parameter)\n y1rh &lt;- residuals(lm(y1h ~ y2h))\n shpb[i] &lt;- coef(lm(y1rh ~ y0rph))[&quot;y0rph&quot;]\n \n # 6. Estimated B (sheb) - Residualized Y1 (half OLS) on residualized Y0 (estimated on full sample)\n y0re &lt;- residuals(lm(y0 ~ y2))\n y0reh &lt;- y0re[1:h]\n sheb[i] &lt;- coef(lm(y1rh ~ y0reh))[&quot;y0reh&quot;]\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta &lt;- 2/3\n\n# Evaluation function for bias, variance, and MSE\nevaluate_estimates &lt;- function(estimates, truth) {\n est &lt;- na.omit(estimates)\n m &lt;- mean(est)\n v &lt;- var(est)\n bias &lt;- m - truth\n mse &lt;- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse)\n}\n\n# Aggregate and display results table\nmodels_list &lt;- list(\n &quot;Full Model (sfm)&quot; = sfm,\n &quot;Half Model (shm)&quot; = shm,\n &quot;Perfect A (shpa)&quot; = shpa,\n &quot;Perfect B (shpb)&quot; = shpb,\n &quot;Estimated B (sheb)&quot; = sheb\n)\n\nresults_matrix &lt;- t(sapply(models_list, evaluate_estimates, truth = true_beta))\nprint(round(results_matrix, 5))\n# Mean Variance Bias Bias_Sq MSE\n# Full Model (sfm) 0.66641 0.01594 -0.00025 0.00000 0.01594\n# Half Model (shm) 0.66566 0.03424 -0.00101 0.00000 0.03424\n# Perfect A (shpa) 0.66565 0.03296 -0.00101 0.00000 0.03296\n# Perfect B (shpb) 0.64255 0.03276 -0.02412 0.00058 0.03334\n# Estimated B (sheb) 0.65333 0.03325 -0.01334 0.00018 0.03342\n</code></pre>\n<p>As you can see in the results above, the &quot;Estimated B&quot; version, the one where we use all data, has a slighly lower MSE of 0.03342 than that of the multiple regression using only fully observed points (&quot;Half Model&quot;), but it does have a bias.</p>\n<p>UPDATE (2/2):\nPer @EdM 's comment, I used the lavaan approach from <a href=\"https://stefvanbuuren.name/fimd/sec-simplesolutions.html\" rel=\"nofollow noreferrer\">section 1.3.2 of this book</a> and the bias does go away, but compared to just doing a standard multiple regression with only the points i have all data for, it appears the MSE (0.07180) is actually higher??:</p>\n<div class=\"s-table-container\"><table class=\"s-table\">\n<thead>\n<tr>\n<th>Model</th>\n<th>Mean</th>\n<th>Variance</th>\n<th>Bias</th>\n<th>Bias_Sq</th>\n<th>MSE</th>\n<th>Valid_Runs</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Full Model (N=40)</td>\n<td>0.66563</td>\n<td>0.02497</td>\n<td>-0.00103</td>\n<td>0.00000</td>\n<td>0.02497</td>\n<td>9947</td>\n</tr>\n<tr>\n<td>Half Model (H=20)</td>\n<td>0.66289</td>\n<td>0.05542</td>\n<td>-0.00377</td>\n<td>0.00001</td>\n<td>0.05543</td>\n<td>9947</td>\n</tr>\n<tr>\n<td>Estimated B</td>\n<td>0.64330</td>\n<td>0.05259</td>\n<td>-0.02337</td>\n<td>0.00055</td>\n<td>0.05313</td>\n<td>9947</td>\n</tr>\n<tr>\n<td>Lavaan Pairwise</td>\n<td>0.65849</td>\n<td>0.07174</td>\n<td>-0.00818</td>\n<td>0.00007</td>\n<td>0.07180</td>\n<td>9947</td>\n</tr>\n</tbody>\n</table></div>\n<p>I am including the code i ran below:</p>\n<pre><code># Simulation: Missing Data Regression\n# Comparing Two-Stage Residualization (Estimated B) vs Pairwise Deletion (Lavaan)\n\n# Note: If you do not have lavaan installed, run: install.packages(&quot;lavaan&quot;)\nlibrary(lavaan)\n\nset.seed(123)\nn &lt;- 40\nh &lt;- 20\nnum_sims &lt;- 10000 # Safe to run at scale now; failures are caught automatically\n\n# Initialize storage vectors with NA so un-run or failed iterations don't skew stats\nsfm &lt;- rep(NA, num_sims) # Full Model\nshm &lt;- rep(NA, num_sims) # Half Model\nsheb &lt;- rep(NA, num_sims) # Estimated B\nslav &lt;- rep(NA, num_sims) # Lavaan Pairwise\n\n# Define Lavaan model syntax once outside the loop\nmodel_syntax &lt;- &quot;\n y1 ~ 1 + y0 + y2\n y1 ~~ y1\n&quot;\n\ncat(&quot;Running&quot;, num_sims, &quot;simulations. Please wait...\\n&quot;)\n\nfor (i in 1:num_sims) {\n # 1. Generate base standard normal variables\n x0 &lt;- rnorm(n); x1 &lt;- rnorm(n); x2 &lt;- rnorm(n); x3 &lt;- rnorm(n)\n y0 &lt;- x0 + x1; y1 &lt;- x1 + x2; y2 &lt;- x0 + x3\n \n # Subsets for missing data\n y0h &lt;- y0[1:h]; y1h &lt;- y1[1:h]; y2h &lt;- y2[1:h]\n \n # Setup Lavaan data and summary statistics\n y1_full &lt;- c(y1h, rep(NA, n - h))\n df &lt;- data.frame(y1 = y1_full, y0 = y0, y2 = y2)\n \n mu &lt;- colMeans(df, na.rm = TRUE)\n cv &lt;- cov(df, use = &quot;pairwise.complete.obs&quot;)\n \n # 2. Try running Lavaan. If the covariance matrix is non-positive-definite, catch it.\n lav_fit &lt;- tryCatch({\n suppressWarnings(lavaan(model_syntax, \n sample.mean = mu, \n sample.cov = cv, \n sample.nobs = h))\n }, error = function(e) {\n NULL\n })\n \n # 3. Only store estimates if Lavaan successfully converged\n if (!is.null(lav_fit)) {\n # Lavaan estimate\n params &lt;- parameterEstimates(lav_fit)\n slav[i] &lt;- params[params<span class=\"math-container\">$lhs == \"y1\" &amp; params$</span>rhs == &quot;y0&quot;, &quot;est&quot;]\n \n # Full Model (sfm)\n sfm[i] &lt;- coef(lm(y1 ~ y0 + y2))[&quot;y0&quot;]\n \n # Half Model (shm)\n shm[i] &lt;- coef(lm(y1h ~ y0h + y2h))[&quot;y0h&quot;]\n \n # Estimated B (sheb)\n y0re &lt;- residuals(lm(y0 ~ y2))\n y0reh &lt;- y0re[1:h]\n y1rh &lt;- residuals(lm(y1h ~ y2h))\n sheb[i] &lt;- coef(lm(y1rh ~ y0reh))[&quot;y0reh&quot;]\n }\n}\n\n# True theoretical beta for y0 in y1 ~ y0 + y2 is 2/3 (~0.66667)\ntrue_beta &lt;- 2/3\n\n# Evaluation function for bias, variance, and MSE (automatically strips NAs)\nevaluate_estimates &lt;- function(estimates, truth) {\n est &lt;- na.omit(estimates)\n m &lt;- mean(est)\n v &lt;- var(est)\n bias &lt;- m - truth\n mse &lt;- mean((est - truth)^2)\n c(Mean = m, Variance = v, Bias = bias, Bias_Sq = bias^2, MSE = mse, Valid_Runs = length(est))\n}\n\n# Aggregate and display results table\nmodels_list &lt;- list(\n &quot;Full Model (N=40)&quot; = sfm,\n &quot;Half Model (H=20)&quot; = shm,\n &quot;Estimated B&quot; = sheb,\n &quot;Lavaan Pairwise&quot; = slav\n)\n\nresults_matrix &lt;- t(sapply(models_list, evaluate_estimates, truth = true_beta))\ncat(&quot;\\n--- Simulation Results ---\\n&quot;)\nprint(round(results_matrix, 5))\n</code></pre>\n","question_title":"missing data: break multiple regression into stages; how?","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://stats.stackexchange.com/questions/676935/missing-data-break-multiple-regression-into-stages-how","split":"holdout"}
{"accepted_answer":null,"answer_scores":[{"answer_id":45250,"score":2}],"answers":[{"answer_html":"<p>Dear Lutz Lehmann and community,</p>\n<p>Thank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.</p>\n<p>For reference, here is the corresponding code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=&quot;Velocity (m/s) at pipe center&quot;)\nplt.xlabel(&quot;Time (s)&quot;)\nplt.ylabel(&quot;Velocity at the middle of the pipe (m/s)&quot;)\nplt.title(&quot;Velocity evolution at the middle of the pipe&quot;)\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f&quot;t = {temps_selectionnes[i]:.1f} s&quot;)\nplt.xlabel(&quot;Position x (m)&quot;)\nplt.ylabel(&quot;Velocity (m/s)&quot;)\nplt.title(&quot;Velocity profile along the pipe at different times&quot;)\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n</code></pre>\n<p>Best regards,\nRaphaël</p>\n","answer_id":45250,"answer_text":"Dear Lutz Lehmann and community,\n\n\n\n\nThank you for your response. I’ve now managed to develop a fully functional program. My main challenge was that I only had two of the four boundary conditions required by the numerical scheme. As it turns out, the two missing conditions could be derived by injecting the known ones into the PDE system. With this adjustment, the program now runs smoothly.\n\n\n\n\nFor reference, here is the corresponding code.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n\n\n\n\n\nBest regards,\nRaphaël","answer_url":"https://scicomp.stackexchange.com/a/45250","author":"Ev0Cation","author_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2025-10-07T14:19:16+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45246,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ev0Cation","profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","user_type":"registered"},"created_at":"2025-10-07T14:19:16+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C3CA863F-650C-4C2D-BD76-4C6863DC85E0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}],"score":2,"updated_at":"2025-10-07T14:19:16+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"Ev0Cation","author_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Ev0Cation","profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","user_type":"registered"},"created_at":"2025-10-07T14:19:16+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"C3CA863F-650C-4C2D-BD76-4C6863DC85E0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/C3CA863F-650C-4C2D-BD76-4C6863DC85E0/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45250"}],"question_author":"Ev0Cation","question_author_url":"https://scicomp.stackexchange.com/users/54820/ev0cation"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n","post_id":"scicomp:45246","sha256":"8be5b8d21acaa3124f11278e9e1956344bcf0077a81fcffd51aa290ed3d02098","source_url":"https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation"},{"block_index":0,"code_text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 10 # Pipe length (m)\nnx = 50 # Number of spatial points\ndx = L / nx # Spatial step (m)\nT = 10*60 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nrho_ext = Patm * Mair / (R * Text) # External air density (kg/m³) at 20°C and atmospheric pressure\nc_v = 5/2 * R / Mair # Specific heat capacity at constant volume (J/kg·K) for a diatomic gas (air)\nv_des = 10.0 # Desired velocity at the inlet (m/s)\n# Temporal initialization of variables\nrho_0 = [rho_ext] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [0] * nx # Initial velocity\nT0 = [Text] * nx # Initial temperature (K)\nPin0 = Patm # Pression initiale (Pa)\nPin_des0 = Pin0 # Pression initiale (Pa)\n# Auxiliary parameters\ntau_comp = 1 # Characteristic time of the compressor (s)\nKp = 4 # m².s-1.Pa-1. Proportional constant of the PD controller.\nKd = 50.75 # m².Pa-1. Derivative constant of the PD controller.\n\ndef mu(T): # Loi de Sutherland pour l'air\n # T en Kelvin\nmu0 = 1.716e-5 # viscosité à T0 (Pa·s)\nT0 = 273.15 # température de référence (K)\nC = 111 # constante de Sutherland (K)\nreturn mu0 * (T / T0)**1.5 * (T0 + C) / (T + C)\n\ndef calculate_dPin_desdt(rho_0, drhodt_0, v_0, dvdt_0):\n Qcomp_des = rho_0 * v_des * Acan # Consigne du débit massique du compresseur (kg/s)\nQcomp = rho_0 * v_0 * Acan # Débit volumique (kg/s)\ndQcompdt = (rho_0 * dvdt_0 + v_0 * drhodt_0) * Acan # Dérivée du débit volumique (kg/s)\nreturn Kp * (Qcomp_des - Qcomp) - Kd * dQcompdt # PD controller\ndef calculate_dPindt(Pin, Pin_des):\n return (Pin_des - Pin) / tau_comp # Modèle de premier ordre du compresseur\ndef calculate_drhodx(rho):\n drhodx = [None] * nx\n drhodx[0] = (rho[1] - rho[0]) / (2 * dx) # The flow is incompressible before entering the pipe.\nfor i in range(1, nx - 1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndrhodx[-1] = (rho[-1] - rho[-2]) / (2 * dx) # The flow is incompressible after exiting the pipe.\nreturn drhodx\n\ndef calculate_dPdx(P):\n dPdx = [None] * nx\n dPdx[0] = (P[1] - P[0]) / (2 * dx) # The flow is incompressible and isotherm before entering the pipe.\nfor i in range(1, nx - 1):\n dPdx[i] = (P[i + 1] - P[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndPdx[-1] = (P[-1] - P[-2]) / (2 * dx) # The flow is incompressible and isotherm after exiting the pipe.\nreturn dPdx\n\ndef calculate_dvdx(rho, drhodx, v, dPindt):\n dvdx = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n dvdx[0] = - v[0] / rho[0] * drhodx[0] - drhodt_0 / rho[0] # Obtained from the boundary condition at the inlet (controlled pressure) injected in the continuity equation.\nfor i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # Schéma centré d'ordre 2\ndvdx[-1] = - v[-1] / rho[-1] * drhodx[-1] # Obtained from the boundary condition rho[-1] = rho_ext injected in the continuity equation.\nreturn dvdx\n\ndef calculate_d2vdx2(rho, v, dvdx, dPindt):\n d2vdx2 = [None] * nx\n drhodt_0 = dPindt * Mair / (R * Text)\n d2vdx2[0] = (dvdx[1] + drhodt_0/rho[0]) / (2 * dx)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx ** 2\nd2vdx2[-1] = - dvdx[-2] / (2 * dx)\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx, dPindt):\n drhodt = [None] * nx\n drhodt[0] = dPindt * Mair / (R * Text) # Boundary condition at the inlet (controlled pressure) - quasi-Dirichlet condition\nfor i in range(1, nx - 1):\n drhodt[i] = - rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\ndrhodt[-1] = 0 # Boundary condition at the outlet (fixed density) - Dirichlet condition\nreturn drhodt\n\ndef calculate_dvdt(rho, v, dvdx, d2vdx2, dPdx):\n dvdt = [None] * nx\n for i in range(0, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu(Text) / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\nreturn dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n P = rho * R * T / Mair # Perfect gas law\n P[0] = y[2*nx]\n Pin_des = y[2*nx + 1]\n\n dPindt = calculate_dPindt(P[0], Pin_des)\n\n drhodx = calculate_drhodx(rho)\n dPdx = calculate_dPdx(P)\n dvdx = calculate_dvdx(rho, drhodx, v, dPindt)\n d2vdx2 = calculate_d2vdx2(rho, v, dvdx, dPindt)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx, dPindt)\n dvdt = calculate_dvdt(rho, v, T, dvdx, d2vdx2, dPdx)\n\n dPin_desdt = calculate_dPin_desdt(rho[0], drhodt[0], v[0], dvdt[0])\n\n return np.concatenate([drhodt, dvdt, [dPindt], [dPin_desdt]])\n\n# Initiale condition\ny0 = np.array(rho_0 + v0 + T0 + [Pin0] + [Pin_des0])\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF')\n\n# Extraction of results\nt = sol.t\nv_all = sol.y[nx:2*nx]\n\n# Visualization of results\n# Preparation for visualization\nindices_temps = [0, len(t)//4, len(t)//2, 3*len(t)//4, -1]\ntemps_selectionnes = [t[i] for i in indices_temps]\nx = np.linspace(0, L, nx)\n\n# Plot 1: Velocity at the middle of the pipe as a function of time\nplt.figure(figsize=(12, 6))\nplt.plot(t, v_all[nx // 2, :], label=\"Velocity (m/s) at pipe center\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity at the middle of the pipe (m/s)\")\nplt.title(\"Velocity evolution at the middle of the pipe\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\n# Plot 2: Velocity profile along the pipe at selected times\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(indices_temps):\n plt.plot(x, v_all[:, idx], label=f\"t = {temps_selectionnes[i]:.1f} s\")\nplt.xlabel(\"Position x (m)\")\nplt.ylabel(\"Velocity (m/s)\")\nplt.title(\"Velocity profile along the pipe at different times\")\nplt.grid()\nplt.legend()\nplt.tight_layout()\n\nplt.show()\n","post_id":45250,"sha256":"e4c81797aebb0183f7ae202e8f40018f8a8f8af8534cea97bd44225f2587483d","source_url":"https://scicomp.stackexchange.com/a/45250"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"a8391bf268b878b5f0507e4b8ceaa7dd72acf2050e6871341b748edaa1f683f8","id":"SCT-6cdeb4f7cbdb46096754005c","language":["python"],"library_or_tool":["numpy","scipy"],"problem_text":"I am currently struggling with the implementation of the compressible Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.\n\n\n\n\nI strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.\n\n\n\n\nHere is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a compressible Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is laminar. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a 1D formulation. Thermal exchanges are neglected.\n\n\n\n\nCould you please give me some guidance on how to solve this problem please?\n\n\n\n\nI will include my current code and figure below for reference.\n\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=\"Velocity (m/s)\")\nplt.xlabel(\"Time (s)\")\nplt.ylabel(\"Velocity\")\nplt.title(\"Velocity evolution\")\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n\n\n\n\n[image: Results; source: https://i.sstatic.net/pB2ZlSLf.png] (https://i.sstatic.net/pB2ZlSLf.png)","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":"Ev0Cation","profile_url":"https://scicomp.stackexchange.com/users/54820/ev0cation","user_type":"registered"},"created_at":"2025-10-03T16:37:31+00:00","raw_file":"raw/codex_api_v1/932c57dde4e92dfe2af05c19643e98b6494a44cb31534e6703e92349c4e07eb4_1790825333093747000_0.json","raw_sha256":"646e25c86dbb0c4df1ebe365442e733a253ac993340d2ed18168bbf783f75cac","revision_guid":"10D2B924-C266-46E3-844E-A857A83DB2A0","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/10D2B924-C266-46E3-844E-A857A83DB2A0/view-source"}],"source_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":"45246","source_record_sha256":"d392eef5e8e0fbd252e6464ae9c2ab947aaba148870ac1dd4589cfc442431a56","source_url":"https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>I am currently struggling with the implementation of the <strong>compressible</strong> Navier–Stokes equations in my research work. To simplify the problem as much as possible, I reformulated it as a textbook-like problem. The numerical solution creates strong oscillations that I cannot get rid of.</p>\n<p>I strongly suspect that the issue lies in the boundary conditions. In particular, I am not sure how to handle the inlet pressure and the outlet velocity. For now, I am using a very simple Neumann-type condition to bypass this difficulty, but I am aware this might be incorrect.</p>\n<p>Here is the statement of the problem: Consider a straight circular pipe of cross-section\nS, with no bends, connected at the inlet to a pump that imposes a constant flow rate, and open to the atmosphere at the outlet. The pipe is filled with a <strong>compressible</strong> Newtonian gas (with Stokes’ hypothesis), assuming constant viscosity. Initially, the pressure inside the pipe is atmospheric, and the velocity in the pipe is zero, except at the inlet where it is equal to the pump-imposed velocity. The resulting flow is <strong>laminar</strong>. Write a Python program that computes the time evolution of the velocity in the pipe, restricted to a <strong>1</strong>D formulation. Thermal exchanges are neglected.</p>\n<p>Could you please give me some guidance on how to solve this problem please?</p>\n<p>I will include my current code and figure below for reference.</p>\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\n# Physical parameters\nRcan = 0.05 # Pipe radius (m)\nAcan = np.pi * Rcan ** 2 # Pipe cross-sectional area (m²)\nL = 1.0 # Pipe length (m)\nnx = 4 # Number of spatial points\ndx = L / (nx - 1) # Spatial step (m)\nT = 30 # Total simulation time (s)\nR = 8.31446261815324 # J/(mol·K)\nMair = 0.029 # Molar mass of air (kg/mol)\nPatm = 101325 # Atmospheric pressure (Pa)\nText = 20 + 273.15 # Outside temperature (K)\nmu = 1.8e-5 # Dynamic viscosity (Pa·s)\n\n# Initialization of variables\nrho0 = [Patm * Mair / (R * Text)] * nx # Initial air density (kg/m³) at 20°C and atmospheric pressure\nv0 = [1.0] + [0] * (nx-1) # Initial velocity\n\n# Boundary conditions\nrho_v_A_in = rho0[0] * v0[0] * Acan\nrho_out = rho0[-1]\n\ndef calculate_drhodx(rho):\n drhodx = np.zeros_like(rho)\n drhodx[0] = 0 # Neumann condition at inlet\n for i in range(1, nx-1):\n drhodx[i] = (rho[i + 1] - rho[i - 1]) / (2 * dx) # 2nd order centered\n return drhodx\n\ndef calculate_dvdx(v):\n dvdx = np.zeros_like(v)\n for i in range(1, nx - 1):\n dvdx[i] = (v[i + 1] - v[i - 1]) / (2 * dx) # 2nd order centered\n dvdx[-1] = 0 # Neumann condition at outlet\n return dvdx\n\ndef calculate_d2vdx2(v):\n d2vdx2 = np.zeros_like(v)\n for i in range(1, nx - 1):\n d2vdx2[i] = (v[i + 1] - 2 * v[i] + v[i - 1]) / dx**2 # 2nd order centered\n d2vdx2[-1] = 0 # Neumann condition at outlet\n return d2vdx2\n\ndef calculate_drhodt(rho, v, drhodx, dvdx):\n drhodt = np.zeros_like(rho)\n drhodt[-1] = 0 # Dirichlet condition at outlet\n for i in range(0, nx - 1):\n drhodt[i] = -rho[i] * dvdx[i] - v[i] * drhodx[i] # 1D compressible continuity equation\n return drhodt\n\ndef calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx):\n dvdt = np.zeros_like(v)\n dvdt[0] = - v[0] / rho[0] * drhodt[0] # Dirichlet condition at inlet knowing that rho*v is constant\n for i in range(1, nx):\n dvdt[i] = - 1 / rho[i] * dPdx[i] - v[i] * dvdx[i] + 4/3 * mu / rho[i] * d2vdx2[i] # 1D compressible Navier-Stokes\n return dvdt\n\n\ndef dydt(t, y):\n rho = y[:nx]\n v = y[nx:2*nx]\n\n drhodx = calculate_drhodx(rho)\n dPdx = drhodx * R * Text / Mair # Perfect gas law + isotherm\n dvdx = calculate_dvdx(v)\n d2vdx2 = calculate_d2vdx2(v)\n\n drhodt = calculate_drhodt(rho, v, drhodx, dvdx)\n dvdt = calculate_dvdt(rho, drhodt, v, dvdx, d2vdx2, dPdx)\n\n return np.concatenate([drhodt, dvdt])\n\n# Initiale condition\ny0 = np.array(rho0 + v0)\n\n# Integration time\nt_span = (0, T)\n\n# Resolution with solve_ivp\nsol = solve_ivp(dydt, t_span, y0, method='BDF', atol=1e-8, rtol=1e-5)\n\n# Extraction of results\nt = sol.t\nv = sol.y[nx-1 + nx //2]\n\n# Visualization of results\nplt.figure(figsize=(12, 6))\nplt.plot(t, v, label=&quot;Velocity (m/s)&quot;)\nplt.xlabel(&quot;Time (s)&quot;)\nplt.ylabel(&quot;Velocity&quot;)\nplt.title(&quot;Velocity evolution&quot;)\nplt.grid()\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n</code></pre>\n<p><a href=\"https://i.sstatic.net/pB2ZlSLf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/pB2ZlSLf.png\" alt=\"Results\" /></a></p>\n","question_title":"Oscillations in 1D compressible Navier–Stokes simulation","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45246/oscillations-in-1d-compressible-navier-stokes-simulation","split":"holdout"}
{"accepted_answer":null,"answer_scores":[{"answer_id":45394,"score":2}],"answers":[{"answer_html":"<p>The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)</p>\n<p>I'll focus on integrals of the type:\n<span class=\"math-container\">\\begin{align}\nI^l &amp;= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&amp;= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}</span></p>\n<p>I'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.</p>\n<p>By using the variable substitution <span class=\"math-container\">$u=1-x$</span>:\n<span class=\"math-container\">\\begin{align}\nI^l_{left} &amp;= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&amp;= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}</span></p>\n<p>Then by using Newton's formula: <span class=\"math-container\">$(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$</span> this integral is then a linear combination of simpler integrals.</p>\n<h1>Code example</h1>\n<p>By applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:</p>\n<pre><code>import numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f&quot;Numerical Result: {result:.10f}&quot;)\n# Result from WolframAlpha = 0.0187983\n</code></pre>\n","answer_id":45394,"answer_text":"The integral can be evaluated analytically. (I'll provide a code with the code quadrature also.)\n\n\n\n\nI'll focus on integrals of the type:\n\\begin{align}\nI^l &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= \\frac{1}{2}\\int_a^b\\frac{x^l}{1-x} + \\frac{x^l}{1+x}dx\n\\end{align}\n\n\n\n\nI'll focus on the integral on the left (without the 1/2 factor) as the tricks involved can be applied to the other one.\n\n\n\n\nBy using the variable substitution $u=1-x$:\n\\begin{align}\nI^l_{left} &= \\int_a^b\\frac{x^l}{1-x}dx\\\\\n&= -\\int_a^b\\frac{(1-u)^l}{u}du\n\\end{align}\n\n\n\n\nThen by using Newton's formula: $(1-u)^n = \\sum_{k=0}^n\\binom{n}{k}(-u)^k$ this integral is then a linear combination of simpler integrals.\n\n\n\n\nCode example\n\n\n\n\nBy applying the usual quadrature scheme with the full integrand with Gauss-Legendre quadrature points:\n\n\n\n\nimport numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983","answer_url":"https://scicomp.stackexchange.com/a/45394","author":"mle","author_url":"https://scicomp.stackexchange.com/users/46538/mle","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-03-04T18:29:45+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:47.033952+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/cb6e5f564c84a92c4e121c0637c99292018f8935652e423630f2001099a2410f_1790825327386675300_0.json","raw_sha256":"1a957289f56621bebd21cb45dd99baaedb2c3bc11cb28d700558e4bbcaa19695","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=1&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45362,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"mle","profile_url":"https://scicomp.stackexchange.com/users/46538/mle","user_type":"registered"},"created_at":"2026-03-04T18:29:45+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"D8A9E199-F055-462B-8A0D-91FD9CE698F5","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}],"score":2,"updated_at":"2026-03-04T18:29:45+00:00"}],"attempted_method_if_explicit":null,"author_attribution":{"answers":[{"author":"mle","author_url":"https://scicomp.stackexchange.com/users/46538/mle","content_license":"CC BY-SA 4.0","revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"mle","profile_url":"https://scicomp.stackexchange.com/users/46538/mle","user_type":"registered"},"created_at":"2026-03-04T18:29:45+00:00","raw_file":"raw/codex_api_v1/09cbe10ae05462240864407122b451f89c4541eb0ee757adda70c0629772d57a_1790825351806992800_0.json","raw_sha256":"34f3f34325937951c51090d8305fb513e1e88ef2ed40dcec5c0fe96d5710ba75","revision_guid":"D8A9E199-F055-462B-8A0D-91FD9CE698F5","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/D8A9E199-F055-462B-8A0D-91FD9CE698F5/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45394"}],"question_author":"vibe","question_author_url":"https://scicomp.stackexchange.com/users/28440/vibe"},"code_blocks":[{"block_index":0,"code_text":"import numpy as np\n\ndef integrate_tabulated(f, a, b):\n xi = np.array([-0.9061798459, -0.5384693101, 0.0, 0.5384693101, 0.9061798459])\n wi = np.array([0.2369268851, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268851])\n\n # Map points from [-1, 1] to [a, b]\n x_mapped = 0.5 * (b - a) * xi + 0.5 * (a + b)\n w_mapped = wi * 0.5 * (b - a)\n return np.sum(w_mapped * f(x_mapped))\n\na = 0.5\nb = 0.75\nfunc = lambda x: x**5/(1+x**2)\nresult = integrate_tabulated(func, a, b)\n\nprint(f\"Numerical Result: {result:.10f}\")\n# Result from WolframAlpha = 0.0187983\n","post_id":45394,"sha256":"3ba14f7d8ca6fcf552a8429426a59372f6c08c1fad801078f723f57a680abda3","source_url":"https://scicomp.stackexchange.com/a/45394"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"f7408494e81e9eb9051ae7559ef4833e86037e463c68458ddae229e377925ec5","id":"SCT-a721c27a72159075f6c8a0c0","language":null,"library_or_tool":null,"problem_text":"I need to compute a number of integrals of the form\n$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$\nwhere $p_n(x)$ is a polynomial of degree $n$. My limits $[a,b] \\subset [-1,1]$ so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits $[a,b]$ I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the $1/(1-x^2)$ factor.\n\n\n\n\nMy question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.\n\n\n\n\nThe problem of computing robust quadrature nodes and weights for an arbitrary interval $[a,b]$ and a given weight function (such as $1/(1-x^2)$) appears to be an open problem in numerics unfortunately.","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":"vibe","profile_url":"https://scicomp.stackexchange.com/users/28440/vibe","user_type":"registered"},"created_at":"2026-02-04T15:10:39+00:00","raw_file":"raw/codex_api_v1/d49b4ef7856602e9d6b1a79d56b143976504b0637af4b266f03f2b60112c6c15_1790825353984908500_0.json","raw_sha256":"4ebc32b188652be208cbfb32007d2c8fcbe5419e5ab336ca46a3e9eb5ef04d0e","revision_guid":"9B775FCA-6689-4886-BE87-22C985705EFF","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/9B775FCA-6689-4886-BE87-22C985705EFF/view-source"}],"source_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":"45362","source_record_sha256":"3cd7fe0248eb0b06ff6dfe38c01b5844f594b098884eed53f61e7f1d6b236d48","source_url":"https://scicomp.stackexchange.com/questions/45362/quadrature-rule-for-ratio-of-polynomials","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>I need to compute a number of integrals of the form\n<span class=\"math-container\">$$\nI = \\int_a^b \\frac{p_n(x)}{1-x^2} dx\n$$</span>\nwhere <span class=\"math-container\">$p_n(x)$</span> is a polynomial of degree <span class=\"math-container\">$n$</span>. My limits <span class=\"math-container\">$[a,b] \\subset [-1,1]$</span> so there is no concern about a singularity in the denominator. Unfortunately because of my arbitrary limits <span class=\"math-container\">$[a,b]$</span> I cannot use standard fixed point quadrature rules. Gauss-Legendre quadrature can be applied to arbitrary intervals but it won't produce exact results because of the <span class=\"math-container\">$1/(1-x^2)$</span> factor.</p>\n<p>My question is whether it is possible to develop an accurate fixed point quadrature rule for these integrals? I do not want to use adaptive quadrature since it is not robust and accurate enough for my purposes.</p>\n<p>The problem of computing robust quadrature nodes and weights for an arbitrary interval <span class=\"math-container\">$[a,b]$</span> and a given weight function (such as <span class=\"math-container\">$1/(1-x^2)$</span>) appears to be an open problem in numerics unfortunately.</p>\n","question_title":"Quadrature rule for ratio of polynomials","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45362/quadrature-rule-for-ratio-of-polynomials","split":"holdout"}
{"accepted_answer":null,"answer_scores":[{"answer_id":45537,"score":2}],"answers":[{"answer_html":"<p>The key insight (also reflected in <a href=\"https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them#comment93668_45533\">this comment</a>) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that <span class=\"math-container\">$P = (0,0)$</span>. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as <span class=\"math-container\">$\\frac 1 {\\cos(\\theta)}$</span> and norm to a point on horizontal segments will scale as <span class=\"math-container\">$\\frac 1 {\\sin(\\theta)}$</span>. In both cases, the result is that the norm minima are seen at axis intersections (<span class=\"math-container\">$\\theta = \\frac {\\pi n} 2$</span>).</p>\n<p>Since you've failed to describe the scale of the problem, start with a simple <span class=\"math-container\">$O(n^2)$</span> implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,</p>\n<ol>\n<li>Union the set of all box-box intersections and all box-axis intersections</li>\n<li>From that set, exclude all points that are occluded by a box</li>\n<li>Do a tensor contraction to get the squared norm for the remaining intersections</li>\n<li>Choose the smallest one.</li>\n</ol>\n<p>For small bounding box count, it's very frequent that an axis intersection is selected:</p>\n<p><a href=\"https://i.sstatic.net/rLLW3nkZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/rLLW3nkZ.png\" alt=\"small problem\" /></a></p>\n<p>For 90 bounding boxes, we see a non-axis intersection being selected:</p>\n<p><a href=\"https://i.sstatic.net/B0XWwMzu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.sstatic.net/B0XWwMzu.png\" alt=\"90 boxes\" /></a></p>\n<p>On my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -&gt; np.ndarray:\n &quot;&quot;&quot;\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n &quot;&quot;&quot;\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -&gt; np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 &lt;= xp) &amp; (xp &lt;= x1) &amp; (y0 &lt;= yp) &amp; (yp &lt;= y1)\n hits[:-1, :-1] &amp;= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -&gt; np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 &lt; xi) &amp; (xi &lt; x1) &amp; (y0 &lt; yi) &amp; (yi &lt; y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -&gt; int:\n norm2 = np.einsum('ij,ij-&gt;j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -&gt; None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -&gt; None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n","answer_id":45537,"answer_text":"The key insight (also reflected in this comment (https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them#comment93668_45533)) is that the closest non-occluded point will either be at the intersection of two bounding box segments, or will be at the intersection of one bounding box segment and one axis - after the problem space has been translated so that $P = (0,0)$. The axis intersection is because of the 'axis-aligned' bounding boxes and the fact that Euclidean norm to a point on vertical segments will scale as $\\frac 1 {\\cos(\\theta)}$ and norm to a point on horizontal segments will scale as $\\frac 1 {\\sin(\\theta)}$. In both cases, the result is that the norm minima are seen at axis intersections ($\\theta = \\frac {\\pi n} 2$).\n\n\n\n\nSince you've failed to describe the scale of the problem, start with a simple $O(n^2)$ implementation - which, for small problems, may actually out-perform anything more sophisticated. That depends on a lot of things and requires benchmarking diligence. Loosely,\n\n\n\n\n\nUnion the set of all box-box intersections and all box-axis intersections\n\n\n\n\nFrom that set, exclude all points that are occluded by a box\n\n\n\n\nDo a tensor contraction to get the squared norm for the remaining intersections\n\n\n\n\nChoose the smallest one.\n\n\n\n\n\nFor small bounding box count, it's very frequent that an axis intersection is selected:\n\n\n\n\n[image: small problem; source: https://i.sstatic.net/rLLW3nkZ.png] (https://i.sstatic.net/rLLW3nkZ.png)\n\n\n\n\nFor 90 bounding boxes, we see a non-axis intersection being selected:\n\n\n\n\n[image: 90 boxes; source: https://i.sstatic.net/B0XWwMzu.png] (https://i.sstatic.net/B0XWwMzu.png)\n\n\n\n\nOn my old laptop, this processes 1,000 bounding boxes in 0.3 seconds.\n\n\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n \"\"\"\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n \"\"\"\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()","answer_url":"https://scicomp.stackexchange.com/a/45537","author":"Reinderien","author_url":"https://scicomp.stackexchange.com/users/41212/reinderien","author_user_type":"registered","content_license":"CC BY-SA 4.0","created_at":"2026-09-07T22:20:58+00:00","is_accepted":false,"provenance":{"attribution_required":true,"collected_at":"2026-10-01T03:28:49.393498+00:00","license":"CC BY-SA 4.0","license_url":"https://creativecommons.org/licenses/by-sa/4.0/","raw_file":"raw/codex_api_v1/bdd73bdc9d483cfaf7d50f2075e853261f39886330cd6d24a17f7b3b2fb731e5_1790825329894890800_0.json","raw_sha256":"dfbb76df9ebacfee7e902db64890f154a777bd3049356aee472798c591424d79","source_api":"Stack Exchange API 2.3","source_url":"https://api.stackexchange.com/2.3/questions/45545;45541;45538;45533;45532;45530;45523;45513;45510;45507;45499;45493;45488;45487;45479;45474;45472;45463;45461;45447;45444;45436;45428;45425;45424;45423;45422;45416;45414;45410;45404;45401;45396;45391;45389;45387;45380;45377;45376;45375;45369;45366;45365;45363;45362;45359;45350;45347;45344;45336;45334;45331;45326;45322;45316;45313;45311;45309;45305;45302;45300;45291;45289;45285;45276;45269;45263;45262;45261;45253;45247;45246;45238;45236;45230;45229;45208;45201;45200;45185;45183;45171;45167;45165;45158;45154;45146;45141;45139;45134;45129;45127;45122;45114;45112;45108;45105;45100;45098;45096/answers?filter=withbody&order=asc&page=2&pagesize=100&site=scicomp&sort=creation","transformation":"API HTML retained; mechanical HTML-to-text; no LLM rewriting"},"question_id":45533,"revision_attribution":[{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:20:58+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"EA034CBB-245E-47BE-9F83-73186A65FD54","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EA034CBB-245E-47BE-9F83-73186A65FD54/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:53:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"13520681-83F3-4234-8A59-CE187F0BEA29","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/13520681-83F3-4234-8A59-CE187F0BEA29/view-source"}],"score":2,"updated_at":"2026-09-07T22:53:19+00:00"}],"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-09-07T22:20:58+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"EA034CBB-245E-47BE-9F83-73186A65FD54","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/EA034CBB-245E-47BE-9F83-73186A65FD54/view-source"},{"content_license":"CC BY-SA 4.0","contributor":{"display_name":"Reinderien","profile_url":"https://scicomp.stackexchange.com/users/41212/reinderien","user_type":"registered"},"created_at":"2026-09-07T22:53:19+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"13520681-83F3-4234-8A59-CE187F0BEA29","revision_number":2,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/13520681-83F3-4234-8A59-CE187F0BEA29/view-source"}],"source_url":"https://scicomp.stackexchange.com/a/45537"}],"question_author":"ffbh","question_author_url":"https://scicomp.stackexchange.com/users/57252/ffbh"},"code_blocks":[{"block_index":0,"code_text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle, Circle\n\n\ndef sample_data(n: int = 20, seed: int = 0) -> np.ndarray:\n \"\"\"\n Generate a tensor of ((2=x,y), (2=min,max), n) bounding boxes\n \"\"\"\n rand = np.random.default_rng(seed)\n box = np.empty(shape=(2, 2, n), dtype=np.float32)\n box[..., 0] = (\n (-0.3, +0.3),\n (-0.3, +0.3),\n )\n box[:, 0, 1:] = rand.uniform(low=-1, high=0.5, size=(2, n-1))\n box[:, 1, 1:] = rand.uniform(low=0, high=0.5, size=(2, n-1)) + box[:, 0, 1:]\n return box.round(2)\n\n\ndef intersect_points(box: np.ndarray) -> np.ndarray:\n n = box.shape[-1]\n\n # All segments from bounding boxes min,max, and axis:\n # segment coordinate values on parallel axis\n segments_par = np.empty(\n shape=(2, 2, 2*n + 1), # (x,y), (parmin,parmax), (perp min, perp max)n + axis\n dtype=box.dtype,\n )\n segments_par[..., :-1] = box.repeat(2, axis=-1)\n # The last line is the axis. The axis intersecting any bounding box produces candidate points\n # for the closest-exterior output.\n segments_par[..., -1] = -np.inf, +np.inf\n\n # segment coordinate values on perpendicular axis\n # (y,x), (perp min, perp max)n + axis\n segments_perp = np.empty(shape=segments_par.shape[1:], dtype=box.dtype)\n segments_perp[:, :-1] = box.transpose((0, 2, 1)).reshape((2, -1))\n segments_perp[:, -1] = 0 # Axis intersects (0,0)\n\n x0, x1 = segments_par[0, :, :, np.newaxis]\n y0, y1 = segments_par[1, :, np.newaxis, :]\n xp = segments_perp[0, np.newaxis, :]\n yp = segments_perp[1, :, np.newaxis]\n\n # Outer product produces boolean intersection predicate\n hits = (x0 <= xp) & (xp <= x1) & (y0 <= yp) & (yp <= y1)\n hits[:-1, :-1] &= ~np.kron(np.eye(n, dtype=bool), np.ones((2, 2), dtype=bool))\n hits[-1, -1] = 0\n\n k = segments_par.shape[-1]\n # Intersection coordinates\n xi = np.broadcast_to(xp, (k, k))[hits]\n yi = np.broadcast_to(yp, (k, k))[hits]\n return np.stack((xi, yi)) # (2, n')\n\n\ndef exclude_bounding(box: np.ndarray, xyi: np.ndarray) -> np.ndarray:\n xi, yi = xyi[:, :, np.newaxis]\n (\n (x0, x1),\n (y0, y1),\n ) = box[:, :, np.newaxis, :]\n\n return ~((x0 < xi) & (xi < x1) & (y0 < yi) & (yi < y1)).any(axis=1)\n\n\ndef choose_closest(xyi: np.ndarray) -> int:\n norm2 = np.einsum('ij,ij->j', xyi, xyi) # x**2 + y**2, product (2,n)\n return norm2.argmin()\n\n\ndef plot(box: np.ndarray, xyi: np.ndarray, xy_free: np.ndarray, free: np.ndarray, best: int) -> None:\n fig, ax = plt.subplots()\n ax.add_artist(Circle(xy_free[:, best], radius=0.03, fc='#A0FFA0A0', ec='black'))\n ax.set_xlim(-1.1, 1.1)\n ax.set_ylim(-1.1, 1.1)\n ax.scatter(*xyi[:, ~free], label='occluded')\n ax.scatter(*xy_free, label='free')\n ax.legend()\n\n for (x0, x1), (y0, y1) in box.transpose((2, 0, 1)):\n ax.add_artist(Rectangle((x0, y0), x1-x0, y1-y0, ec='black', fc='#80808020'))\n\n\ndef main() -> None:\n box = sample_data(90)\n xyi = intersect_points(box)\n free = exclude_bounding(box, xyi)\n xy_free = xyi[:, free]\n best = choose_closest(xy_free)\n plot(box, xyi, xy_free, free, best)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","post_id":45537,"sha256":"6637077f835d130cffa7ea8578142da4476921b98d0380a50f965b7d7ccb12a0","source_url":"https://scicomp.stackexchange.com/a/45537"}],"content_license":"CC BY-SA 4.0","domain":"computational_science","error_text_if_explicit":null,"group_id":"d86836aa7b471b88053ba3946e27afb910038bc268b2506894de8ecff8a7a9aa","id":"SCT-93741176d396566b0bc6e060","language":null,"library_or_tool":null,"problem_text":"I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.\n\n\n\n\n\nIf P is not inside any AABB, I don't need to do anything.\n\n\n\n\nIf P is inside one or more AABBs, I need to find the closest point to P that is outside all AABBs\n\n\n\n\nA point lying exactly on the edge/boundary of an AABB is considered valid (not inside). Therefore, when P is inside an AABB group, the desired result will normally be a point on the edge of one of the AABBs.\n\n\n\n\n\nIs there a known algorithm for this problem?\n\n\n\n\nThanks.","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":"ffbh","profile_url":"https://scicomp.stackexchange.com/users/57252/ffbh","user_type":"registered"},"created_at":"2026-09-03T03:48:42+00:00","raw_file":"raw/codex_api_v1/388d30597d4ce2c68c96b784f7bf92098fad8c44850c54687d3a3028cce83504_1790825358707940600_0.json","raw_sha256":"798328140b22ca830f996dc29957e2ed66bad007670d3eb6cfce6a5d1c2b82b7","revision_guid":"4165EEB0-A429-43DE-A4E0-E9FB5F902B12","revision_number":1,"revision_type":"single_user","revision_url":"https://scicomp.stackexchange.com/revisions/4165EEB0-A429-43DE-A4E0-E9FB5F902B12/view-source"}],"source_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":"45533","source_record_sha256":"6aa8e72f63abb74eb1342729a4b43d888897993bead981495b0e936275456a06","source_url":"https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them","transformation":"RegalFire V3 deterministic transformation; no LLM truth labels"},"question_html":"<p>I have a collection of axis-aligned bounding boxes (AABBs). The AABBs may overlap each other and may form multiple disconnected groups.</p>\n<ol>\n<li>If P is not inside any AABB, I don't need to do anything.</li>\n<li>If P is inside one or more AABBs, I need to find the closest point to P that is outside all AABBs</li>\n<li>A point lying exactly on the edge/boundary of an AABB is considered valid (not inside). Therefore, when P is inside an AABB group, the desired result will normally be a point on the edge of one of the AABBs.</li>\n</ol>\n<p>Is there a known algorithm for this problem?</p>\n<p>Thanks.</p>\n","question_title":"Find the closest point outside overlapping AABBs from a point inside them","selection_rule":"question troubleshooting lexeme plus literal pre block in question or answer; no root-cause inference","source_url":"https://scicomp.stackexchange.com/questions/45533/find-the-closest-point-outside-overlapping-aabbs-from-a-point-inside-them","split":"holdout"}