# Mixed-Density Parameter

**URL:** <https://discourse.mc-stan.org/t/mixed-density-parameter/6665>\
**Category:** Modeling\
**Created:** [November 20, 2018, 7:28pm UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665 "2018-11-20T19:28:00Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![Vishv\_Jeet](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/vishv_jeet/32/319_2.png) [@Vishv\_Jeet](https://discourse.mc-stan.org/u/Vishv_Jeet)\
**Post date:** [November 20, 2018, 7:28pm UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/1 "2018-11-20T19:28:00Z")

</div>

Stan model such as one below compiles and runs but it doesn’t produce the right density for the single parameter.

```stan

transformed data{
  vector[1000] x;
  for (i in 1:1000) {
    x[i] = normal_rng(0, 1);
  }
}
parameters{
  real y;
}
model {
  for (i in 1:1000) {
    if(x[i] > 0) {
      y ~ normal(10, 2);
    } else {
      y ~ gamma(3, 3);
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![Vishv\_Jeet](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/vishv_jeet/32/319_2.png) [@Vishv\_Jeet](https://discourse.mc-stan.org/u/Vishv_Jeet)\
**Post date:** [November 20, 2018, 7:36pm UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/2 "2018-11-20T19:36:15Z")

</div>

Here is the density plot from Stan sampling.  
[Rplot.pdf](https://canada1.discourse-cdn.com/flex030/uploads/mc_stan/original/2X/3/3f5b392ea4d2649f44498a24b0061fcebb09779e.pdf) (8.8 KB)

This is what is expected.  
[Rplot01.pdf](https://canada1.discourse-cdn.com/flex030/uploads/mc_stan/original/2X/a/aa4f1fa9f5eb958ccca5e5ad94f46a140b717997.pdf) (10.4 KB)

---

<div class="post-metadata">

**Author:** ![tiagocc](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/tiagocc/32/85_2.png) [@tiagocc](https://discourse.mc-stan.org/u/tiagocc)\
**Post date:** [November 20, 2018, 9:10pm UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/4 "2018-11-20T21:10:56Z")

</div>

The problem seems to be that you specify that y only has one dimension (`real y`), thus when you run the the model with multiple iterations, you’ll get the sampling distribution of the singe value of y. The following code will replicate your undesired figure:

```
library(rstan)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
library(tidyverse)

mJeet <- stan_model("path_to_model/mJeet.stan")

fit <- sampling(mJeet,
                refresh = 1e5)

as.data.frame(fit, pars = "y") %>% 
  ggplot(aes(x = y)) + 
  geom_histogram(bins = 80)

```

![undesired](https://canada1.discourse-cdn.com/flex030/uploads/mc_stan/original/2X/8/8dcdcb377992449c7152e78cc250ea0c4392ab91.jpeg)  
By moving everything to the `generating quantities` block and correctly specifying the dimensions of y, you can obtain your desired distribution:

```

data {
  int N; // sample size
}

generated quantities{
  vector[N] x;
  vector[N] y;
  
  
for (i in 1:N) {
  x[i] = normal_rng(0,1);

    if(x[i] > 0) {
      y[i] = normal_rng(10,2);
    } else {
      y[i] = gamma_rng(3, 3);
    }
  }  
}

```

```
mDiscourse <- stan_model("path_to_model/mDiscourse.stan")

fit <- sampling(mDiscourse,
                data = list(N = 1e3), 
                iter = 1,
                chains= 1,
                algorithm = "Fixed_param")

as.data.frame(fit, pars = "y") %>% 
  gather %>% 
  ggplot(aes(x = value)) + 
  geom_histogram(bins = 80)

```

 ![desired](https://canada1.discourse-cdn.com/flex030/uploads/mc_stan/original/2X/9/988865dc06a0d82c8e9dd905b2747a5b68a305cd.jpeg)

---

<div class="post-metadata">

**Author:** ![Vishv\_Jeet](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/vishv_jeet/32/319_2.png) [@Vishv\_Jeet](https://discourse.mc-stan.org/u/Vishv_Jeet)\
**Post date:** [November 21, 2018, 2:31pm UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/5 "2018-11-21T14:31:38Z")

</div>

The question of being able to `estimate` a parameter with a mixture density is quite different from `generate` mixed-density data. Your code is doing the latter.

---

<div class="post-metadata">

**Author:** ![tiagocc](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/tiagocc/32/85_2.png) [@tiagocc](https://discourse.mc-stan.org/u/tiagocc)\
**Post date:** [November 21, 2018, 11:32pm UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/6 "2018-11-21T23:32:14Z")

</div>

Sorry for the misunderstanding then… If you want to `estimate` y then you need to change two things in your model:

- declare the parameter dimensions and set it to be higher then 0: `real<lower = 0> y;`

- add to index on both y’s on the for loop in the model block.

```
data{
int N;
}

transformed data{
  vector[N] x;
  for (i in 1:N) {
    x[i] = normal_rng(0, 1);
  }
}
parameters{
  real<lower =0> y[N];
}
model {
  for (i in 1:N) {
    if(x[i] > 0) {
      y[i] ~ normal(10, 2);
    } else {
      y[i] ~ gamma(3, 3);
    }
  }
}

```

After fitting the model and looking at one of the sampled data sets, everything seems to in order.

```

dstan <- list(N=1e3)

fitJeet <- sampling(mJeet_fix, 
                    data = dstan, 
                    chain = 1)

dpred <- as.matrix(fitJeet, pars = "y") %>% 
 t() %>% as.data.frame()

colnames(dpred) <- 1:dstan$N

dpred %>% gather(rep, value, 1:dstan$N) %>%
  filter(rep == 1) %>% 
  ggplot(aes(x=value)) +
  geom_histogram(bins = 100)

```

![desired](https://canada1.discourse-cdn.com/flex030/uploads/mc_stan/original/2X/6/69ce186496f19bf1077cc4d99903349803e2e15e.jpeg)

---

<div class="post-metadata">

**Author:** ![Vishv\_Jeet](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/vishv_jeet/32/319_2.png) [@Vishv\_Jeet](https://discourse.mc-stan.org/u/Vishv_Jeet)\
**Post date:** [November 27, 2018, 1:11am UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/7 "2018-11-27T01:11:30Z")

</div>

Not quite there yet. The above histogram isn’t the posterior density of single parameter.

---

<div class="post-metadata">

**Author:** ![stijn](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/stijn/32/105_2.png) [@stijn](https://discourse.mc-stan.org/u/stijn)\
**Post date:** [November 27, 2018, 8:52am UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/8 "2018-11-27T08:52:13Z")

</div>

I am not sure about what I am going to write, so take everything I say with a grain of salt.

I think what you are trying to achieve might not be possible in this stylized set-up. Because, you have 1000 values for `x`, and only 1 `y`, you are effectively averaging over the two distributions. You can think of it as: for `x[1]`, `y` is drawn from the normal, for `x[2]`, `y` is drawn (I know this is not how HMC/Stan works) from the gamma, and so forth. So the best guess for `y` is some kind of average over the `normal(10,2)` and the `gamma(3,3)` which gives you the `Rplot.pdf`.

If you want to have the nice separation of the distribution, you need to have the same amount of `x`'s and `y`s. Just like @tiagocc wrote. Then for `x[1]`, `y[1]` is always drawn from the normal, for `x[2]`, `y[2]` is always drawn from the gamma, … As a result half of the `y`'s will come from the normal and half will come from the gamma and you get the separate distributions in the histograms. The original stan model basically estimated the mean of the vector `y` with `N` elements.

---

<div class="post-metadata">

**Author:** ![tiagocc](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/tiagocc/32/85_2.png) [@tiagocc](https://discourse.mc-stan.org/u/tiagocc)\
**Post date:** [November 27, 2018, 1:47pm UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/9 "2018-11-27T13:47:51Z")

</div>

In the spirit of what @stijn said, I am not totally sure this is the correct approach to your problem, but if the goal is to estimate a single parameter, I guess the solution would be to sample it from a finite mixture between the gamma and normal distributions you want, with a mixing proportion lambda

```
transformed data {
 real lambda = .5;  
}

parameters{
  real<lower = 0> y;
}

model {
  target += log_mix(lambda, 
                    normal_lpdf(y | 10, 2),
                    gamma_lpdf(y | 3, 3));
}

```

I define lambda as 0.5, since the cdf of the standard normal on 0 is \Phi(0) = 0.5, but you can still generate the samples from the standard normal and compute the `ecdf` at 0 on the `transformed data` block.

If you plot the posterior samples of y you’ll get something close to what I think you want.

 ![jeet_mix](https://canada1.discourse-cdn.com/flex030/uploads/mc_stan/original/2X/e/e76b7e99b627586cfdd0df556ce96346b28abf6c.jpeg)

The `R` code bellow will replicate the figture:

```
library(rstan)
options(mc.cores = parallel::detectCores())

fitJeet <- sampling(mix_jeet,
                    chains = 4,
                    iter = 10000, 
                    warmup = 2000,
                    control = list(adapt_delta = .99), 
                    seed = 132)

dfit <- as.data.frame(fitJeet, pars = "y")

library(ggplot2) 
ggplot(dfit, aes(x = y))+
  geom_histogram(bins = 100)

```

---

<div class="post-metadata">

**Author:** ![Vishv\_Jeet](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/vishv_jeet/32/319_2.png) [@Vishv\_Jeet](https://discourse.mc-stan.org/u/Vishv_Jeet)\
**Post date:** [November 27, 2018, 2:36pm UTC](https://discourse.mc-stan.org/t/mixed-density-parameter/6665/10 "2018-11-27T14:36:07Z")

</div>

This is great, finally the question is settled.
