accepted_answer dict | code_blocks list | other_answers list | product string | question string | record_id string | selected_answer dict | selection_rule string | split string | thread dict |
|---|---|---|---|---|---|---|---|---|---|
{
"answer_html": "<p>Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.</p>\n<p>In this instance, I don't see why you need to decompose the 2d function <span class=\"math-container\">$f(\\text{time}, \\text{z})$</spa... | [
{
"block_index": 0,
"code_text": "\nm <- gam(y ~ s(time) + s(subject, bs = \"re\") + s(z) + ti(time, z), data = dat)\n",
"language": "unspecified",
"language_note": "Syntax-screened scientific code; language not asserted; not executed",
"post_id": 676821,
"sha256": "26b22c75d5bb179af3f2834ca... | [] | code_qa | I have repeated-measures data — multiple observations per subject over time — and a covariate that is constant within subject (e.g., a baseline characteristic measured once). My model includes a subject-level random intercept and I want to test whether this covariate's association with the outcome changes over time.
... | Scientific-Code-and-Analysis-QA:stats:676821 | {
"answer_html": "<p>Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.</p>\n<p>In this instance, I don't see why you need to decompose the 2d function <span class=\"math-container\">$f(\\text{time}, \\text{z})$</spa... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 676825,
"answers": [
{
"answer_html": "<p>Concurvity is only really an issue if it causes the estimated effects of other terms to change qualitatively when you remove one of the concurved terms.</p>\n<p>In this instance, I don't see why you need to decompose the 2d function <span c... |
null | [
{
"block_index": 0,
"code_text": "#\n# log(f(k; nu))\n#\nlf <- function(k, nu) {\n n <- length(k)\n i <- seq_len(n)\n sum(lbeta((rev(k) + 1)/2, (nu - cumsum(rev(k)) + rev(i) - 1) / 2))\n}\n#\n# Absolute multivariate moments.\n# (They can be fractional--but not negative.)\n#\nmu <- function(k, nu, sigma =... | [] | code_qa | The following is a multivariate Student's t distribution
$$ p_{\sigma^2}(\mathrm{x})= {\displaystyle {N_{\nu,\sigma^2}}\left[1+\frac{1}{\nu\sigma^2}\sum_{i=1}^nx_i^2\right]^{-(\nu +n)/2}}, \;\mathrm{x}=[x_1,\cdots,x_n]^{\top}\in \mathbb{R}^n,\;\nu>2,$$ where $N_{\nu,\sigma^2}=\frac {\Gamma \left[(\nu +n)/2\right]}{\Gam... | Scientific-Code-and-Analysis-QA:stats:676824 | {
"answer_html": "<p><strong>I offer an elementary solution.</strong> It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.</p>\n<p>There are other solutions that might provide simpler formulas but are less elementary (<em>e.g.</em>, us... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p><strong>I offer an elementary solution.</strong> It requires one substitution in an ordinary integral which, when repeated for each variable, yields a product of Beta function values.</p>\n<p>There are other solutions that might provide simp... |
{
"answer_html": "<p>It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your <span class=\"math-container\">$N(\\mu,\\sigma^2)$</span> example that means the asymptotic null distribution is the same as testing <span class=\"math-contai... | [
{
"block_index": 0,
"code_text": "# R code for simulation\n\nnsim=1000 # number of simulation\nnsample= 20000 # number of sample\n\nN= nsample\nT= rep(0, nsim)\n\nfor(i in 1: nsim){\n x= rnorm(mean=0, sd=1, n=N)\n muhat= mean(x)\n sigmahat= sqrt(mean((x- muhat)^2))\n ll_mu_in_H0 = sum(dnorm(x, m... | [] | code_qa | In fact I doubt if such kind of hypothesis test will be used in real work, but just out of curiosity I have a question on the property of such test.
Question. Consider an $n$-dimensional parameter $\theta= (\theta_1, \cdots, \theta_n)\in \Theta$ where $\Theta$ is an open subset in $\mathbb R^n$, and the hypothesis
... | Scientific-Code-and-Analysis-QA:stats:676842 | {
"answer_html": "<p>It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your <span class=\"math-container\">$N(\\mu,\\sigma^2)$</span> example that means the asymptotic null distribution is the same as testing <span class=\"math-contai... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 676849,
"answers": [
{
"answer_html": "<p>It is still true that the asymptotic null distribution of the LRT is the null distribution of a local Gaussian shift alternative. In your <span class=\"math-container\">$N(\\mu,\\sigma^2)$</span> example that means the asymptotic null dist... |
null | [
{
"block_index": 0,
"code_text": "library(vegan)\n\ndbrda(Y ~ pH + NO3 + MAT + Condition(Site))\n",
"language": "unspecified",
"language_note": "Syntax-screened scientific code; language not asserted; not executed",
"post_id": 676858,
"sha256": "e3b1e32f3f32fe01d572135a32ea1e26fbbec71586b485... | [] | code_qa | I am trying to evaluate which environmental variables drive variation in microbial communities. I have 5 samples collected at 15 sites, and for each sample, I have a microbial community, soil pH, soil NO3, and MAT.
I wanted to account for site when testing the effect of my environmental variables, so I tried:
l... | Scientific-Code-and-Analysis-QA:stats:676858 | {
"answer_html": "<p>There are two options for testing ordination models in <em>vegan</em>:</p>\n<ol>\n<li>model-based permutations, and</li>\n<li>design-based</li>\n</ol>\n<p>In 1. you model the site effects (like you have) and you assume the residuals are no conditionally independent, so you can just randomise the ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>There are two options for testing ordination models in <em>vegan</em>:</p>\n<ol>\n<li>model-based permutations, and</li>\n<li>design-based</li>\n</ol>\n<p>In 1. you model the site effects (like you have) and you assume the residuals are no co... |
{
"answer_html": "<p>Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample ... | [
{
"block_index": 0,
"code_text": "library(MatchIt); library(cobalt)\n\ndata(\"lalonde\", package = \"MatchIt\")\n\n# Full matching\nM1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,\n data = lalonde, method = \"full\", estimand = \"ATE\", tol = 1e-7,\n lin... | [] | code_qa | I was using full matching (using MatchIt, method = "full") to estimate the ATE. Now I want to extend this to examine a moderation effect by a categorical variable. I am fitting separate propensity score models within each moderator subgroup, and setting the estimand to ATE as well.
I am getting quite high weights in se... | Scientific-Code-and-Analysis-QA:stats:676867 | {
"answer_html": "<p>Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like the one you imposed, I would guess that the matched sample ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 676905,
"answers": [
{
"answer_html": "<p>Your approach is perfectly reasonable. It is true that using a caliper changes the target estimand, but it does so only when the remaining matched sample has a different covariate distribution from the overall sample. With a caliper like th... |
null | [
{
"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(y1... | [] | code_qa | 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 ... | Scientific-Code-and-Analysis-QA:stats:676935 | {
"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 "missing completely at random" (MCAR), as in the data that you simul... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"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 "missing completel... |
null | [
{
"block_index": 0,
"code_text": "Model <- lme( Height_BC ~ Treatments * Years * H_2007_BC_c,\n random = ~1|Blocks/BlocksTreatments/Tree_no,\n na.action = na.omit,\n correlation = corCAR1(form=~as.numeric(Years)|Blocks/BlocksTreatments/Tree_no),\n control = lmeC... | [] | code_qa | Hi could anyone please help me with this I would be really grateful. I am performing an mixed model ANCOVA to evaluate changes in a response variable (Height) over time and differences among treatments. The baseline measurement is included as a continuous covariate to account for initial differences among individuals.... | Scientific-Code-and-Analysis-QA:stats:676937 | {
"answer_html": "<p>If the treatment × time × baseline covariate interaction is significant, then the association between treatment/time and outcome depends on the value of the baseline covariate. It thus would make sense to evaluate treatment effects within each time point over a range of baseline covariate values.... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>If the treatment × time × baseline covariate interaction is significant, then the association between treatment/time and outcome depends on the value of the baseline covariate. It thus would make sense to evaluate treatment effects within eac... |
null | [
{
"block_index": 0,
"code_text": "data(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\nm2 <- lm(scale(mpg) ~ scale(wt) + scale(hp) + scale(disp), data = mtcars)\n\nround(coef(m1), 4)\n#> (Intercept) scale(wt)... | [] | code_qa | For homework assignment regarding stepwise regression (along with forward and backwards) the professor said to scale all the data except for the response and categorical variables.
I suppose I somewhat can understand the categorical variables they can only be binary values. However I don't understand why the respon... | Scientific-Code-and-Analysis-QA:stats:676958 | {
"answer_html": "<p>In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:</p>\n<pre class=\"lang-r prettyprint-override\"><code>data(mtcars)\n\n# Fit the same model with and without scaling the response\nm1 <- lm(mpg ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>In stepwise regression, scaling the response variable changes coefficient magnitudes but has no other meaningful effect. Here is an example in R:</p>\n<pre class=\"lang-r prettyprint-override\"><code>data(mtcars)\n\n# Fit the same model with ... |
null | [
{
"block_index": 0,
"code_text": "data(summer_cat)\nputu <- summer_cat$NUS003\nGUESS <- ctmm.guess(putu,interactive=FALSE) # automated model guess\nM.OUF <- ctmm.fit(putu,GUESS)\nwAKDE <- akde(putu,M.OUF,weights=TRUE)\nAKDE <- akde(putu,M.OUF)\n\n#Plot\nEXT <- extent(AKDE,level=0.95) #DOP is missing. Assume... | [] | code_qa | I am doing a study on my university cats' home ranges. The tracker we are using is Damien Farine's Bluetooth Low-energy (BLE) beacons. The tags transmit a signal that can be detected by an Apple device. The phone receiving the signal captures a location from its own GPS and uploads the identity of the tag and its locat... | Scientific-Code-and-Analysis-QA:stats:676997 | {
"answer_html": "<p>Welcome to CV.<br />\nThis will not be an answer to your direct questions, nor will it be a particularly "statistical" answer, but a series of remarks, too long to fit in comments, which I hope can help, and a final remark, which unfortunately may not "help"...</p>\n<p>First, ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>Welcome to CV.<br />\nThis will not be an answer to your direct questions, nor will it be a particularly "statistical" answer, but a series of remarks, too long to fit in comments, which I hope can help, and a final remark, which un... |
{
"answer_html": "<p><strong>Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation</strong>. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the esti... | [
{
"block_index": 0,
"code_text": "#\n# Negative log likelihood of the Beta distribution.\n# `lgm` is the log geometric mean of the data;\n# `lgm1` is the log geometric mean of the complements of the data.\n#\nLambda <- function(theta, lgm, lgm1) {\n alpha <- exp(theta[1])\n beta <- exp(theta[2])\n lbeta(... | [] | code_qa | Suppose $X_1, \dots, X_n \overset{\text{iid}}{\sim} \text{Beta}(\alpha, \beta)$, and I want to estimate the parameters by maximum likelihood.
I know that:
$$\hat\mu = \frac{\hat\alpha}{\hat\alpha + \hat\beta}, \qquad \hat\sigma^2 = \frac{\hat\alpha\hat\beta}{(\hat\alpha+\hat\beta)^2(\hat\alpha+\hat\beta+1)}.$$
... | Scientific-Code-and-Analysis-QA:stats:677021 | {
"answer_html": "<p><strong>Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation</strong>. This amounts to selecting parameter values of interest and repeatedly creating a random sample determined by those parameters and recording the esti... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 677036,
"answers": [
{
"answer_html": "<p><strong>Because it can be difficult or impossible to analyze numerical solutions mathematically, one would naturally resort to simulation</strong>. This amounts to selecting parameter values of interest and repeatedly creating a random sam... |
null | [
{
"block_index": 0,
"code_text": "glm(Y ~ X * Z + C1 + C2, family = binomial)\n",
"language": "unspecified",
"language_note": "Syntax-screened scientific code; language not asserted; not executed",
"post_id": 677023,
"sha256": "c4f9bf8f0235bd91571ecb82f9237cf525d1071c10a1c4cd61809e1b52959402... | [
{
"answer_html": "<p>The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.</p>\n<p>I don't know of a book that states this, but you can either a) Do the math and show it or b) Plug in different values of X, Z, C1, an... | code_qa | Logistic regression:
glm(Y ~ X * Z + C1 + C2, family = binomial)
I know β_X and β_Z are conditional (effect when the other is 0) and shouldn't be read as main effects.
Does this also apply to C1, which isn't in the interaction? Or is exp(β_C1) still the ordinary adjusted OR, with the p value testing the or... | Scientific-Code-and-Analysis-QA:stats:677023 | {
"answer_html": "<h3>Edit:</h3>\n<p>The original answer focused more on OLS, when the question is about the logistic case. I'm leaving the commenters' suggested citations but added on another to mine and revamped the example</p>\n<hr />\n<ul>\n<li>from Whuber: <a href=\"https://archive.org/details/dataanalysisregr00... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>The regression coefficients for variables not in the interaction are main effects, conditional on all the other variables, including the interaction.</p>\n<p>I don't know of a book that states this, but you can either a) Do the math and show ... |
null | [
{
"block_index": 0,
"code_text": "library(cluster)\nN <- 20\nfor (n in 1:N) {\n res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power=2)\n gs[n] <- maxSE(res$Tab[,\"gap\"],res$Tab[,\"SE.sim\"], method=\"Tibs2001SEmax\")\n}\ntable(gs)\n",
"language": "unspe... | [] | code_qa | While trying the gap statistics for K-Means to determine the number of clusters in the Iris dataset, I have noticed that the results are random. I have tried the following:
library(cluster)
N <- 20
for (n in 1:N) {
res <- clusGap(iris[,-5], function(x, k){kmeans(x,k,nstart=50)}, K.max=6, B=500, verbose=F, d.power... | Scientific-Code-and-Analysis-QA:stats:677058 | {
"answer_html": "<p>The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.</p>\n<p>Other potential issues: Note that kmeans implicitly looks for clusters that are spherical and ha... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>The gap statistic will indeed be the more stable the larger you choose nstart and the larger you choose B, but you seem to be aware of this, and the values you chose don't seem critically low.</p>\n<p>Other potential issues: Note that kmeans ... |
{
"answer_html": "<p>The AI-generated code manually slices <code>{DHARMa}</code>'s internal arrays, which is fragile. The cleaner approach would be to use <code>recalculateResiduals()</code> with <code>NA</code> for the other season's rows, letting DHARMa's NA handling drop them during grouping:</p>\n<pre class=\"lan... | [
{
"block_index": 0,
"code_text": "library(mgcv)\nlibrary(gratia)\nlibrary(DHARMa)\n\nsystem.time(\n by <- gam(total_count ~ \n \n offset(log(area_sampled)) +\n \n s(CYR, by = fSeason) +\n fSeason + \n \n s(s... | [] | code_qa | I have 2 time series in abundance that I'm modeling by a 2-level factor in mgcv , by "fSeason" (wet/dry), and following advice here (https://stackoverflow.com/questions/78182559/autocorrelation-in-gam-r), I should be splitting a test for auto-correlation by each factor level. I'm just not sure how to do that. Apologies... | Scientific-Code-and-Analysis-QA:stats:677062 | {
"answer_html": "<p>The AI-generated code manually slices <code>{DHARMa}</code>'s internal arrays, which is fragile. The cleaner approach would be to use <code>recalculateResiduals()</code> with <code>NA</code> for the other season's rows, letting DHARMa's NA handling drop them during grouping:</p>\n<pre class=\"lan... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 677064,
"answers": [
{
"answer_html": "<p>The AI-generated code manually slices <code>{DHARMa}</code>'s internal arrays, which is fragile. The cleaner approach would be to use <code>recalculateResiduals()</code> with <code>NA</code> for the other season's rows, letting DHARMa's NA ... |
{
"answer_html": "<p>I see what's going on here. When <code>refit = F</code> DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at <em><strong>18</strong></em>:</p>\n<pre><code># library(tidyverse)\n> shiny_toad %>% group... | [
{
"block_index": 0,
"code_text": "shiny_toad$fSeason <- as.factor(shiny_toad$fSeason)\nshiny_toad$fSite <- as.factor(shiny_toad$fSite)\nshiny_toad$fCYR <- as.factor(shiny_toad$fCYR)\n\nshiny_toad$fDiet_presence <- as.factor(shiny_toad$fDiet_presence)\nshiny_toad$fDiet_presence <- relevel(shiny_toad$fDiet_pr... | [] | code_qa | Are long tails in a fitted vs. simulated residuals plot from DHARMa a sign of over-fitting (or any other issues)? Do they make the test for dispersion overly optimistic (p-value > 0.05)? I'm not sure if this is a problem simply because it's not significant, but are there ways to model theta in mgcv? Is it necessary her... | Scientific-Code-and-Analysis-QA:stats:677079 | {
"answer_html": "<p>I see what's going on here. When <code>refit = F</code> DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at <em><strong>18</strong></em>:</p>\n<pre><code># library(tidyverse)\n> shiny_toad %>% group... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 677089,
"answers": [
{
"answer_html": "<p>I see what's going on here. When <code>refit = F</code> DHARMa uses raw residuals and your raw response values are kind of crazy. 90% are zero, the second biggest number is 7 and then it maxes out at <em><strong>18</strong></em>:</p>\n<pre>... |
null | [
{
"block_index": 0,
"code_text": "modules <- c(\n \"MA101\",\"MA102\",\"MA103\",\"MA201\",\"MA202\",\"MA301\",\"MA302\",\n \"FR101\",\"FR102\",\"FR104\",\"FR201\",\"FR202\",\"FR203\",\"FR301\",\n \"EN101\",\"EN102\",\"EN201\",\"EN202\",\"EN203\",\"EN301\",\"EN302\"\n)\ntotals <- sample(30:400, length(mod... | [] | code_qa | I have records of student grades for some university courses. I want to investigate whether any of these courses award significantly different proportions of the best (A) or worst (F) grades, compared to the other courses.
I have individual student data, but some aggregated dummy data would be:
modules <- c(
... | Scientific-Code-and-Analysis-QA:stats:677095 | {
"answer_html": "<p>Welcome to CV!</p>\n<p>So you want to compare 2 proportions; e.g. “<em>Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?</em>”.</p>\n<p>Well, the “canonical” way to compare 2 proportions is via a <a... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>Welcome to CV!</p>\n<p>So you want to compare 2 proportions; e.g. “<em>Is the proportion of students who receive an A grade in MA101 the same as the proportion of students who receive an A grade in all other MA courses?</em>”.</p>\n<p>Well, t... |
null | [
{
"block_index": 0,
"code_text": "library(lme4)\n\nmodel <- lmer(log(sd_depth) ~ Grazing * Country + (1|PlotID), data = sd_data)\n",
"language": "unspecified",
"language_note": "Syntax-screened scientific code; language not asserted; not executed",
"post_id": 677129,
"sha256": "2709c370d4eb7... | [] | code_qa | I have been working on analysing ecological data for different countries (within each country there are two groups (grazed/ungrazed) and plots (5 per group) which contain subplots (pseudoreplicates)
My sample size: 9 countries with each 2 groups of 5 plots with 4 subplots, so 20 measurepoints per group, 40 measure ... | Scientific-Code-and-Analysis-QA:stats:677129 | {
"answer_html": "<p>Putting together the comments:</p>\n<blockquote>\n<p>Is that p-value enough to fit the Linear mixed model anyway?</p>\n</blockquote>\n<p>Don't rely on such <em>p</em>-values for making decisions about the model to use. As @mastropi notes, with large data sets it's possible to get "statistica... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>Putting together the comments:</p>\n<blockquote>\n<p>Is that p-value enough to fit the Linear mixed model anyway?</p>\n</blockquote>\n<p>Don't rely on such <em>p</em>-values for making decisions about the model to use. As @mastropi notes, wit... |
{
"answer_html": "<p>You are using R version 4.6.1. Well, since R 4.6.0, from <a href=\"https://cran.r-project.org/doc/manuals/r-release/NEWS.html\" rel=\"noreferrer\">R News</a>:</p>\n<blockquote>\n<p>wilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hoth... | [
{
"block_index": 0,
"code_text": "df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30, \n30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c(\"tbl_df\", \n\"tbl\", \"data.frame\"))\n",
"language": "unspecified",
"... | [
{
"answer_html": "<p>Can you provide a <a href=\"https://reprex.tidyverse.org/\" rel=\"nofollow noreferrer\"><code>{reprex}</code></a>? I'm getting a warning when I run your code</p>\n<pre class=\"lang-r prettyprint-override\"><code>df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21, \n ... | code_qa | I ran wilcox.test(df$PostScore, df$PreScore, conf.int = TRUE, paired=TRUE, exact = TRUE) on the following data set:
df <- structure(list(PreScore = c(16, 23, 17, 24, 22, 27, 20, 18, 21,
26, 25, 23, 18), PostScore = c(20, 31, 17, 31, 32, 31, 31, 30,
30, 32, 30, 31, 17)), row.names = c(NA, -13L), class = c("tbl_df"... | Scientific-Code-and-Analysis-QA:stats:677135 | {
"answer_html": "<p>You are using R version 4.6.1. Well, since R 4.6.0, from <a href=\"https://cran.r-project.org/doc/manuals/r-release/NEWS.html\" rel=\"noreferrer\">R News</a>:</p>\n<blockquote>\n<p>wilcox.test() can now perform exact (conditional) inference in case\nof ties. Based on contributions by Torsten Hoth... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 677139,
"answers": [
{
"answer_html": "<p>Can you provide a <a href=\"https://reprex.tidyverse.org/\" rel=\"nofollow noreferrer\"><code>{reprex}</code></a>? I'm getting a warning when I run your code</p>\n<pre class=\"lang-r prettyprint-override\"><code>df <- structure(list(Pre... |
null | [
{
"block_index": 0,
"code_text": "library(splines)\nx_i <- 1.5\nbasis_matrix <- splines::bs(x_i,\n knots = c(-2, -1, 0, 1, 2, 3, 4, 5), # interior knots\n Boundary.knots = c(-3, 6), # boundary knots\n degree = 3)... | [
{
"answer_html": "<p>Amplifying @Glen_b's answer and @whuber's comment: here's the plot of the basis elements (for <span class=\"math-container\">$-3 \\lt x \\lt 6$</span>), with the ones that are non-zero at <span class=\"math-container\">$x=1.5$</span> highlighted:</p>\n<p><a href=\"https://i.sstatic.net/7o5j... | code_qa | I've been studying how splines::bs() builds its basis matrix, and I'm trying to fully understand why the returned matrix has so many zero entries.
The worked example in Ken Koon Wong's blog post "Understanding Basis Spline (B-spline) By Working Through Cox-deBoor Algorithm", reproduced below:
library(splines)
x... | Scientific-Code-and-Analysis-QA:stats:677137 | {
"answer_html": "<p>B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).</p>\n<p>Consequently the predictor columns will be zero out of the local interval (described in terms of the nearby few knots), and hence for small such intervals will be mostl... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>B-splines are designed to be local* (only nearby x-values affect the relevant predictor, and hence the fitted response).</p>\n<p>Consequently the predictor columns will be zero out of the local interval (described in terms of the nearby few k... |
null | [
{
"block_index": 0,
"code_text": "modelOrdinalWordCat <- clmm(Rating_Resp ~ WordCat * Group * Session + (1|participant) + (1|Word), data = completed, link = \"logit\")\n",
"language": "unspecified",
"language_note": "Syntax-screened scientific code; language not asserted; not executed",
"post_id... | [] | code_qa | I am a beginner in Ordinal Models looking for some help. I am doing a 3-factor model, primarily interested in the effect of the 3 way interaction on the results. I have to say that I come from making Linear mixed effect models and initially assumed it would largerly transfer. However, I do not know how to report the re... | Scientific-Code-and-Analysis-QA:stats:677183 | {
"answer_html": "<p>Ordinal models pose (at least) two difficulties in interpretation beyond standard linear models.</p>\n<p>First, the coefficients are in <em>log-odds</em> scales, which can be hard to think about even in logistic regression. A log-odds coefficient in ordinal regression is for the change of one out... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>Ordinal models pose (at least) two difficulties in interpretation beyond standard linear models.</p>\n<p>First, the coefficients are in <em>log-odds</em> scales, which can be hard to think about even in logistic regression. A log-odds coeffic... |
{
"answer_html": "<p>No you can not estimate the <span class=\"math-container\">$\\theta_i$</span> variance for <span class=\"math-container\">$k = 1$</span>. The relevant concept is the beta-binomial distribution(<a href=\"https://en.wikipedia.org/wiki/Beta-binomial_distribution\" rel=\"nofollow noreferrer\">https:/... | [
{
"block_index": 0,
"code_text": "set.seed(42)\nn <- 20\nk <- 10\nalpha <- 3\nbeta <- 2 \nmu <- alpha / (alpha + beta) \n\nsubjects <- factor(paste(\"Subject\", 1:n), levels = paste(\"Subject\", n:1))\n\n# one theta (true probability) per subject \ntheta <- numeric(n)\nfor (i in 1:n)... | [
{
"answer_html": "<p>After thinking about this, I think I know how to do this. When <span class=\"math-container\">$k=1$</span>, it is possible to estimate the population mean but it is impossible to estimate the variance of the population.</p>\n<p>However, it is possible to estimate the variance of the mean es... | code_qa | Here is a hierarchical data generating process:
(Population) Layer 1: $$\theta_i \overset{\text{iid}}{\sim} \text{Beta}(\alpha,\ \beta), \qquad i = 1, \dots, n$$
(Individual) Layer 2: $$y_{ij} \mid \theta_i \overset{\text{iid}}{\sim} \text{Bernoulli}(\theta_i), \qquad j = 1, \dots, k$$
There are two ... | Scientific-Code-and-Analysis-QA:stats:677226 | {
"answer_html": "<p>No you can not estimate the <span class=\"math-container\">$\\theta_i$</span> variance for <span class=\"math-container\">$k = 1$</span>. The relevant concept is the beta-binomial distribution(<a href=\"https://en.wikipedia.org/wiki/Beta-binomial_distribution\" rel=\"nofollow noreferrer\">https:/... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 677231,
"answers": [
{
"answer_html": "<p>No you can not estimate the <span class=\"math-container\">$\\theta_i$</span> variance for <span class=\"math-container\">$k = 1$</span>. The relevant concept is the beta-binomial distribution(<a href=\"https://en.wikipedia.org/wiki/Beta-bi... |
null | [
{
"block_index": 0,
"code_text": "dat$t_elapsed <- as.numeric(\n difftime(dat$datetime, min(dat$datetime), units = \"days\")\n)\nThis\n",
"language": "unspecified",
"language_note": "Syntax-screened scientific code; language not asserted; not executed",
"post_id": 677242,
"sha256": "578bb12... | [] | code_qa | I am running an experiment in which 1 participant is randomized multiple times to different treatments, and we are assessing the effect of treatment on blood pressure (BP).
The data collection protocol is as follows:
• BP is measured every day at two time points: 12:00 and 20:00, for approximately 3 months.
... | Scientific-Code-and-Analysis-QA:stats:677242 | {
"answer_html": "<p>I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern about the <code>corCAR1</code> correlation structure.</p>\n... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>I would treat the 2 observations that are only 1 minute apart as technical replicates that are unlikely to differ biologically. Average them and the associated measurement times instead of using them separately. That removes your concern abou... |
null | [
{
"block_index": 0,
"code_text": "ratlong <- read.csv(\"ratlong.csv\") |>\n mutate(Rat = factor(Rat), Group = as_factor(Group)) |>\n mutate(time = as.factor(as.numeric(time)))\n\nmodel <- gls(Weight ~ time*Group,\n correlation = corSymm(form = ~ as.integer(time) | Rat),\n w... | [] | code_qa | I have been tasked with understanding why normalized residuals between R and Stata are different when using mixed models (i.e. the nlme package in R).
What I have found is that the residuals are both theoretically computed the same way: norm_residuals = sigma^(-1) * Lambda^(-1/2) * residuals
This is based on th... | Scientific-Code-and-Analysis-QA:stats:677243 | {
"answer_html": "<p>Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does not make any of the methods less valid than any other. ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>Upon further testing, it seems like all methods of normalizing the residuals will approximate uncorrelated standard normal distributions in large samples. In smaller samples, the difference between methods can look quite stark, but that does ... |
{
"answer_html": "<h3>UPDATE</h3>\n<p>I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up... | [
{
"block_index": 0,
"code_text": "## generate the data\nset.seed(86709) \n## Poisson, not normal!\ng1 <- rpois(n = 12, lambda = 25)\ng2 <- rpois(n = 11, lambda = 20)\noutcome <- c(rep(1, 12), rep(0, 11))\nwidth <- c(g1,g2)\nd <- data.frame(outcome, width)\n\nm <- glm(outcome ~ width, family = binomial, data... | [] | code_qa | I'm writing my medical thesis and I want to test our research group's hypothesis that the width of the foramen magnum can predict response or non-response to a certain surgical intervention in a neurological disease. The sample is however quite small (only 23 patients) so any biological signal whould have to be quite ... | Scientific-Code-and-Analysis-QA:stats:677262 | {
"answer_html": "<h3>UPDATE</h3>\n<p>I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you use to create predictions / classifications is really up... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 677263,
"answers": [
{
"answer_html": "<h3>UPDATE</h3>\n<p>I realized I didn't really address the crux of your question, which seems to be about fitting a logistic regression to obtain predicted probabilities and using those predictions to construct an ROC curve. Whatever means you... |
{
"answer_html": "<p>I think you can find the mean and variance of <span class=\"math-container\">$\\bar y$</span> analytically. Clearly <span class=\"math-container\">$\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$</span> and, using the law of total variance <span class=\"math-container\">$$\\operatorname{Var... | [
{
"block_index": 0,
"code_text": "set.seed(2026)\n\nmu_vals <- c(0.01, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.99)\nn_var <- 10\nn_vals <- c(5, 15, 30, 50, 100, 200)\nk_vals <- c(1, 2, 3, 4, 5, 6)\nR <- 2000\nconf <- 0.95\n\nscenarios <- data.frame()\n\nfor (mu in mu_vals)... | [
{
"answer_html": "<p>I would not go through mean and variance here. Your model for data generation is based on <span class=\"math-container\">$\\alpha$</span> and <span class=\"math-container\">$\\beta$</span> right? So why not work with them? Your population variable <span class=\"math-container\">$\\theta$</s... | code_qa | Here is a hierarchical data generating process (DGP):
(Population) Layer 1: $$\theta_i \overset{\text{iid}}{\sim} \text{Beta}(\alpha,\ \beta), \qquad i = 1, \dots, n$$
(Individual) Layer 2: $$y_{ij} \mid \theta_i \overset{\text{iid}}{\sim} \text{Bernoulli}(\theta_i), \qquad j = 1, \dots, k$$
$$\mu = ... | Scientific-Code-and-Analysis-QA:stats:677266 | {
"answer_html": "<p>I think you can find the mean and variance of <span class=\"math-container\">$\\bar y$</span> analytically. Clearly <span class=\"math-container\">$\\mathbb E[\\bar y]=\\frac{\\alpha}{\\alpha+\\beta}$</span> and, using the law of total variance <span class=\"math-container\">$$\\operatorname{Var... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 677268,
"answers": [
{
"answer_html": "<p>I would not go through mean and variance here. Your model for data generation is based on <span class=\"math-container\">$\\alpha$</span> and <span class=\"math-container\">$\\beta$</span> right? So why not work with them? Your population v... |
null | [
{
"block_index": 0,
"code_text": "#preview of seeddamage\n year planting_block plant_genotype plant_trait_a plant_trait_b seeds_total seeds_beetle_damaged prop_beetle_damaged\n1 2024 1 1 yes short 100 59 0.59000000\n2 2024 ... | [] | code_qa | I'm trying to decide which GLMM distribution is best for my data.
I want to determine how plant_trait_a and plant_trait_b affect beetle seed damage.
There were two levels of plant_trait_a and two levels of plant_trait_b that made up 4 treatment groups. We selected 20 plant_genotypes for our field experiment, ea... | Scientific-Code-and-Analysis-QA:stats:677298 | {
"answer_html": "<p>I think a <em>non</em> Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is the wrong direction to go with data that have a known i... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>I think a <em>non</em> Z-I beta-binomial looks perfectly adequate, and I personally would push back against your stats consultant — in particular, the Beta distribution (which assumes a continuous distribution of outcomes between 0 and 1) is ... |
null | [
{
"block_index": 0,
"code_text": "import numpy as np\nimport scipy\nimport cvxpy as cp\nimport matplotlib.pyplot as plt\nimport math\n\ndef ridge_objective(x, A, y, lmbda):\n return 0.5 * np.linalg.norm(A @ x - y)**2 + 0.5 * lmbda * np.linalg.norm(x)**2\n\ndef gradient_descent(A, y, lmbda, beta, num_iter... | [] | code_qa | I have this Exercise in my Numerical Optimization class and here it is:
In this exercise, you will consider the ridge regression problem:
$$\min_{x \in \mathbb{R}^n}\frac{1}{2}\|Ax-y\|^2_2+\frac{\lambda}{2}\|x\|^2_2$$
which aims to recover a point $x_{\text{opt}}$ from noisy linear measurements $y$. For $n=100$, $m... | Scientific-Code-and-Analysis-QA:scicomp:45100 | {
"answer_html": "<p>Accelerated Methods (Momentum / NESTEROV / FISTA) in their vanilla form do not guarantee a descent direction.<br />\nHence one might get steps where the objective is not minimized.</p>\n<p>There are monotonic versions of some of the methods.<br />\nSee <a href=\"https://ieeexplore.ieee.org/docume... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>Accelerated Methods (Momentum / NESTEROV / FISTA) in their vanilla form do not guarantee a descent direction.<br />\nHence one might get steps where the objective is not minimized.</p>\n<p>There are monotonic versions of some of the methods.<... |
null | [
{
"block_index": 0,
"code_text": "import numpy as np\nimport matplotlib.pyplot as plt\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\ndef logistic_objective(theta, X, y, lmbda):\n yz = y * (X @ theta)\n my_loss = np.log(1 + np.exp(-yz)).sum()\n r = 0.5 * lmbda * np.linalg.norm(theta)**2\n ret... | [] | code_qa | Consider the regularized logistic regression problem:
$$\min_{\theta \in \mathbb{R}^n}\sum_{i=1}^m \ln \left(1+e^{-y_i\theta^T x_i}\right)+\frac{\lambda}{2}\big\lVert\theta\big\rVert^2_2.$$
Here, $y_i \in \{\pm 1\}$ are binary labels for the data points $x_i \in \mathbb{R}^n$ and we are trying to find the best vector $... | Scientific-Code-and-Analysis-QA:scicomp:45105 | {
"answer_html": "<p>The error was that I stated <code>ja = 1 / (1+np.exp(-yz))</code> , but instead I should state <code>ja = 1 / (1+np.exp(yz))</code>.</p>\n",
"answer_id": 45106,
"answer_text": "The error was that I stated ja = 1 / (1+np.exp(-yz)) , but instead I should state ja = 1 / (1+np.exp(yz)).",
"answ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>The error was that I stated <code>ja = 1 / (1+np.exp(-yz))</code> , but instead I should state <code>ja = 1 / (1+np.exp(yz))</code>.</p>\n",
"answer_id": 45106,
"answer_text": "The error was that I stated ja = 1 / (1+np.exp(-yz)) ... |
null | [
{
"block_index": 2,
"code_text": "#include <iostream>\n#include <fstream>\n#include <cmath>\nint main() {\n int nx, nt;\n double dx, dt, mu, lambda;\n std::ifstream fin(\"input.txt\");\n fin >> nx >> nt >> dx >> dt >> mu >> lambda;\n fin.close();\n int *sup = new int[nx];\n int *sdn = n... | [] | code_qa | i'm trying to simulate one dimensional phi^4 theory.
$$\frac{\partial^2φ}{\partial t^2}-\frac{\partial^2φ}{\partial x^2}+m^2φ+λφ^3=0$$
I'm using leapfrog (https://en.wikipedia.org/wiki/Leapfrog_integration) method to integrate these equations of motion. I'm using periodic boundary conditions in space. The initial condi... | Scientific-Code-and-Analysis-QA:scicomp:45112 | {
"answer_html": "<p>There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.</p>\n<p><span class=\"math-container\">$$\\begin{align*}\n\\frac{\\partial \\phi}{\\partial t} - ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>There is likely a bug in your code, which others have given you good insight about in the comments. As an alternative approach, you can recast your original PDE into a system of two first order PDEs.</p>\n<p><span class=\"math-container\">$$\... |
null | [
{
"block_index": 0,
"code_text": "import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.model_selection import train_test_split\nimport operator\nimport sympy\n\nnp.random.seed(42)\nn = 1000\nx1 = np.r... | [] | code_qa | I wrote a symbolic regression tool (https://github.com/Julien-Livet/SymbolicRegression) in Python. It is possible to give unary and binary operators. If nothing is specified, I want to determine potential operators. So, I want to know if there is an approach to find necessary operators. I tried machine learning and cor... | Scientific-Code-and-Analysis-QA:scicomp:45114 | {
"answer_html": "<p>In the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:</p>\n<ul>\n<li><a href=\"https://doi.org/10.1126/sciadv.aay2631\" rel=\"nofoll... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>In the context of your attempt to use machine learning, I think these two publications could be relevant, since they are fitting a neural network to the data first to then inform the search for the symbolic expression:</p>\n<ul>\n<li><a href=... |
null | [
{
"block_index": 0,
"code_text": "from scipy.optimize import minimize\n\n\ndef loss(free_euler_angles, skeleton, target):\n joints = compute_new_position(free_euler_angles, skeleton) # based on what the new game can handle\n # Compute an appropriate error here, like taking the positions of all the jo... | [] | code_qa | CONTEXT FOR THE QUESTION
I'm porting animations between two video games from the same developer that use mostly the same skeleton and coordinate system. So in general, data can be ported from the source to destination exactly as it is. However, while both games use Euler angles to represent bone rotation data, the ... | Scientific-Code-and-Analysis-QA:scicomp:45129 | {
"answer_html": "<p>What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.</p>\n<p>One strategy one could employ here is (constrained) Inverse Kinematics, though ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>What you wish to achieve is a equivalent position of the entire limb, so your solutions can't be determined by looking at the angles alone; the orientation of length of the arms between the joints also matter.</p>\n<p>One strategy one could e... |
null | [
{
"block_index": 0,
"code_text": "# freq to time:\ndef ifft(A_w):\n return np.fft.fftshift(np.fft.ifft(np.fft.ifftshift(A_w))) / dt\n\n# time to freq\ndef fft(A_t):\n return np.fft.fftshift(np.fft.fft(np.fft.ifftshift(A_t))) * dt\n\n\n# Dispersion and absorption operators for air and fused silica\nD_o... | [] | code_qa | I'm implementing in Python the split-step Fourier method (SSFM) to solve the non-linear envelope propagation equation (NEE), and I'm including second and third order dispersion (GDD, TOD), self-phase modulation (SPM) and self-steepening. I'm pretty happy with the results of the simulation: I can predict, at least in th... | Scientific-Code-and-Analysis-QA:scicomp:45185 | {
"answer_html": "<p>I might have found the solution, of which I'm listing the main points/observations here below:</p>\n<ul>\n<li>the FFT/IFFT implementation in the code is consistent with the Fourier transform computed as <span class=\"math-container\">$\\tilde{F}(\\omega)=\\int^{+\\infty}_{-\\infty}f(t)e^{-i\\omeg... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>I might have found the solution, of which I'm listing the main points/observations here below:</p>\n<ul>\n<li>the FFT/IFFT implementation in the code is consistent with the Fourier transform computed as <span class=\"math-container\">$\\tilde... |
null | [
{
"block_index": 0,
"code_text": "import math\n\ndef calculate_expression():\n n = 660\n k = 5\n\n # Calculate the outer binomial coefficient (660 choose 5)\n outer_binomial_coefficient = math.comb(n, k)\n\n sum_terms = 0\n\n # Iterate for the summation from j = 1 to 660\n for j in rang... | [] | code_qa | I have found this paper: http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf (http://www.unige.ch/math/folks/velenik/Vulg/Paninimania.pdf)
On page 4 I am trying to turn this:
[image: enter image description here; source: https://i.sstatic.net/Bod2tUzu.jpg] (https://i.sstatic.net/Bod2tUzu.jpg)
into p... | Scientific-Code-and-Analysis-QA:scicomp:45236 | {
"answer_html": "<p>The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,000 digits each). Ways to help it out: expand the binom... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>The quantities in this expression are challenging for any fixed-precision numerical system. Python supports arbitrary-precision fractional math natively, and it does fine here (despite the numerator and denominator being integers with over 4,... |
null | [
{
"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\nd... | [] | code_qa | 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.
I strongly suspect that the issue... | Scientific-Code-and-Analysis-QA:scicomp:45246 | {
"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... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"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 tu... |
null | [
{
"block_index": 1,
"code_text": "#include <stdio.h>\n#include <complex.h>\n#include <math.h>\nconst int size = 16;\nconst double m = 1.0;\nconst double dt = 0.1;\nconst double xmax = 2.0;\nconst double dx = 2*xmax/size;\nvoid mult(complex A[size][size], complex B[size][size], double x_a, double x_b, int n)... | [] | code_qa | I'm trying to code the path integral simulation described in this (https://arxiv.org/pdf/quant-ph/9511042) article. I followed all the instructions, but no matter how hard I try, my program won't work. Could someone please explain what I am doing wrong?
In my code, I first construct the short-time propagator matrix... | Scientific-Code-and-Analysis-QA:scicomp:45261 | {
"answer_html": "<p>The <strong>fastest</strong> way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before returning (isNan(), check for expected sign, ...) These he... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>The <strong>fastest</strong> way forward for debugging something like this might be to break up your main() and mult() method into smaller mathematical helper-functions. Within these helper functions you can do some sanity checking before ret... |
{
"answer_html": "<h2>Eigenvector matrices are not unique.</h2>\n<p>The standard computation <span class=\"math-container\">$AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$</span> tells you that <span class=\"math-container\">$U$</span> is <em>an</em> eigenvector matrix of <span class=\"math-... | [
{
"block_index": 0,
"code_text": "import numpy as np\n\nA=np.array([\n [1,2],\n [4,5],\n [7,8]])\nAt=A.T\nAtA=np.matmul(At,A)\nAAt=np.matmul(A,At)\n\neigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)\neigenvalues_AtA, eigenvectors_AtA = np.linalg.eig(AtA)\n\nidx_descending = eigenvalues_AAt.ar... | [] | code_qa | Recently, I have been learning singular value decomposition (SVD). I want to compute SVD manually with NumPy . Here is my code
import numpy as np
A=np.array([
[1,2],
[4,5],
[7,8]])
At=A.T
AtA=np.matmul(At,A)
AAt=np.matmul(A,At)
eigenvalues_AAt, eigenvectors_AAt = np.linalg.eig(AAt)
eigenvalues_AtA, ei... | Scientific-Code-and-Analysis-QA:scicomp:45311 | {
"answer_html": "<h2>Eigenvector matrices are not unique.</h2>\n<p>The standard computation <span class=\"math-container\">$AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$</span> tells you that <span class=\"math-container\">$U$</span> is <em>an</em> eigenvector matrix of <span class=\"math-... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 45312,
"answers": [
{
"answer_html": "<h2>Eigenvector matrices are not unique.</h2>\n<p>The standard computation <span class=\"math-container\">$AA^* = U\\operatorname{diag}(s^2_1,\\dots,s^2_{\\min}, 0, \\dots ,0)U^*$</span> tells you that <span class=\"math-container\">$U$</span> ... |
{
"answer_html": "<p>The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.</p>\n<p>This is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all ... | [
{
"block_index": 0,
"code_text": "class PINN(nn.Module):\n def __init__(self, num_hidden, dim_hidden, act=torch.sin):\n super().__init__()\n self.layer_in = nn.Linear(3, dim_hidden)\n self.layer_out = nn.Linear(dim_hidden, 1)\n self.middle_layers = nn.ModuleList([\n ... | [
{
"answer_html": "<p>I am not an expert on neural nets. The size of the net you state strikes me as odd. You state that it has 4 layers with 80 degrees of freedom each, while the problem you try to solve has 30^3 degrees of freedom.</p>\n<p>In classical discretizations you have to evaluate the derivatives at ea... | code_qa | I am implementing a Physics-Informed Neural Network (PINN) in PyTorch to solve the 2D acoustic wave equation with a point source. The model trains and converges in terms of loss, and the solution propagates outward from the source, but the resulting wavefronts are not clean circular waves. Instead, they appear distorte... | Scientific-Code-and-Analysis-QA:scicomp:45326 | {
"answer_html": "<p>The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.</p>\n<p>This is not part of your question, but I'll comment on it anyway: In general, I am not convinced PINNs are at all ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 45327,
"answers": [
{
"answer_html": "<p>The NN does not know anything about the qualitative properties of the equations. If these properties are important to you, then you should include them in your loss function.</p>\n<p>This is not part of your question, but I'll comment on it ... |
null | [
{
"block_index": 0,
"code_text": "import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse as sp\nfrom scipy.optimize import milp, LinearConstraint\n\n\ndef sample_data(rand: np.random.Generator, n: int = 1501) -> tuple[\n np.ndarray, np.ndarray, np.ndarray,\n]:\n x = np.linspace(start... | [
{
"answer_html": "<p>I managed to create a prototype solver based on ADMM in MATLAB:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>function [ vX, isConv ] = SplineQPSmooth( vY, mD, paramLambda, vI, mA, sParams )\n\narguments(Input)\n vY (:, 1) {mustBeNumeric, mustBeFinite, mustBeReal}\n mD (:... | code_qa | Let a 1D curve defined by $\left\{ {y}_{1}, {y}_{2}, \ldots, {y}_{n} \right\}$ sampled on a uniform grid.
I want to smooth the curve with the following properties:
The result, $\left\{ {z}_{1}, {z}_{2}, \ldots {z}_{n} \right\}$ should be smooth like Spline based method.
For a set of indices $\mathcal{I}$ t... | Scientific-Code-and-Analysis-QA:scicomp:45334 | {
"answer_html": "<blockquote>\n<p>monothonic</p>\n</blockquote>\n<p>I'm sure you meant monotonic.</p>\n<blockquote>\n<p>I am looking for a fast way to solve the problem</p>\n</blockquote>\n<p>Are you actually? I think if you were, you would use something off-the-shelf. "Simple iterative" and "fast&quo... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<blockquote>\n<p>monothonic</p>\n</blockquote>\n<p>I'm sure you meant monotonic.</p>\n<blockquote>\n<p>I am looking for a fast way to solve the problem</p>\n</blockquote>\n<p>Are you actually? I think if you were, you would use something off-the... |
null | [
{
"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]\... | [] | code_qa | I need to compute a number of integrals of the form
$$
I = \int_a^b \frac{p_n(x)}{1-x^2} dx
$$
where $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 po... | Scientific-Code-and-Analysis-QA:scicomp:45362 | {
"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 &= \\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... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"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 &= \\int_a^b\\frac{x^l}{1-x²}dx\\\\\n&= ... |
null | [
{
"block_index": 0,
"code_text": " // TEMPERATURE\nvoid solveTemperature(\n double theta[Nx + 1][Ny + 1],\n double u[Nx + 1][Ny + 1],\n double v[Nx + 1][Ny + 1],\n double alpha[], double beta[],\n double hx, double hy, double dt, double Pr, double Ra)\n{\n double A, B, C, F;\n\n // i... | [] | code_qa | Trying to solve natural convection probalem in a square region. Dimensionless. Here are the conditions:
$0 \leq x \leq 1.5 0 \leq y \leq 1.0$ Pr = 7, Re = 7 Ra= 1e3, 1e4 $\ldots$1e7.
Left and right walls are insulated. At the bottom wall $q_1= 1000$ and at
the upper wall $q_2=0.5*q_1$
The temperature fiel... | Scientific-Code-and-Analysis-QA:scicomp:45377 | {
"answer_html": "<p>it seems you are trying to simulate a Rayleigh-Benard convection in a cavity. It is typically coupled with flow field, which you are trying to simulate through omega-psi formulation. No, I believe the convection currents and temperature fields will look different than what you have shown in the p... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>it seems you are trying to simulate a Rayleigh-Benard convection in a cavity. It is typically coupled with flow field, which you are trying to simulate through omega-psi formulation. No, I believe the convection currents and temperature field... |
{
"answer_html": "<p>Unfortunately, an error free transform <code>Threeproduct()</code> of the form <span class=\"math-container\">$a⋅b⋅c=x+y$</span> doesn't necessarily exist for arbitrary <span class=\"math-container\">$a$</span>, <span class=\"math-container\">$b$</span> and <span class=\"math-container\">$c$</spa... | [
{
"block_index": 0,
"code_text": "function [x, y] = ThreeProduct(a, b, c)\n",
"language": "unspecified",
"language_note": "Syntax-screened scientific code; language not asserted; not executed",
"post_id": 45387,
"sha256": "bd4356e06b4e83b3708b56f9d06ac35cfeedc70c4f5106650611050aae8f90f8",
... | [] | code_qa | TL;DR: I am looking for a function that computes the product of three floating point numbers:
function [x, y] = ThreeProduct(a, b, c)
Such that:
$$
a · b · c = x + y \\
x = \operatorname{fl}(a · b ·c)
$$
Background
Ogita et al. (2005) introduced a method of computing a dot product based on "Erro... | Scientific-Code-and-Analysis-QA:scicomp:45387 | {
"answer_html": "<p>Unfortunately, an error free transform <code>Threeproduct()</code> of the form <span class=\"math-container\">$a⋅b⋅c=x+y$</span> doesn't necessarily exist for arbitrary <span class=\"math-container\">$a$</span>, <span class=\"math-container\">$b$</span> and <span class=\"math-container\">$c$</spa... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 45388,
"answers": [
{
"answer_html": "<p>Unfortunately, an error free transform <code>Threeproduct()</code> of the form <span class=\"math-container\">$a⋅b⋅c=x+y$</span> doesn't necessarily exist for arbitrary <span class=\"math-container\">$a$</span>, <span class=\"math-container\... |
{
"answer_html": "<p>Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance F... | [
{
"block_index": 0,
"code_text": "let quadratic_node_intersection =\n move |origin: &Vec3,\n lray: &Vec3,\n box_position: &Vec3,\n box_dims: &Vec3,\n node: &Node<HpNode<f32, 10>>| {\n // Legendre coefficients.\n let cfs = node.... | [] | code_qa | Background
I have an oct-tree approximating a signed distance function that I am then raytracing. I have one implementation that first collides against the oct tree then uses traditional sphere tracing within a node to produce a final image. This works, it looks like this (plus some debugging info):
[image: ent... | Scientific-Code-and-Analysis-QA:scicomp:45396 | {
"answer_html": "<p>Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in the paper "Hierarchical hp-Adaptive Signed Distance F... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 45440,
"answers": [
{
"answer_html": "<p>Makogan and I are both in a Discord server where we were discussing the problem and figured it out. For the sake of completeness, I am putting the answer here as well. The original question makes use of a Legendre polynomial basis like in th... |
null | [
{
"block_index": 0,
"code_text": "restart;\nP1 := 1 + 1/q^6 + q^2 + q^6 + q^8 + q^10 + q^12 + q^14 + q^16 + 2*q^18 + q^20 + q^22 + q^24 + q^26 + q^30;\nP2 := 1/q^6 + q^6 + q^18 + q^30 + q^(-8 + 2*(8 + x[13])) + q^(-8 + 2*(9 + x[13])) + q^(-8 + 2*(6 + x[15])) + q^(-8 + 2*(7 + x[15])) + q^(2*x[17]) + q^(-8 + ... | [
{
"answer_html": "<p>The gist of the problem is (as the Author has suggested) to "assign" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables <span class=\"math-container\">$x_{ij}$</span> in the second Laurent polyomial.</p>\n<p>The... | code_qa | I am trying to solve a linear system of equations that comes from equating two Laurent polynomials (https://en.wikipedia.org/wiki/Laurent_polynomial). The first such polynomial has known numeric values of its exponents, while the second polynomial has the exponents depending linearly on variables we are trying to solve... | Scientific-Code-and-Analysis-QA:scicomp:45472 | {
"answer_html": "<p>Consider first the simpler problem where we have only the laurent polynomials in <span class=\"math-container\">$q$</span> that are multiplied by <span class=\"math-container\">$a^{20}$</span>; call these <span class=\"math-container\">$P_{1}$</span> and <span class=\"math-container\">$P_{2}$</sp... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>The gist of the problem is (as the Author has suggested) to "assign" or match terms with known exponents of the first Laurent polynomial with terms with exponents depending on the variables <span class=\"math-container\">$x_{ij}$</s... |
{
"answer_html": "<p>The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.</p>\n<p>In fact, I realized that I was updating the velocity <strong>before</strong> the position. This means I was not implementing the standard (explicit) Euler method, but the <strong>... | [
{
"block_index": 0,
"code_text": "def euler_function(\n x_earth, y_earth, vx_earth, vy_earth, dt\n):\n\n for i in range(n_steps):\n ax_earth = -(G * M_sun) * x_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n ay_earth = -(G * M_sun) * y_earth / ((x_earth**2 + y_earth**2)**0.5)**3\n\n ... | [
{
"answer_html": "<p>From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually be able to run) and a timestep ten times more fin... | code_qa | I'm simulating the Earth's orbit around the Sun using three different numerical integration methods: Euler, RK2 (midpoint), and Velocity Verlet. Since RK2 and Velocity Verlet are higher-order methods, I expected them to produce more accurate trajectories than Euler when using the same initial conditions and time step.
... | Scientific-Code-and-Analysis-QA:scicomp:45487 | {
"answer_html": "<p>The answer was ultimately provided in a comment, so I'll reproduce it here for the benefit of future readers.</p>\n<p>In fact, I realized that I was updating the velocity <strong>before</strong> the position. This means I was not implementing the standard (explicit) Euler method, but the <strong>... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 45503,
"answers": [
{
"answer_html": "<p>From my eye, the biggest issue is that your timestep is simply too large. Decrease it, either explicitly or by allowing an adaptive-timestep method to meet a specified tolerance. You can see that, for your existing code (repaired to actually... |
{
"answer_html": "<p>The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modifi... | [
{
"block_index": 0,
"code_text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nG = 4 * (np.pi)**2\nM_sun = 1 # solar mass\ndistance = 1 # AU\ntemps = 1 # year\nM_earth = 3.002513826043238e-06 # solar mass\nv_earth = 2 * np.pi # AU/year\ndt = 0.1... | [
{
"answer_html": "<p>I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport matplotlib.pyplot as plt\n\nG = 4 * np.pi**2\nM_sun = 1 ... | code_qa | Can someone please tell me why these two codes don't give the same answer?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
G = 4 * (np.pi)**2
M_sun = 1 # solar mass
distance = 1 # AU
temps = 1 # year
M_earth = 3.002513826043238e-06 # solar mass
v_earth = 2 * np... | Scientific-Code-and-Analysis-QA:scicomp:45488 | {
"answer_html": "<p>The second variant correctly implements the first-order Euler method for the kinematic equation seen as a first-order ODE system. As the Euler method with large step size tends to increase the radius of the orbit, and apparently also the energy level, the gravitational orbit seemingly gets modifi... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 45492,
"answers": [
{
"answer_html": "<p>I'm going to read into your question a little and infer that you want to, at least in part, vectorise your code. You've gotten about halfway there. Try:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport matplo... |
{
"answer_html": "<p>You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term <code>(Au)**3</code> to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it shoul... | [
{
"block_index": 0,
"code_text": "# Creating dealiasing mask\nk_x = freq_grid[0]\nk_y = freq_grid[1]\nk_cutoff = N / 4 \nfreq_mask = (np.abs(k_x) < k_cutoff) & (np.abs(k_y) < k_cutoff)\n\n\n#Constants\nepsilon = 0.01\ndelta = 0.01\ntimesteps = 1000\nmag_sqr = freq_grid[0]**2 + freq_grid[1]**2\n\n# Implicit ... | [] | code_qa | I am trying to implement a IMEX psuedospectral solver to simulate the allen-cahn equation. I have approximated the next step solution using the procedure laid down in the notes: Parallel Spectral Numerical Methods (https://open.umich.edu/sites/default/files/downloads/2012-parallel-spectral-numerical-methods.pdf). Accor... | Scientific-Code-and-Analysis-QA:scicomp:45510 | {
"answer_html": "<p>You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term <code>(Au)**3</code> to your equation with A being a field of 0/1 generated from your filtering. Write out the PDE and the discretization you are using and it shoul... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 45511,
"answers": [
{
"answer_html": "<p>You are "dealiasing" in real space, not frequency space, but real space got no aliasing. You are effectively adding a term <code>(Au)**3</code> to your equation with A being a field of 0/1 generated from your filtering. Write out t... |
{
"answer_html": "<p>Your calculation</p>\n<pre><code>vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n</code></pre>\n<p>is wrong. Notice your typo in the last vector term.</p>\n<p>But also... your code listing does not make sense, because <code>vecf</code> is calculated before its dependencies. Any sane C warnin... | [
{
"block_index": 2,
"code_text": "#include <stdio.h>\n#include <math.h>\n\nint main() {\n // Define a constant for PI to convert degrees to radians\n // const double PI = 3.14159265358979323846;\n double pid;\n // pid=acos(-1);\n // double DegreesToRadians = 3.14159265358979323846/180.0;\n ... | [] | code_qa | I am trying to calculate some angles for a Regular Heptagon in my question using the C programming language:
How can the Referenced Regular Heptagon inscribed within a Unit Circle, with its center coinciding, be drawn using PostScript Programming Language? (https://scicomp.stackexchange.com/questions/45518/how-can-... | Scientific-Code-and-Analysis-QA:scicomp:45523 | {
"answer_html": "<p>Your calculation</p>\n<pre><code>vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n</code></pre>\n<p>is wrong. Notice your typo in the last vector term.</p>\n<p>But also... your code listing does not make sense, because <code>vecf</code> is calculated before its dependencies. Any sane C warnin... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": 45524,
"answers": [
{
"answer_html": "<p>Your calculation</p>\n<pre><code>vecaf[0]=vecf[0]-veca[0]; vecaf[1]=vecf[1]-vecf[0]\n</code></pre>\n<p>is wrong. Notice your typo in the last vector term.</p>\n<p>But also... your code listing does not make sense, because <code>vecf</code> ... |
null | [
{
"block_index": 0,
"code_text": "from dolfinx.fem.petsc import LinearProblem\nimport dolfinx as df\nimport ufl\nimport pyvista as pv\nfrom mpi4py import MPI\nimport numpy as np\n\n# --- Mesh creation ---\ncomm = MPI.COMM_WORLD\nnx = 10 # number of points\nstart_point = 0 # starts at x = 0\nL = 1 # ends at ... | [] | code_qa | I need a resource that covers creating variational/weak forms of differential equations. Where I first learned about obtaining the variational/weak/Galerkin form of a differential equation was in a subsection of my Partial Differential Equations textbook labeled "Finite Element Method", so I'll assume an FEM book will ... | Scientific-Code-and-Analysis-QA:scicomp:45530 | {
"answer_html": "<p>I'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for <span class=\"math-container\">$f = 1 - 2x$</span>.</p>\n<p>Here is an example code which solves <span class=\"math-container\">$(\\nabla u, v) = (1 ... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>I'm not familiar with how to use Fenics, though this seems like there is a bug in code rather than a miss-understanding of the theory, at least for <span class=\"math-container\">$f = 1 - 2x$</span>.</p>\n<p>Here is an example code which solv... |
null | [
{
"block_index": 0,
"code_text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nn= 1500\nA = 2\nT = 2*np.pi\ntau = np.pi\nc = (A*tau)/T\n# a_n = (A/np.pi*n)*np.sin(n*tau)\n# b_n = (A/np.pi*n)*(1-np.cos(n*tau))\nsize = 10\n# t= np.arange(1,size+1,0.01) #arange\nt=np.linspace(1,size+1,500)\nf_t = np.... | [] | code_qa | here is the Fourier series I'm trying to represent:
$$
f(t) = \frac{A\tau}{T} + \frac{A}{\pi}\sum_{n=1}^{\infty}\frac{1}{n}\left[\sin(n\omega\tau)\cos(n\omega t) + \left(1-\cos(n\omega\tau)\right)\sin(n\omega t)\right]
$$
import matplotlib.pyplot as plt
import numpy as np
n= 1500
A = 2
T = 2*np.pi
tau = np.pi
... | Scientific-Code-and-Analysis-QA:scicomp:45541 | {
"answer_html": "<p>Assuming your math is correct, then very literally and using a broadcast sum,</p>\n<pre class=\"lang-py prettyprint-override\"><code>import matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ = π\nω = 1\nn = np.arange(1, 15_001)[:, np.newaxis]\nt... | accepted; otherwise maximum score >= 1, tie lowest ID; no correctness label | train | {
"accepted_answer_id": null,
"answers": [
{
"answer_html": "<p>Assuming your math is correct, then very literally and using a broadcast sum,</p>\n<pre class=\"lang-py prettyprint-override\"><code>import matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import sin, cos, pi as π\n\nA = 2\nT = 2*π\nτ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.