Post · 212 min read· pp. 1921–2190

Impact Factor

Hierarchical models are a natural way to model heterogeneity across exchangeable contexts, but they become less appropriate when additional information discriminates those contexts. In particular any labels that categorize individual contexts into groups immediately obstructs the full exchangeability, and modeling heterogeneity consistently with these groupings becomes much more subtle. When the contexts are subject to multiple, overlapping categorizations the challenge becomes even more difficult. In this case study we investigate how to generalize exchangeability in the presence of factors that categorize individual contexts and then develop modeling techniques compatible with this generalization.

We begin by discussing how to consistently model heterogeneity in the presence of a single factor before considering multiple factors, in particular multiple factors whose groups nest within each other and multiple factors whose groups overlap. With this foundation laid we then demonstrate the basic implementation and analysis of these models before working through some more realistic examples.

1 Single Factor Models

Let's begin by considering how heterogeneity manifests in the presence of a single categorizing variable. After defining these categorizing variables as factors we discuss the conditional and marginal exchangeability compatible with categorical groups and the resulting hierarchical models. Finally we reframe these hierarchies in terms of residual variations across the groups.

1.1 Factors

As we saw in my hierarchical modeling case study a set of individual contexts are exchangeable only when we do not have, or ignore, any information that discriminates one context from another. For example the cards in a deck are exchangeable when we can view only their back faces.

Flipping the cars over, however, reveals patterns that break the full exchangeability of the cards.

We will denote such discriminating information with traditional statistics terminology. A factor is a categorical variable that endows each context with one of a finite number of discrete, unordered values, or levels. When there is minimal risk of confusion I will also use "level" to refer to all of the individual contexts grouped with the same level value. In our card example the immediate factor is color, with the three levels corresponding to light red, red, and dark red values. The "dark red level" would then correspond to all cards with dark red coloring.

Factors can capture any abstract categorization or labeling. For example if the contexts are defined by facilities where a certain product is manufactured then a region factor might assign values of "northeast", "southeast", southwest", and "northwest" depending on where each factory is located. Additional factors might include where the material input to the manufacturing process is sourced, environmental conditions, and even manager and employee assignments.

1.2 Conditional and Marginal Exchangeability

Regardless of its interpretation, the level assignments within a factor obstruct some of the permutations that would be valid without the factor. In particular although our information is still indifferent to permutations of cards within the same level we will notice permutations of cards within different levels.

Grouping the individual contexts by their level assignments makes it easier to identify, and classify, the permutations that persist after a factor has been introduced. For example the permutations that modify only contexts within a single level are unaffected by the introduction of the factor and they define a conditional exchangeability.

These conditional exchangeabilities then suggests that the heterogeneity of the individual contexts should be modeled with independent hierarchical models within each level.

Because the level values themselves are also arbitrary labels, any permutation that swaps all of the contexts within different levels is also compatible with the given factor. These permutations then define a corresponding marginal exchangeability.

Consequently any behavior common to each level is naturally modeled with a hierarchical model across the levels.

1.3 Factor Compatible Hierarchical Models

Conditional exchangeability motivates independent hierarchical models within each of the factor levels, while marginal exchangeability motivates a hierarchical model across the factor levels. These residual exchangeabilities, however, are compatible with each other. Consequently the hierarchies can be combined into a deeper hierarchical model with multiple layers, the top level capturing the conditional heterogeneity and the bottom layer capturing the marginal heterogeneity across levels.

This architecture gives the most general family of hierarchical models compatible with a given factor. In order to specify a particular hierarchical model we first need to specify the population models within each level,

θk∼π(ϕl(k)),\theta_{k} \sim \pi(\phi_{l(k)}),
where k∈{1,…,Kl}k \in \{1, \ldots, K_{l} \} indexes the individual contexts, l∈{1,…,L}l \in \{1, \ldots, L\} indexes each factor level, and l(k)l(k) maps each context into its associated factor level. The full model specification is then completed with a population model across the level-specific population parameters,
ϕl∼π(ϕ).\phi_{l} \sim \pi(\phi).

For example within each level we might consider a normal population model,

θk∼normal(θl(k),τl(k)).\theta_{k} \sim \text{normal}(\theta_{l(k)}, \tau_{l(k)}).
In general we can pool the population parameters (θl(\theta_{l}, τl)\tau_{l}) jointly with a two-dimensional population model, but we might also pool just the level-specific location parameters, θl\theta_{l}, or the level-specific scale parameters, τl\tau_{l}, with one-dimensional hierarchical models. We might for instance pool only the location parameters with another normal population model,
θl∼normal(μ,τ).\theta_{l} \sim \text{normal}(\mu, \tau).
Together these assumptions specify a basic, but effective, factor compatible hierarchical model,
θk∼normal(θl(k),τl(k))θl∼normal(μ,τ).\begin{align*} \theta_{k} &\sim \text{normal}(\theta_{l(k)}, \tau_{l(k)}) \\ \theta_{l} &\sim \text{normal}(\mu, \tau). \end{align*}

That said, this specific hierarchical model doesn't actually appear much in the statistics literature. Most commonly the conditional heterogeneity within the levels is implicitly ignored, or occasionally explicitly assumed to be zero. In either case all of the individual contexts collapse into a set of level contexts, and the remaining marginal heterogeneity across those level contexts is captured by a single hierarchical model,

θl∼π(ϕ).\theta_{l} \sim \pi(\phi).
For example given the normal assumptions from above we might have
θl∼normal(μ,τ).\theta_{l} \sim \text{normal}(\mu, \tau).
From this perspective the full factor-compatible hierarchical model that includes the within-level heterogeneity becomes a special case of nested factor model which we will discuss in depth in Section 2.

To avoid too much confusion with the literature, from here on we will by default also ignore the conditional heterogeneity within the factor levels so that the heterogeneity compatible with a factor is naturally modeled by a single, one-layer hierarchical model.

1.4 Residual Hierarchical Models

When building our first factor compatible hierarchical model above we exploited the interpretability of the monolithically centered parameterization,

θl∼normal(θ,τ).\theta_{l} \sim \text{normal}(\theta, \tau).
Once we have specified the model we may have to consider non-centering some or even all of the level parameters as needed to ensure accurate computation in practice.

One particular reparameterization, however, also offers a useful interpretability that can facilitate model building. If we non-center the level parameters with respect to the location parameter then the hierarchical model takes on a particularly compelling form:

θl=θ+δlδl∼normal(0,τ).\begin{align*} \theta_{l} &= \theta + \delta_{l} \\ \delta_{l} &\sim \text{normal}(0, \tau). \end{align*}
The behavior within each level decomposes into additive contribution from a common baseline θ\theta plus a residual δl\delta_{l} that captures the variation across levels.

This residual perspective can also be useful when building more general factor compatible hierarchical models. If the parameters θl\theta_{l} are unconstrained then we can always mathematically decompose the behavior of each individual context into a baseline behavior with residual corrections. All we have to do is add and subtract a common baseline contribution,

θl=θl+0=θl+(−θ+θ)=(θl−θ)+θ,=δl+θ.\begin{align*} \theta_{l} &= \theta_{l} + 0 \\ &= \theta_{l} + (-\theta + \theta) \\ &= (\theta_{l} - \theta) + \theta, \\ &= \delta_{l} + \theta. \end{align*}
Keep in mind that this residual decomposition is not always possible, especially when the behavior in each context is modeled with a single constrained parameter or multiple coupled parameters.

Assuming that each set of residual parameters are exchangeable motivates another hierarchical model,

θl=δl+θδl∼π(ϕ).\begin{align*} \theta_{l} &= \delta_{l} + \theta \\ \delta_{l} &\sim \pi(\phi). \end{align*}
Taking normal population models exactly recovers the normal hierarchical model from above, but this approach can provide a convenient way to engineer more general hierarchical models that also maintain marginal exchangeability. Of course once we build a model this way we may still have to consider reparameterizations when fitting the model in practice.

One subtlety introduced with this residual construction is the interpretation of the parameters themselves, which are defined only relative to each other. Because neither the baseline nor the residual contributions influence the data generating process independently of the other they have no independent meaning. In order to reconstruct the behavior in any observed context, θl\theta_{l}, we have to incorporate both θ\theta and δl\delta_{l} together.

That said the residual parameters are often implicitly given an interpretation based on counterfactual circumstances. For example the baseline θ\theta might be presented as the behavior of a hypothetical level with deltal=0delta_{l} = 0,

θl=θ+0.\theta_{l} = \theta + 0.
Although we might not observe this circumstance, and indeed it might be impossible to observe this circumstance at all, it provides an interpretation for θ\theta independent of the other parameters. Similarly the factor level residuals might be interpreted as the behavior within each level in the hypothetical circumstance where the baseline contribution vanishes,
θl=0+δl.\theta_{l} = 0 + \delta_{l}.

Personally I find these counterfactual interpretations confusing if not outright misleading, especially when they are made implicitly. I recommend instead always using explicit configurations to interpret the residual parameters. That configuration might be actual, corresponding to levels observed in the data, or hypothetical, corresponding to hypothetical levels with hypothetical behavior. By making these assumptions explicit we avoid any ambiguity in statements about the parameters, and hence any confusion in how those statements might apply in other circumstances. In particular writing out the full assumptions can make it clear when hypothetical assumptions are particularly irrelevant or misleading.

2 Nested Multifactor Models

The information encoded in a single factor complicates notions of exchangeability and, consequently, the modeling of heterogeneity compatible with that information. Unsurprisingly incorporating multiple factors complicates matters further still. Let's first consider multifactor models where each factor is compatible with each other.

2.1 Nested Hierarchies

In particular consider a sequence of factors that nest within each other, where the levels of each successive factor only subdivides the levels of the previous factor. More formally each successive factor has strictly more levels than the proceeding factor, and those factor levels fall into one and only one of the proceeding factor levels.

For example we might have a deck of cards that are characterized by not just colors but also symbols.

As before the color factor groups the individual contexts into color levels, reducing the full exchangeability into marginal exchangeability across the color levels and conditional exchangeability within the color levels. As above we will assume that there is no heterogeneity within the levels so that the structure of the factor compatible hierarchical model is determined entirely by the marginal exchangeability.

The new symbol factor also groups the individual contexts, but this time into symbol levels. These symbol levels then motivate their own own factor compatible hierarchical models.

If we look closely, however, we see that the symbol levels nest within the color levels, subdividing the color levels but not crossing them. Consequently the exchangeabilities induced by these two factors are compatible with each other. The full exchangeability of the individual contexts separates into marginal exchangeability across the color levels, a marginal/conditional exchangeability across the symbol levels nested within each color level, and then finally the fully conditional exchangeability within the symbol levels.

Because the exchangeabilities are compatible so too are the two factor compatible hierarchical models. In particular the symbol hierarchies nest within the color hierarchy to form a deeper hierarchical model.

In this case by ignoring the conditional heterogeneity within the symbol levels the individual contexts collapse into one context for each symbol. This holds more generally -- the relevant contexts in a nested multifactor model are always the levels of the shallowest factor with the most refined levels.

For example consider an initial factor f1f_{1} that separates the individual contexts into the levels l1∈{1,…,Lf1}l_{1} \in \{1, \ldots, L_{f_{1}}\}, and then a second factor f2f_{2} that separates the contexts into the levels l2∈{1,…,Lf2}l_{2} \in \{1, \ldots, L_{f_{2}} \} that nest into the f1f_{1} levels with the many-to-one map l1(l2)l_{1}(l_{2}). The most general family of hierarchical models compatible with these two nested factors is given by

θl2f2∼π(θl1(l2)f1)θl1f1∼π(ϕ).\begin{align*} \theta^{f_{2}}_{l_{2}} &\sim \pi( \theta^{f_{1}}_{l_{1}(l_{2})} ) \\ \theta^{f_{1}}_{l_{1}} &\sim \pi(\phi). \end{align*}
If we assume that the heterogeneity manifests only in the location of a normal population model then we arrive at a nested normal hierarchical model,
θl2f2∼normal(θl1(l2)f1,τl1(l2)f1)θl1f1∼normal(θ,τ).\begin{align*} \theta^{f_{2}}_{l_{2}} &\sim \text{normal}( \theta^{f_{1}}_{l_{1}(l_{2})}, \tau^{f_{1}}_{l_{1}(l_{2})} ) \\ \theta^{f_{1}}_{l_{1}} &\sim \text{normal}(\theta, \tau). \end{align*}

One of the more frustrating but also critical aspects of multifactor models is their organization. Through this case study I try to communicate that organization as clearly as possible with a careful, explicit notation. That notation, however, also introduces a mess of indices that can be a bit overwhelming at first. Hopefully the clarity is worth it!

2.2 Conditional Exchangeability and Trivial Factors

If we do want to include the conditional heterogeneity within the symbol levels then the hierarchy must extend to the individual contexts as well.

Those individual contexts, however, always defines a natural factor: the trivial factor that assigns each context to its own level.

Because it completely separates the contexts, the trivial factor is always compatible with other factors no matter how refined their levels might be. Consequently we can always add another hierarchy to modeling the heterogeneity across the trivial levels on top of any nested hierarchical model.

This final layer, however, recovers the exact same hierarchical structure that arose when we included the conditional heterogeneity of the most refined level! Consequently even if we generally ignore the conditional heterogeneity within the individual factor levels we can always incorporated it back into the final nested multifactor model by including an additional trivial factor. In particular once we have programs capable of automatically building multifactor model for any set of nested factors it's straightforward to add the residual heterogeneity within the more refined level by adding an explicit trivial factor. This is perhaps one reason why conditional heterogeneity is often ignored entirely in many references on multifactor models.

2.3 Nested Residuals

As is often the case we specified the nested normal hierarchical model in a monolithically centered parameterization,

θl2f2∼normal(θl1(l2)f1,τl1(l2)f1)θl1f1∼normal(θ,τ).\begin{align*} \theta^{f_{2}}_{l_{2}} &\sim \text{normal}( \theta^{f_{1}}_{l_{1}(l_{2})}, \tau^{f_{1}}_{l_{1}(l_{2})} ) \\ \theta^{f_{1}}_{l_{1}} &\sim \text{normal}(\theta, \tau). \end{align*}
Equivalently we can also non-center each hierarchical parameter relative to the corresponding location parameter to give a residual model,
θl2f2=θ+δl1(l2)f1+δl2f2δl2f2∼normal(0,τl1(l2)f1)δl1f1∼normal(0,τ).\begin{align*} \theta^{f_{2}}_{l_{2}} &= \theta + \delta^{f_{1}}_{l_{1}(l_{2})} + \delta^{f_{2}}_{l_{2}} \\ \delta^{f_{2}}_{l_{2}} &\sim \text{normal}(0, \tau^{f_{1}}_{l_{1}(l_{2})} ) \\ \delta^{f_{1}}_{l_{1}} &\sim \text{normal}(0, \tau). \end{align*}

As before we can also motivate such a nested residual construction more generally if all of the hierarchical parameters are unconstrained. We begin by adding and subtracting a variable corresponding the levels of the first factor,

θl2f2=θl2f2+0=θl2f2+(−θl1(l2)f1+θl1(l2)f1)=(θl2f2−θl1(l2)f1)+θl1(l2)f1.\begin{align*} \theta^{f_{2}}_{l_{2}} &= \theta^{f_{2}}_{l_{2}} + 0 \\ &= \theta^{f_{2}}_{l_{2}} + \big( -\theta^{f_{1}}_{l_{1}(l_{2})} + \theta^{f_{1}}_{l_{1}(l_{2})} \big) \\ &= \big( \theta^{f_{2}}_{l_{2}} - \theta^{f_{1}}_{l_{1}(l_{2})} \big) + \theta^{f_{1}}_{l_{1}(l_{2})}. \end{align*}
Then we add and subtract a term common to all levels,
θl2f2=(θl2f2−θl1(l2)f1)+θl1(l2)f1+0=(θl2f2−θl1(l2)f1)+θl1(l2)f1+(−θ+θ)=(θl2f2−θl1(l2)f1)+(θl1(l2)f1−θ)+θ=δl2f2+δl1(l2)f1+θ.\begin{align*} \theta^{f_{2}}_{l_{2}} &= \big(\theta^{f_{2}}_{l_{2}} - \theta^{f_{1}}_{l_{1}(l_{2})}\big) + \theta^{f_{1}}_{l_{1}(l_{2})} + 0 \\ &= \big(\theta^{f_{2}}_{l_{2}} - \theta^{f_{1}}_{l_{1}(l_{2})}\big) + \theta^{f_{1}}_{l_{1}(l_{2})} + \big( -\theta + \theta \big) \\ &= \big( \theta^{f_{2}}_{l_{2}} - \theta^{f_{1}}_{l_{1}(l_{2})} \big) + \big( \theta^{f_{1}}_{l_{1}(l_{2})} - \theta \big) + \theta \\ &= \hspace{1mm} \delta^{f_{2}}_{l_{2}} \hspace{18.1mm} + \delta^{f_{1}}_{l_{1}(l_{2})} \hspace{11.4mm} + \theta. \end{align*}
We can then build a hierarchical model compatible with the two nested factors by modeling the residuals that are nested together with independent hierarchical models. If the population models in these hierarchies are normal then we recover the nested normal model above, but again this construction gives us the freedom to specify more complex hierarchies that might be useful in any given application.

The residual parameters here suffer the same interpretational difficulties that we encountered in Section 1.4. In order to reconstruct the behavior in any observed context, θl2f2\theta^{f_{2}}_{l_{2}}, we have to incorporate all of the contributions, including the baseline θ\theta, the first factor residuals δl1(l2)f1\delta^{f_{1}}_{l_{1}(l_{2})}, and the second factor residuals, δl2f2\delta^{f_{2}}_{l_{2}}. Consequently none of these parameters have any interpretation independent of the others.

We can continue to avoid confusion by always interpreting model inferences in terms of an explicit context, and the contributions from all of the factors levels to which that context belongs. As before those contexts can be actual, constructed from observed levels and their inferred behavior, or hypothetical, imagined levels where heterogeneity vanishes. For example in order to isolate the baseline we have to consider hypothetical residuals levels with zero contribution,

δl1(l2)f1=δl2f2=0θl2f2=θ+0+0=θ,\begin{align*} \delta^{f_{1}}_{l_{1}(l_{2})} &= \delta^{f_{2}}_{l_{2}} = 0 \\ \theta^{f_{2}}_{l_{2}} &= \theta + 0 + 0 = \theta, \end{align*}
while isolating the first factor contributions require hypothetically vanishing contributions from the baseline and second factor,
θ=δl2f2=0,θl2f2=0+δl1(l2)f1+0=δl1(l2)f1.\begin{align*} \theta &= \delta^{f_{2}}_{l_{2}} = 0, \\ \theta^{f_{2}}_{l_{2}} &= 0 + \delta^{f_{1}}_{l_{1}(l_{2})} + 0 = \delta^{f_{1}}_{l_{1}(l_{2})}. \end{align*}
Finally to isolate only the second factor contributions we have to imagine that the contributions from both the baseline and first factor vanish,
θ=δl1(l2)f1=0,θl2f2=0+0+δl2f2=δl2f2.\begin{align*} \theta &= \delta^{f_{1}}_{l_{1}(l_{2})} = 0, \\ \theta^{f_{2}}_{l_{2}} &= 0 + 0 + \delta^{f_{2}}_{l_{2}} = \delta^{f_{2}}_{l_{2}}. \end{align*}

By communicating all of the relevant assumptions we avoid any interpretational ambiguity.

3 Overlapping Multifactor Models

When the levels of multiple factors don't nest, and instead overlap with each other, building models compatible with all of the factors at the same time becomes especially challenging. In this case we often have to appeal to models that are only approximately compatible with all of the factors.

3.1 Intersecting Exchangeability

Let's look at a deck of cards once again. The cards continue to be characterized by color and symbol factors, only this time the symbols levels are allocated differently.

If we consider only the color factor then our model proceeds as in Section 1. We can freely permute the cards within each color level, defining conditional exchangeabilities, and all of the cards across levels, defining marginal exchangeability, and motivating a compatible hierarchical model.

The symbol factors, however, define a different sense of marginal and conditional exchangeability and hence a different compatible hierarchical model.

Because the factor levels overlap, however, these notions of exchangeability are not consistent with each other. Many permutations that are compatible the color factor, for example, are not compatible with the symbol factor categorizations.

The only permutations that are compatible with both factors at the same time are those confined to the same intersection level.

These permutations define an intersectional exchangeability that decomposes into marginal exchangeability across the intersection levels and conditional exchangeability within the intersection levels. This decomposition then defines the compatible hierarchical models that we're after.

The intersectional marginal exchangeability motivates a hierarchical model across the intersection levels.

Similarly the intersectional conditional exchangeability motivates hierarchical models nested within the intersection levels to account for the residual heterogeneity.

Per convention we will focus on the marginal exchangeability, ignoring the conditional exchangeability and hence the residual heterogeneity within the intersection levels. We can always incorporate that residual heterogeneity by explicitly adding a trivial factor to the existing factors.

In order to build these overlapping factor compatible hierarchical models we first have to build the intersection levels across which the heterogeneity manifests. If there are FF factors, each with LfL_{f} levels, then the number of intersection levels is given by the product of all of the factor levels,

Lint=∏f=1FLf.L_{\text{int}} = \prod_{f = 1}^{F} L_{f}.
For example in our deck example we have three color levels, four symbol levels, and hence twelve total intersection levels.

If we use these intersection levels to define an intersection factor then the hierarchical model compatible with all of the factors is straightforward: we just build a single factor model for the intersection factor as in Section 1,

θl∼normal(θ,τ).\theta_{l} \sim \text{normal}(\theta, \tau).

3.2 Incremental Intersections

Once we construct the intersection factor building the compatible hierarchical model is conceptually straightforward. In practice, however, some critical problems quickly arise.

Most immediately the number of intersection levels tends to be large. As we consider more factors, and more levels within each factor, the total number of intersections explodes multiplicatively. Even if each factor features only a few levels on its own, the intersection factor can easily have hundreds if not thousands of levels. As the number of intersection levels grows the occupancy of the levels also becomes more sparse for any fixed number of observations; many of the intersection levels might not be observed at all. At best this results in weak inferences, and at worst it can result in inferences that are degenerate enough to obstruct accurate computation.

The intersection levels also manifest strong correlations. Any behavior common to a level in one of the factors will propagate to all of the intersection levels that correspond to that level; the more significant the common behavior the more strongly those intersection parameters will be coupled together. For example any behavior common to the second color level will induce correlations between all four of the corresponding interaction levels, and any behavior common to the second symbol level will induce correlations between all three of the corresponding interaction levels.

The common behavior in all of the individual factor levels results in a tangled web of complex interactions that can frustrate not only computation but also the interpretation of the parameters.

Taking inspiration from the residual perspective we considered above, however, we can expand the intersection parameters into a sequence of residual parameters that may be better behaved. For example consider the case of two factors, the first with levels indexed by l1∈{1,…,L1}l_{1} \in \{1, \ldots, L_{1}\}, the second with levels indexed l2∈{1,…,L2}l_{2} \in \{1, \ldots, L_{2}\}, and the corresponding intersection levels indexed by the ordered pair (l1,l2)(l_{1}, l_{2}).

Notational complaints aside, we can isolate the behavior common to the individual factor levels by adding and subtracting parameters for each,

θl1,l2f1,f2=θl1,l2f1,f2+0+0=θl1,l2f1,f2+(−θl1f1+θl2f2)+(−θjf1+θl2f2)=(θl1,l2f1,f2−θl1f1−θl2f2)+θl1f1+θl2f2.\begin{align*} \theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} &= \theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} + 0 + 0 \\ &= \theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} + \big(-\theta^{f_{1}}_{l_{1}} + \theta^{f_{2}}_{l_{2}} \big) + \big(-\theta^{f_{1}}_{j} + \theta^{f_{2}}_{l_{2}} \big) \\ &= \big(\theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} - \theta^{f_{1}}_{l_{1}} - \theta^{f_{2}}_{l_{2}}\big) + \theta^{f_{1}}_{l_{1}} + \theta^{f_{2}}_{l_{2}}. \end{align*}
We can then isolate the behavior common to all levels by adding and subtracting a baseline parameter,
θl1,l2f1,f2=(θl1,l2f1,f2−θl1f1−θl2f2)+θl1f1+θl2f2+2⋅0=(θl1,l2f1,f2−θl1f1−θl2f2)+θl1f1+θl2f2+2⋅(−θ+θ)=(θl1,l212−θl1f1−θl2f2+θ)+(θl1f1−θ)+(θl2f2−θ)+θ=δl1,l2f1,f2+δl1f1+δl2f2+θ\begin{align*} \theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} &= \big(\theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} - \theta^{f_{1}}_{l_{1}} - \theta^{f_{2}}_{l_{2}}\big) + \theta^{f_{1}}_{l_{1}} + \theta^{f_{2}}_{l_{2}} + 2 \cdot 0 \\ &= \big(\theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} - \theta^{f_{1}}_{l_{1}} - \theta^{f_{2}}_{l_{2}}\big) + \theta^{f_{1}}_{l_{1}} + \theta^{f_{2}}_{l_{2}} + 2 \cdot (-\theta + \theta) \\ &= \big(\theta^{12}_{l_{1}, l_{2}} - \theta^{f_{1}}_{l_{1}} - \theta^{f_{2}}_{l_{2}} + \theta\big) + \big(\theta^{f_{1}}_{l_{1}} - \theta\big) + \big(\theta^{f_{2}}_{l_{2}} - \theta\big) + \theta \\ &= \hspace{1mm} \delta^{f_{1}, f_{2}}_{l_{1}, l_{2}} \hspace{31.25mm} + \delta^{f_{1}}_{l_{1}} \hspace{12.25mm} + \delta^{f_{2}}_{l_{2}} \hspace{12.5mm} + \theta \end{align*}

The baseline factor θ\theta captures the behavior common to all contexts while the residual factors δl1f1\delta^{f_{1}}_{l_{1}} and δl2f2\delta^{f_{2}}_{l_{2}} capture the behavior common to the contexts within each individual factor level. This leaves the residual interaction factor, δl1,l2f1,f2\delta^{f_{1}, f_{2}}_{l_{1}, l_{2}}, which captures any excess heterogeneity unique to the overlap of the factor levels.

If these common behaviors are significant then these residual parameters should be less strongly coupled then the original intersection parameters. Moreover even if the intersection levels are sparsely populated the baseline and factor residuals will tend to be more densely populated and hence easier to infer.

In general we can decompose the intersection of NFN_{F} factors into a single baseline, main contributions from each factor, first-order interactions between each pair of factors, second-order interactions between each triplet of factors, and so on. To break the notational asymmetry between the first two contributions and the various intersections I will also refer to all of these contributions by their order, starting with the zeroth-order contribution from the baseline. This ordering will also be consistent with the more formal treatment in Section 3.4.

Common NameOverall OrderNumber of FactorsLevels within Each FactorFactor Notation
BaselineZeroth
(NF0)=1{ N_{F} \choose 0 } = 1
11
θ\theta
Main ContributionFirst
(NF1)=NF{ N_{F} \choose 1 } = N_{F}
LfL_{f}
δlf\delta^{f}_{l}
First-Order InteractionSecond
(NF2){ N_{F} \choose 2 }
Lf1⋅Lf2L_{f_{1}} \cdot L_{f_{2}}
δl1,l2f1,f2\delta^{f_{1}, f_{2}}_{l_{1}, l_{2}}
R-th Order Interaction(R + 1)st
(NFR+1){ N_{F} \choose R + 1 }
Lf1⋅…⋅LfRL_{f_{1}} \cdot \ldots \cdot L_{f_{R}}
δl1,…,lRf1,…,fR\delta^{f_{1}, \ldots, f_{R}}_{l_{1}, \ldots, l_{R}}

The interpretational subtleties of the residual construction are especially important here. Again because all of the contributions are integrated together when generating data they are meaningful only in relation to each other. In order to avoid misleading interpretations it's best to always explicitly specify the levels of each context and the assumptions about those contributions.

For example the main contributions are often interpreted as the behavior within each factor level; in our card example we might talk about the isolated influence from color on the behavior of the cards. There are no cards, however, that are characterized by only color. The contributions from the color and symbol levels always accompany each other, not to mention the corresponding intersections. In order to isolate an independent color contribution we'd have to consider an artificial circumstance where baseline contribution, the main symbol contributions, and all of the intersection contributions vanish,

θ=δl2f2=δl1,l2f1,f2=0θl1,l2f1,f2=0+δl1f1+0+0=δl1f1.\begin{align*} \theta &= \delta^{f_{2}}_{l_{2}} = \delta^{f_{1}, f_{2}}_{l_{1}, l_{2}} = 0 \\ \theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} &= 0 + \delta^{f_{1}}_{l_{1}} + 0 + 0 = \delta^{f_{1}}_{l_{1}}. \end{align*}

If the artificiality of this construction is taken for granted then it can lead to far more misunderstanding than insight.

3.3 Residual Hierarchies

Once we've decomposed the full interaction factor into a residual sequence we can build a multifactor compatible hierarchical model by assigning independent hierarchies to each contributing factor,

θl1,l2f1,f2=θ+δl1f1+δl2f2+δl1,l2f1,f2δl1,l2f1,f2∼π(ϕf1,f2)δl1f1∼π(ϕf1)δl2f2∼π(ϕf2).\begin{align*} \theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} &= \theta + \delta^{f_{1}}_{l_{1}} + \delta^{f_{2}}_{l_{2}} + \delta^{f_{1}, f_{2}}_{l_{1}, l_{2}} \\ \delta^{f_{1}, f_{2}}_{l_{1}, l_{2}} &\sim \pi( \phi^{f_{1}, f_{2}} ) \\ \delta^{f_{1}}_{l_{1}} &\sim \pi( \phi^{f_{1}} ) \\ \delta^{f_{2}}_{l_{2}} &\sim \pi( \phi^{f_{2}} ). \end{align*}

The advantage of this construction over building a hierarchy over the main interaction factor levels directly is that we have much more flexibility in the prior modeling.

In particular if the higher-order interactions grow weaker, and the behavior of each context is dominated by the leading-order contributions, then we can use narrower priors on the higher-order population parameters to provide stronger regularization. This is especially useful given that the higher-order interaction factor levels will be more sparsely occupied and less constrained by the observed likelihood function than the lower-order terms.

At the same time if the significance of the contributions does decay with order then at some point the higher-order contributions can be neglected without really affecting the quality of our inferences. Although dropping higher-order contributions technically results in hierarchical models that are not exactly compatible with the overlapping exchangeability of the individual factors, we may not be able to resolve those incompatibilities without the very precise inferences afforded by massive data sets.

In fact the residual construction provides a natural scaffolding for expanding our hierarchical models with a sequence of truncated models that capture more and more delicate features of the interacting factors. We start with a zeroth-order model where all of the intersection levels behave the same,

δl1,…,lFf1,…,fF≈θ.\delta^{f_{1}, \ldots, f_{F}}_{l_{1}, \ldots, l_{F}} \approx \theta.
Once we fit this initial model we can look for indications of heterogeneity across the factor levels with carefully designed posterior retrodictive checks. If these checks indicate that excess heterogeneity is important then we might add the first-order residuals,
δl1,…,lFf1,…,fF≈θ+∑f=1Fδlff,\delta^{f_{1}, \ldots, f_{F}}_{l_{1}, \ldots, l_{F}} \approx \theta + \sum_{f = 1}^{F} \delta^{f}_{l_{f}},
and then check for excess heterogeneity within the first-order intersection groups. If we continue to see excesses then we can add the first-order intersections into the model,
δl1,…,lFf1,…,fF≈θ+∑f=1Fδlff+∑f1=1F∑f1=f2+1F+δlf1,f2f1,f2.\delta^{f_{1}, \ldots, f_{F}}_{l_{1}, \ldots, l_{F}} \approx \theta + \sum_{f = 1}^{F} \delta^{f}_{l_{f}} + \sum_{f_{1} = 1}^{F} \sum_{f_{1} = f_{2} + 1}^{F} + \delta^{f_{1}, f_{2}}_{l_{f_{1}}, f_{2}}.

In practice expansion based on posterior retrodictive checks alone is limited by our ability to design a summary statistic that is directly sensitive to the potential heterogeneity. This is especially true in complex models where the heterogeneity is only one of many different, varying contributions to the data generating process. The residual scaffolding, however, can still be useful even without sensitive posterior retrodictive checks. Instead of terminating when the posterior retrodictive checks show no deviant behavior we can terminate when the posterior inferences for the most recent, highest-order contribution are consistent with zero.

By following the natural order of the residuals we model only as much heterogeneity as is supported by our observations, avoiding degenerate inferences from over-parameterized models without sacrificing explanatory power within the scope of those observations. Of course if that scope changes then the validity of a truncated model will also, in general, change. In particular a truncated model that is sufficient for a small data set is unlikely to remain sufficient when we consider larger data sets where we can resolve more and more subtle behaviors that often manifest only in the higher-order interaction contributions.

3.4 Extra Credit: Getting Tensor

The residual expansion that we constructed somewhat heuristically above can be formalized more rigorously using the mathematics of tensor algebra.

Consider two vectors: a\mathbf{a} containing NaN_{\mathbf{a}} elements and b\mathbf{b} containing NbN_{\mathbf{b}} elements. There are two natural ways to combine these vectors into new objects.

Firstly the direct sum a⊕b\mathbf{a} \oplus \mathbf{b} is the vector with Na+NbN_{\mathbf{a}} + N_{\mathbf{b}} elements obtained by concatenating the elements of the two vectors together.

Given II vectors fi\mathbf{f}_{i} we can apply the direct sum recursively, concatenating all of the vectors together to construct the total direct sum ⊕i=1Ifi\oplus_{i = 1}^{I} \mathbf{f}_{i} with ∑i=1INfi\sum_{i = 1}^{I} N_{\mathbf{f}_{i}} total elements.

Secondly the tensor product a⊗b\mathbf{a} \otimes \mathbf{b} is a collection of Na⋅NbN_{\mathbf{a}} \cdot N_{\mathbf{b}} elements defined by replicating the entire vector b\mathbf{b} for every element of a\mathbf{a}, or equivalently replicating the entire vector a\mathbf{a} for every element of b\mathbf{b}. Individual elements of the tensor product can be defined by picking one element of a\mathbf{a} and then an element of the associated copy of b\mathbf{b}, or vice versa. In other words every element a⊗b\mathbf{a} \otimes \mathbf{b} can be defined by an ordered pair (a,b)(a, b), where aa is an element of a\mathbf{a} and bb is an element of b\mathbf{b}.

The component vectors are denoted rank one tensors and their tensor product a rank two tensor.

Given II vectors fi\mathbf{f}_{i} we can apply the tensor product recursively to construct a rank II tensor ⊕i=1Ifi\oplus_{i = 1}^{I} \mathbf{f}_{i} with ∏i=1INfi\prod_{i = 1}^{I} N_{\mathbf{f}_{i}} total elements. This then allows us to define the tensor product of a rank RR tensor with N1N_{1} elements and a rank SS tensor with N2N_{2} elements as a rank R+SR + S tensor with N1⋅N2N_{1} \cdot N_{2} elements.

The tensor product of II vectors defines an II-dimensional, or rank II, multidimensional array. Each element is identified with II indices, where the iith index identifies which element of the iith component vector contributes to the tensor element.

The direct sum and tensor product play nicely with each other, generating an algebra with many of the properties familiar to the integers and the real numbers. For example if 1\mathbf{1} denotes a constant vector then we can expand products of sums,

(1⊕a⊕b)2=(1⊕a⊕b)⊗(1⊕a⊕b)=        (1⊗1)⊕(1⊗a)⊕(1⊗b)⊕ (a⊗1)⊕(a⊗a)⊕(a⊗b)⊕ (b⊗1)⊕(b⊗a)⊕(b⊗b).\begin{align*} (\mathbf{1} \oplus \mathbf{a} \oplus \mathbf{b})^{2} &= (\mathbf{1} \oplus \mathbf{a} \oplus \mathbf{b}) \otimes (\mathbf{1} \oplus \mathbf{a} \oplus \mathbf{b}) \\ &= \;\;\;\; (\mathbf{1} \otimes \mathbf{1}) \oplus (\mathbf{1} \otimes \mathbf{a}) \oplus (\mathbf{1} \otimes \mathbf{b}) \\ &\quad \oplus \, (\mathbf{a} \otimes \mathbf{1}) \oplus (\mathbf{a} \otimes \mathbf{a}) \oplus (\mathbf{a} \otimes \mathbf{b}) \\ &\quad \oplus \, (\mathbf{b} \otimes \mathbf{1}) \oplus (\mathbf{b} \otimes \mathbf{a}) \oplus (\mathbf{b} \otimes \mathbf{b}). \end{align*}

Now something interesting happens if assume that the quadratic terms in a\mathbf{a} and b\mathbf{b} vanish,

a⊗a=b⊗b=0,\mathbf{a} \otimes \mathbf{a} = \mathbf{b} \otimes \mathbf{b} = 0,
that the order of the direct sums doesn't matter,
a⊕b=b⊕a,\mathbf{a} \oplus \mathbf{b} = \mathbf{b} \oplus \mathbf{a},
and finally that the order of the tensor products doesn't matter,
a⊗b=b⊗a.\mathbf{a} \otimes \mathbf{b} = \mathbf{b} \otimes \mathbf{a}.
In this case the expanded product reduces to
(1⊕a⊕b)2=(1⊗1)⊕(a⊗1)⊕(1⊗b)⊕(a⊗b)\begin{align*} (\mathbf{1} \oplus \mathbf{a} \oplus \mathbf{b})^{2} &= \quad (\mathbf{1} \otimes \mathbf{1}) \\ & \quad \oplus (\mathbf{a} \otimes \mathbf{1}) \oplus (\mathbf{1} \otimes \mathbf{b}) \\ & \quad \oplus (\mathbf{a} \otimes \mathbf{b}) \end{align*}
which has the exact same form as residual expansion that we derived in Section 3.2!

In particular we can associate a\mathbf{a} and b\mathbf{b} with two factors, 1⊗1\mathbf{1} \otimes \mathbf{1} the rank zero baseline contribution, a⊗1\mathbf{a} \otimes \mathbf{1} and 1⊗b\mathbf{1} \otimes \mathbf{b} the rank one main contributions, and a⊗b\mathbf{a} \otimes \mathbf{b} the rank two interaction contribution. Truncating the residual expansion then corresponds to a low rank approximation of the tensor product (1⊕a⊕b)2(\mathbf{1} \oplus \mathbf{a} \oplus \mathbf{b})^{2}.

For example given the factor a\mathbf{a} with four levels and the factor b\mathbf{b} with three levels we can expand

(1⊗a⊗b)2( \mathbf{1} \otimes \mathbf{a} \otimes \mathbf{b})^{2}
into a series of contributions with progressively increasing rank.

Given three factors -- a\mathbf{a} with four levels, b\mathbf{b} with three levels, and c\mathbf{c} with five levels -- the product

(1⊗a⊗b⊗c)3( \mathbf{1} \otimes \mathbf{a} \otimes \mathbf{b} \otimes \mathbf{c})^{3}
admits a similar decomposition.

In general given II factors we can use this particular tensor algebra to systematically generate and organize all of the terms in the residual expansion, including all of the higher-order interaction factors, by expanding

(1⊕(⊕i=1Ifi))I,\big( \mathbf{1} \oplus ( \oplus_{i = 1}^{I} \mathbf{f}_{i} ) \big)^{I},
dropping all terms with more than one factor of any of the fi\mathbf{f}_{i}, and then combining any tensor products that are equivalent up to permutations. Although this may seem excessively formal in the low rank examples that we've considered so far, it can be helpful when trying to reason about or even automatically implement much higher rank systems.

3.5 Residual Degeneracies

As useful as the residual expansion can be in structuring heterogeneity and motivating principled model expansion, not to mention facilitating prior modeling within each model iteration, the approach does introduce some complications. In particular if we don't observe enough contexts then our likelihood functions may not be able to identify the different residual contributions from each other.

Recall that we can interpret the contributions at any order as coming from an appropriate factor. For example the baseline contribution is given by a factor with just one level, the main contributions are given by the main factors, and the first-order interaction contribution is given by the interaction factors formed by intersecting the levels from each pair of main factors. How many observations are associated with each level, or the occupancy, provides critical information about how degenerate our inferences of those levels will be with the levels of lower-order factors.

Those levels that have no occupancy at all are of particular interest. Let's define a factor configuration as a binary classification of which levels have zero occupancy and which levels have non-zero occupancy. For first order interactions we can readily communicate this configuration with a table or lattice plot.

Careful analysis of these configurations can alert us to degeneracies between the different residual contributions. For example consider a first-order factor where only one level is observed.

Because only one level is observed we can shift a constant between the baseline term and this main factor contribution without affecting the reconstructed behavior,

θl1,l2f1,f2=θ+δl1f1=(θ+α)+(δl1f1−α),\begin{align*} \theta^{f_{1}, f_{2}}_{l_{1}, l_{2}} &= \theta + \delta^{f_{1}}_{l_{1}} \\ &= \big( \theta + \alpha \big) + \big( \delta^{f_{1}}_{l_{1}} - \alpha \big), \end{align*}
resulting in a non-identified likelihood function. We need to observe some heterogeneity in order to distinguish the two contributions!

Similarly consider two factors but observe only one interaction level associated with two factor levels.

In this case we can shift a constant between the two main factor contributions and the corresponding interaction contributions without affecting the reconstructed behavior,

θ2,2f1,f2=θ+δ2f1+δ2f2+δ2,2f1,f2=θ+(δ2f1−α)+(δ2f2−β)+(δ2,2f1,f2+α+β),\begin{align*} \theta^{f_{1}, f_{2}}_{2, 2} &= \theta + \delta^{f_{1}}_{2} + \delta^{f_{2}}_{2} + \delta^{f_{1}, f_{2}}_{2, 2} \\ &= \theta + \big( \delta^{f_{1}}_{2} - \alpha \big) + \big( \delta^{f_{2}}_{2} - \beta \big) + \big( \delta^{f_{1}, f_{2}}_{2, 2} + \alpha + \beta \big), \end{align*}
resulting in yet another non-identifiable likelihood function.

These non-identified configurations lead to degenerate likelihood functions no matter how much data we replicate with that particular factor configuration. Prior models can help regularize the resulting posterior inferences, but ideally we would observe a sufficient diversity of contexts so that the likelihood function could do its fair share.

The study and design of factor configurations that allow higher-order interactions to be distinguished from the lower-order contributions is a key objective of experimental design in classical statistics [1]. In particular sophisticated combinatoric methods motivate particular factor configurations, or designs, such as Latin hypercubes that are capable of identifying certain interaction terms with as few observed contexts as possible.

While these methods are intended to help in the design controlled experiments, they can also be useful for identifying the degeneracies inherent to an accidental or unintended factor configuration, for example one that arises when measurements are subjected to heavy selection bias. This information then informs what orders of residuals might be feasible as well as on which contributions we might need to focus elicitation of domain expertise for more informative prior models.

3.6 The Limitations of Overlapping Multifactor Models

Ultimately the residual decomposition is just a way of organizing heterogeneity across the overlapping levels of the component factors. As with any exchangeable model this organizations allows us to learn how behavior varies across the factor levels and their intersections, but it doesn't tell us why the behavior varies. When we assume that these exact variations extrapolate to external circumstances we are implicitly making assumptions not just about the multifactor model itself but also the generative process from which those heterogeneities arise, and hence the interpretation of the multifactor model.

This is especially important when the interpretation of the factor levels, or their assignments, is ambiguous. For example because many common demographic factors like ethnicity and race are socially constructed, their level assignments can differ significantly when self-identified by the individuals themselves or externally identified by researchers. Even if substantial heterogeneity manifests across the assigned levels we will have trouble determining how that heterogeneity generalizes if we don't understand how those levels were assigned, and hence the precise interpretation of the factors.

Moreveor how well a decomposition of heterogeneity across the factor levels and their intersections captures the behavior of any latent generative process depends on exactly which factors, and which levels within those factors, are considered. If the factor levels poorly correlate with the generative process then even multifactor models with higher-order interactions will resolve only a partial picture of that process; the heterogeneity that manifests across those levels and their intersections will provide only limited information that, at best, awkwardly generalizes to external circumstances. Indeed the less sensitive the levels are to the generative structure, the more prone the resulting multifactor models will be to contorting to accidental patterns in the observations that do happen to align with the factors.

For example consider the case where we're using a multifactor model to capture systematic behavior inherent to a particular measurement procedure, as opposed to behavior that manifests from the latent phenomena being observed. If the factors aren't rich enough to fully represent those systematic behaviors then the phenomenological part of the model may attempt to compensate. The resulting inferences of the phenomenological behavior will then be corrupted by this contortion and poorly generalize to circumstances where the latent phenomena is observed differently.

Similarly consider the case where our measurements probe some phenomena about which we don't yet know enough to build a generative model. In this case we might use a multifactor model as an initial heuristic model to learn about the broad behavior of that latent phenomena. Again if we don't include enough relevant factors then our inferences can be erratic, in the best case highly uncertain and in the worst case misleading as the rigid factors adapt to only certain projections of the latent phenomenological behavior of interest. When trying to increases sales, for example, a multifactor model based on demographic factors will be of limited use if patterns in purchasing behavior do not manifest as a strong heterogeneity within demographic levels and their lower-order interactions.

At the same time the factor levels that are actually observed can be just as critical. When observations exhaust all of the input factor levels we know that our data are sensitive to the full range of possible behaviors that the multifactor model can accommodate. If many levels are unobserved, however, then the resulting multifactor model will not take full advantage of the given factors!

For example classical experimental design is often focused on probing the behavior of some system only around some operational baseline. In particular only a few factors levels that most strongly associated with the baseline levels might be included.

Although we assume that the heterogeneity across the levels is exchangeable, the design for which levels are observed is very much not exchangeable here! Because of this limitation the resulting multifactor model will be sensitive only to behavior around that chosen baseline. When working with only partially observed factors it's critical to investigate the behavior near the boundary levels for any indications of trends that might persist beyond, for example trends that peak around the "X" in the above figure. In some cases expanding factor designs to include more levels can be more useful than adding new factors!

As critical as the choice of main factors, their observed levels, and their interpretations is, we do not always have the luxury of that choice in practice. In many cases the available factors are determined not by careful statistical design but rather by external conventions or even alternative priorities such as privacy. For example when working with survey data we are typically limited to common demographic factors that may correlate poorly with the behaviors in which we're interested. When we aren't able to design relevant factors we have to be especially mindful of the limitations of overlapping multifactor models and their resulting inferences.

When the main factors are well chosen, and the behavior of the system being observed manifests in largely independent variation across the each factor, then the interaction factors tend to be less important and can often be ignored without a substantial loss of exploratory power. If the main factors are not quite as well chosen, however, then those behaviors often manifest most strongly in the interaction levels. Indeed the more complex the behavior the higher the order of the interaction in which it will tend to manifest.

The importance of interactions in understanding sophisticated systems is well known in many fields. For instance the framework of intersectionality [2] emphasizes the important societal, cultural, and political consequences that vary across the intersections of common demographic features. The experience of a Black woman, for example, cannot in most circumstances be accurately characterized solely by the experiences common to all women and the experiences common to all Black people. Ignoring this interaction then results in not just poor inferences but also ineffectual policy informed by those inferences. Of course the importance of these interactions is further complicated by the interpretation of race as discussed above!

In order to ensure robust inferences we cannot take for granted the dominance of the main factors, and the negligibility of the interaction factors. While finite measurements may not be able to resolve any heterogeneity in the interactions factors, especially the higher-order interaction factors, we have to explicitly verify that this is the case in any given analysis with, for example, posterior inferences or posterior retrodictive checks.

Ultimately the choice of both main and interaction factors is critical to the utility of a multifactor model. The more each factor is sensitive to the relevant behavior the more generative consequences the resulting multifactor model will be able to represent. Similarly the more precisely we can interpret each factor the more we can understand those generative consequences and the better we will be able to determine when those consequences generalize.

4 Experiments

To reinforce these concepts let's put them to work in some demonstrative examples. In this section we'll review implementations of single factor, nested multifactor, and overlapping multifactor models in Stan and some basic workflow principles.

We begin by setting up our local R environment.

text
library(rstan)
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
parallel:::setDefaultClusterOptions(setup_strategy = "sequential")

util <- new.env()
source('stan_utility.R', local=util)

c_light <- c("#DCBCBC")
c_light_highlight <- c("#C79999")
c_mid <- c("#B97C7C")
c_mid_highlight <- c("#A25050")
c_dark <- c("#8F2727")
c_dark_highlight <- c("#7C0000")

c_light_trans <- c("#DCBCBC80")
c_dark_trans <- c("#8F272780")
c_green_trans <- c("#00FF0080")

par(family="CMU Serif", las=1, bty="l", cex.axis=1, cex.lab=1, cex.main=1,
    xaxs="i", yaxs="i", mar = c(5, 5, 3, 5))
   
set.seed(9958284)

4.1 Single Factor Models in Action

First let's read in our data and take a look at its contents.

text
data <- read_rdump("data/single_factor1.data.R")

names(data)
text
[1] "y"                "N_factor_levels"  "sigma"            "K"               
[5] "N"                "obs_to_context"   "context_to_level"

The data y contain N = 4050 independent, one-dimensional, and real-valued values y each generated with a known measurement variability sigma.

These observations are reasonably uniformly distribution across K = 81 individual contexts. The variable obs_to_context identifies to which context each observation is associated.

text
hist(data$obs_to_context, breaks=seq(0.5, data$K + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$K + 0.5), xlab="Context",
     ylim=c(0, 80), ylab="Context Observations")

Our lone factor spans N_factor_levels = 9 levels, each of which contains 9 indiviual contexts. The variable context_to_level identifies to which factor level each individual context is associated.

text
hist(data$context_to_level, breaks=seq(0.5, data$N_factor_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor_levels + 0.5), xlab="Level",
     ylim=c(0, 10), ylab="Level Occupancies")

Composing obs_to_context and context_to_level identifies to which factor level each observation is associated, allowing us to for example count how many observations inform the behavior in each level. Because the observations within context and contexts within levels are reasonably uniformly distributed so too are the observations within each level.

text
hist(data$context_to_level[data$obs_to_context],
     breaks=seq(0.5, data$N_factor_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor_levels + 0.5), xlab="Level",
     ylim=c(0, 500), ylab="Level Observations")

Implementing a hierarchical model capturing both the marginal and conditional exchangeability induced by the factor is pretty straightforward in Stan. Here we use a monolithically centered parameterization.

text
writeLines(readLines("stan_programs/marginal_conditional_cp.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability
  
  // Number of individual contexts
  int<lower=0> K;
  int<lower=1, upper=K> obs_to_context[N];
  
  // Factor information
  int<lower=0> N_factor_levels;
  int<lower=1, upper=N_factor_levels> context_to_level[K];
}

parameters {
  // Centered hierarchical models for the conditional heterogeneity within each level
  vector[K] context_theta;                       // Centered individual parameters
  vector<lower=0>[N_factor_levels] residual_tau; // Population scales within each level
  
  // Centered hierarchical model for the marginal level heterogeneity
  vector[N_factor_levels] factor_theta; // Centered individual parameters
  real factor_mu;                       // Population location
  real<lower=0> factor_tau;             // Population scale
}

model {
  context_theta ~ normal(factor_theta[context_to_level],
                         residual_tau[context_to_level]);
  residual_tau ~ normal(0, 3);
    
  factor_theta ~ normal(factor_mu, factor_tau);
  factor_mu ~ normal(0, 5);
  factor_tau ~ normal(0, 3);
  
  y ~ normal(context_theta[obs_to_context], sigma);
}

Given the program Stan can do its Hamiltonian thing.

text
fit <- stan(file='stan_programs/marginal_conditional_cp.stan',
            data=data, seed=4838282, refresh=1000)

No diagnostics indications of problems provides some confidence that we can trust the fit.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

To visualize the posterior inferences for the marginal heterogeneity we plot the level parameters together with the population location for comparison, and then the population scale on the side. We infer significant variation across the factor levels.

text
samples <- extract(fit)

layout(matrix(c(1, 1, 2), nrow=1))

L <- data$N_factor_levels
idx <- rep(1:(L + 1), each=2)
x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:L, function(l)
                    quantile(samples$factor_theta[,l], probs=probs))
cred <- cbind(cred, quantile(samples$factor_mu, probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

par(mar=c(5, 5, 3, 1))
plot(1, type="n", main="Marginal Heterogeneity",
     xlim=c(0.5, L + 1.5), xlab="", xaxt="n",
     ylim=c(min(pad_cred[1,]), max(pad_cred[9,])), ylab="Marginal Posterior")
abline(v=L+0.5, col="gray80", lwd=2, lty=3)

polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
for (l in 1:(L + 1))
  lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

axis(1, at=1:(L + 1),
     labels=c(sapply(1:L, function(l) paste("l", l, sep="")), "mu"))

par(mar=c(5, 1, 3, 1))
u <- 1.25 * max(samples$factor_tau)
hist(samples$factor_tau, breaks=seq(0, u, u / 50), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")

In order to visualize the conditional heterogeneity we have to repeat this for the hierarchical models within each of the nine levels. The variation is consistently strong across all of the levels.

text
for (l in 1:L) {
  layout(matrix(c(1, 1, 2), nrow=1))

  context_idx <- which(data$context_to_level == l)
  K <- length(context_idx)
  idx <- rep(1:(K + 1), each=2)
  x <- sapply(1:length(idx), function(k) if(k %% 2 == 0) idx[k] + 0.5 else idx[k] - 0.5)

  probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
  cred <- sapply(context_idx, function(k)
                      quantile(samples$context_theta[,k], probs=probs))
  cred <- cbind(cred, quantile(samples$factor_theta[,l], probs=probs))
  pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

  par(mar=c(5, 5, 3, 1))
  plot(1, type="n", main=paste("Conditional Heterogeneity Within Level", l),
       xlim=c(0.5, K + 1.5), xlab="", xaxt="n",
       ylim=c(min(pad_cred[1,]), max(pad_cred[9,])), ylab="Marginal Posterior")
  abline(v=L+0.5, col="gray80", lwd=2, lty=3)

  polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
          col = c_light, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
          col = c_light_highlight, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
          col = c_mid, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
          col = c_mid_highlight, border = NA)
  for (k in 1:(K + 1))
    lines(x[(2*k-1):(2*k)], pad_cred[5,(2*k-1):(2*k)], col=c_dark, lwd=2)


  axis(1, at=1:(K + 1),
       c(sapply(context_idx, function(k) paste("c", k, sep="")), paste("l", l, sep="")))

  par(mar=c(5, 1, 3, 1))
  u <- 1.25 * max(samples$residual_tau[,l])
  hist(samples$residual_tau[,l], breaks=seq(0, u, u / 50), main="",
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
}

The same model can also be implemented with a non-centered parameterization with respect to the location parameters, resulting in a natural a residual interpretation. Note that the program is still centered with respect to the scale parameters.

text
writeLines(readLines("stan_programs/marginal_conditional_residual_cp.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  
  real<lower=0> sigma; // Measurement variability
  
  // Number of individual contexts
  int<lower=0> K;
  int<lower=1, upper=K> obs_to_context[N];
  
  // Factor information
  int<lower=0> N_factor_levels;
  int<lower=1, upper=N_factor_levels> context_to_level[K];
}

parameters {
  // Centered hierarchical models for the within-level residuals
  vector[K] delta_context;                          // Centered residuals
  real<lower=0> delta_context_tau[N_factor_levels]; // Residual population scales
  
  // Centered hierarchical model for between level residuals
  vector[N_factor_levels] delta_factor; // Centered residuals
  real<lower=0> delta_factor_tau;       // Residual population scales
  
  // Baseline
  real baseline;
}

transformed parameters {
  vector[K] theta_context =  baseline                        // Baseline
                           + delta_factor[context_to_level]  // Between level variation
                           + delta_context;                  // Within level variation
}

model {
  delta_context ~ normal(0, delta_context_tau[context_to_level]);
  delta_context_tau ~ normal(0, 3);
    
  delta_factor ~ normal(0, delta_factor_tau);
  delta_factor_tau ~ normal(0, 3);
  
  baseline ~ normal(0, 5);
  
  y ~ normal(theta_context[obs_to_context], sigma);
}

We run.

text
fit <- stan(file='stan_programs/marginal_conditional_residual_cp.stan',
            data=data, seed=4838282, refresh=1000)

No indications of fitting problems.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

This new parameterization suggests a different visualization of our posterior inferences. We first show the marginal posterior for the baseline parameter.

text
samples <- extract(fit)

par(mfrow=c(1, 1), mar=c(5, 1, 3, 1))

hist(samples$baseline, breaks=seq(0, 15, 0.1), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 11), xlab="Baseline", yaxt='n', ylab="")

We can then visualize the marginal residuals common to each factor level. In this case I also show lines for 0, plus twice the scale mean, and minus twice the scale mean to make it easier to compare the two plots.

text
layout(matrix(c(1, 1, 2), nrow=1))

L <- data$N_factor_levels
idx <- rep(1:L, each=2)
x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:L, function(l)
  quantile(samples$delta_factor[,l], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

mean_tau <- mean(samples$delta_factor_tau)

lb <- min(c(-2.25 * mean_tau, cred[1,]))
ub <- max(c(2.25 * mean_tau,  cred[9,]))

par(mar=c(5, 5, 3, 1))
plot(1, type="n", main="Marginal Heterogeneity",
     xlim=c(0.5, L + 0.5), xlab="", xaxt="n",
     ylim=c(lb, ub), ylab="Marginal Posterior")

lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
for (l in 1:L)
  lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

axis(1, at=1:L, labels=sapply(1:L, function(l) paste("l", l, sep="")))

par(mar=c(5, 1, 3, 1))
u <- 1.25 * max(samples$delta_factor_tau)
hist(samples$delta_factor_tau, breaks=seq(0, u, u / 50), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
abline(v=mean_tau, col="gray80", lwd=2, lty=3)

The conditional residuals for the individual contexts within each level are visualized similarly.

text
for (l in 1:L) {
  layout(matrix(c(1, 1, 2), nrow=1))

  context_idx <- which(data$context_to_level == l)
  K <- length(context_idx)
  idx <- rep(1:K, each=2)
  x <- sapply(1:length(idx), function(k) if(k %% 2 == 0) idx[k] + 0.5 else idx[k] - 0.5)

  probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
  cred <- sapply(context_idx, function(k)
    quantile(samples$delta_context[,k], probs=probs))
  pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

  mean_tau <- mean(samples$delta_context_tau[,l])

  lb <- min(c(-2.25 * mean_tau, cred[1,]))
  ub <- max(c(2.25 * mean_tau,  cred[9,]))

  par(mar=c(5, 5, 3, 1))
  plot(1, type="n", main=paste("Conditional Heterogeneity Within Level", l),
       xlim=c(0.5, K + 0.5), xlab="", xaxt="n",
       ylim=c(lb, ub), ylab="Marginal Posterior")

  lines(c(0.5, K + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
  lines(c(0.5, K + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
  lines(c(0.5, K + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

  polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
          col = c_light, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
          col = c_light_highlight, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
          col = c_mid, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
          col = c_mid_highlight, border = NA)
  for (k in 1:K)
    lines(x[(2*k-1):(2*k)], pad_cred[5,(2*k-1):(2*k)], col=c_dark, lwd=2)

  axis(1, at=1:(K + 1),
       c(sapply(context_idx, function(k) paste("c", k, sep="")), paste("l", l, sep="")))

  par(mar=c(5, 1, 3, 1))
  u <- 1.25 * max(samples$delta_context_tau[,l])
  hist(samples$delta_context_tau[,l], breaks=seq(0, u, u / 50), main="",
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
  abline(v=mean_tau, col="gray80", lwd=2, lty=3)
}

Riding high on statistics let's consider a different observation of the same system.

text
data <- read_rdump("data/single_factor2.data.R")

Here we have only N = 810 total observations distributed across the same K = 81 individual contexts.

text
par(mfrow=c(1, 1), mar=c(5, 5, 3, 5))

hist(data$obs_to_context, breaks=seq(0.5, data$K + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$K + 0.5), xlab="Context",
     ylim=c(0, 25), ylab="Context Observations")

The level occupancies are no longer exactly uniform as well.

text
hist(data$context_to_level, breaks=seq(0.5, data$N_factor_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor_levels + 0.5), xlab="Level",
     ylim=c(0, 15), ylab="Level Occupancies")

Consequently the number of observations associated with each level are fewer and more variable.

text
hist(data$context_to_level[data$obs_to_context],
     breaks=seq(0.5, data$N_factor_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor_levels + 0.5), xlab="Level",
     ylim=c(0, 175), ylab="Level Observations")

How will our current Stan program fare?

text
fit <- stan(file='stan_programs/marginal_conditional_residual_cp.stan',
            data=data, seed=4838282, refresh=1000)

Not well!

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "83 of 4000 iterations ended with a divergence (2.075%)"
[1] "  Try running with larger adapt_delta to remove the divergences"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

Let's track down those divergences to see if we can find the problem.

text
partition <- util$partition_div(fit)
div_samples <- partition[[1]]
nondiv_samples <- partition[[2]]

The marginal level parameters exhibit a mild funnel geometry.

text
par(mfrow=c(3, 3))
par(mar=c(5, 5, 3, 1))

for (l in 1:9) {
  name_x <- paste("delta_factor[", l, "]", sep='')
  name_y <- "delta_factor_tau"

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=paste("l =", l),
       xlab=name_x, xlim=c(-6, 6),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-1, 2))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

The context parameters, however, show much stronger funnels. The concentration of divergences in the neck of some of the funnels strongly indicates that we need to fully non-center these parameters.

text
par(mfrow=c(1, 4))

for (k in 1:81) {
  name_x <- paste("delta_context[", k, "]", sep='')
  name_y <- paste("delta_context_tau[", data$context_to_level[k], "]", sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=paste("k =", k),
       xlab=name_x, xlim=c(-15, 15),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-5, 3))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

Instead of writing a Stan program for each possible parameterization let's be a little more foresightful and write one Stan program with a configurable parameterization.

text
writeLines(readLines("stan_programs/marginal_conditional_residual_mixed.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability
  
  // Context information
  int<lower=0> K;
  int<lower=1, upper=K> obs_to_context[N];
  
  int<lower=0, upper=K> K_ncp;                  // Number of noncentered contexts
  int<lower=1, upper=K> context_ncp_idx[K_ncp]; // Index of noncentered contexts
  
  int<lower=0, upper=K> K_cp;                   // Number of centered contexts
  int<lower=1, upper=K> context_cp_idx[K_cp];   // Index of noncentered contexts
  
  // Factor information
  int<lower=0> N_factor_levels;
  int<lower=1, upper=N_factor_levels> context_to_level[K];
  
  int<lower=0, upper=N_factor_levels> L_ncp;                 // Number of noncentered levels
  int<lower=1, upper=N_factor_levels> factor_ncp_idx[L_ncp]; // Index of noncentered levels

  int<lower=0, upper=N_factor_levels> L_cp;                  // Number of centered levels
  int<lower=1, upper=N_factor_levels> factor_cp_idx[L_cp];   // Index of noncentered levels
}

parameters {
  // Hierarchical models for the within-level residuals
  vector[K_ncp] delta_context_ncp;                    // Non-centered residuals
  vector[K_cp] delta_context_cp;                      // Centered residuals
  vector<lower=0>[N_factor_levels] delta_context_tau; // Residual scales
  
  // Hierarchical model for between-level residuals
  vector[L_ncp] delta_factor_ncp; // Non-centered residuals
  vector[L_cp]  delta_factor_cp;  // Centered residuals
  real<lower=0> delta_factor_tau; // Residual scale
  
  // Baseline
  real baseline;
}

transformed parameters {
  vector[K] delta_context;
  vector[N_factor_levels] delta_factor;
  vector[K] theta_context;
  
  delta_context[context_ncp_idx] 
    = delta_context_tau[context_to_level[context_ncp_idx]] .* delta_context_ncp;
  delta_context[context_cp_idx] = delta_context_cp;
  
  delta_factor[factor_ncp_idx] = delta_factor_tau * delta_factor_ncp;
  delta_factor[factor_cp_idx] = delta_factor_cp;
  
  theta_context =  baseline                        // Baseline
                 + delta_factor[context_to_level]  // Between-level variation
                 + delta_context;                  // Within-level variation
}

model {
  delta_context_cp ~ normal(0, delta_context_tau[context_to_level[context_cp_idx]]);
  delta_context_ncp ~ normal(0, 1);
  delta_context_tau ~ normal(0, 3);
    
  delta_factor_cp ~ normal(0, delta_factor_tau);
  delta_factor_ncp ~ normal(0, 1);
  delta_factor_tau ~ normal(0, 3);
  
  baseline ~ normal(0, 5);
  
  y ~ normal(theta_context[obs_to_context], sigma);
}

To start we fully non-center all of the parameters.

text
data$context_cp_idx <- vector()
data$K_cp <- length(data$context_cp_idx)

data$context_ncp_idx <- setdiff(1:data$K, data$context_cp_idx)
data$K_ncp <- length(data$context_ncp_idx)

data$factor_cp_idx <- vector()
data$L_cp <- length(data$factor_cp_idx)

data$factor_ncp_idx <- setdiff(1:data$N_factor_levels, data$factor_cp_idx)
data$L_ncp <- length(data$factor_ncp_idx)

Hopeful, we try again.

text
fit <- stan(file='stan_programs/marginal_conditional_residual_mixed.stan',
            data=data, seed=4838282, refresh=1000)

Fortunately the divergences have vanished and we no longer have any indication that our Markov chains are not faithfully capturing our posterior inferences.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

Consequently we can proceed to visualize our results. First the baseline.

text
samples <- extract(fit)

par(mfrow=c(1, 1), mar=c(5, 1, 3, 1))

hist(samples$baseline, breaks=seq(0, 15, 0.1), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 11), xlab="Baseline", yaxt='n', ylab="")

Then the marginal residuals.

text
layout(matrix(c(1, 1, 2), nrow=1))

L <- data$N_factor_levels
idx <- rep(1:L, each=2)
x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:L, function(l)
  quantile(samples$delta_factor[,l], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

mean_tau <- mean(samples$delta_factor_tau)

lb <- min(c(-2.25 * mean_tau, cred[1,]))
ub <- max(c(2.25 * mean_tau,  cred[9,]))

par(mar=c(5, 5, 3, 1))
plot(1, type="n", main="Marginal Heterogeneity",
     xlim=c(0.5, L + 0.5), xlab="", xaxt="n",
     ylim=c(lb, ub), ylab="Marginal Posterior")

lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
for (l in 1:L)
  lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

axis(1, at=1:L, labels=sapply(1:L, function(l) paste("l", l, sep="")))

par(mar=c(5, 1, 3, 1))
u <- 1.25 * max(samples$delta_factor_tau)
hist(samples$delta_factor_tau, breaks=seq(0, u, u / 50), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
abline(v=mean_tau, col="gray80", lwd=2, lty=3)

Finally the conditional residuals.

text
for (l in 1:L) {
  layout(matrix(c(1, 1, 2), nrow=1))

  context_idx <- which(data$context_to_level == l)
  K <- length(context_idx)
  idx <- rep(1:K, each=2)
  x <- sapply(1:length(idx), function(k) if(k %% 2 == 0) idx[k] + 0.5 else idx[k] - 0.5)

  probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
  cred <- sapply(context_idx, function(k)
    quantile(samples$delta_context[,k], probs=probs))
  pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

  mean_tau <- mean(samples$delta_context_tau[,l])

  lb <- min(c(-2.25 * mean_tau, cred[1,]))
  ub <- max(c(2.25 * mean_tau,  cred[9,]))

  par(mar=c(5, 5, 3, 1))
  plot(1, type="n", main=paste("Conditional Heterogeneity Within Level", l),
       xlim=c(0.5, K + 0.5), xlab="", xaxt="n",
       ylim=c(lb, ub), ylab="Marginal Posterior")

  lines(c(0.5, K + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
  lines(c(0.5, K + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
  lines(c(0.5, K + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

  polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
          col = c_light, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
          col = c_light_highlight, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
          col = c_mid, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
          col = c_mid_highlight, border = NA)
  for (k in 1:K)
    lines(x[(2*k-1):(2*k)], pad_cred[5,(2*k-1):(2*k)], col=c_dark, lwd=2)

  axis(1, at=1:(K + 1),
       c(sapply(context_idx, function(k) paste("k", k, sep="")), paste("l", l, sep="")))

  par(mar=c(5, 1, 3, 1))
  u <- 1.25 * max(samples$delta_context_tau[,l])
  hist(samples$delta_context_tau[,l], breaks=seq(0, u, u / 50), main="",
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
  abline(v=mean_tau, col="gray80", lwd=2, lty=3)
}

As discussed in Section 1.4 the conditional heterogeneity within each factor level is often not considered. In this case the levels themselves become the relevant contexts, and we need to provide a mapping from observations to these new contexts.

text
data$obs_to_level <- data$context_to_level[data$obs_to_context]

The corresponding Stan program doesn't require much more beyond excising the conditional hierarchies.

text
writeLines(readLines("stan_programs/marginal_residual_mixed.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability
  
  // Factor information
  int<lower=0> N_factor_levels;
  int<lower=1, upper=N_factor_levels> obs_to_level[N];
  
  int<lower=0, upper=N_factor_levels> L_ncp;                 // Number of noncentered levels
  int<lower=1, upper=N_factor_levels> factor_ncp_idx[L_ncp]; // Index of noncentered levels

  int<lower=0, upper=N_factor_levels> L_cp;                  // Number of centered levels
  int<lower=1, upper=N_factor_levels> factor_cp_idx[L_cp];   // Index of noncentered levels
}

parameters {
  // Hierarchical model for between-level residuals
  vector[L_ncp] delta_factor_ncp; // Non-centered residuals
  vector[L_cp]  delta_factor_cp;  // Centered residuals
  real<lower=0> delta_factor_tau; // Residual scale
  
  // Baseline
  real baseline;
}

transformed parameters {
  vector[N_factor_levels] delta_factor;
  vector[N_factor_levels] theta_level;
  
  delta_factor[factor_ncp_idx] = delta_factor_tau * delta_factor_ncp;
  delta_factor[factor_cp_idx] = delta_factor_cp;
  
  theta_level =  baseline      // Baseline
               + delta_factor; // Between-level variation
}

model {
  delta_factor_cp ~ normal(0, delta_factor_tau);
  delta_factor_ncp ~ normal(0, 1);
  delta_factor_tau ~ normal(0, 3);
  
  baseline ~ normal(0, 5);
  
  y ~ normal(theta_level[obs_to_level], sigma);
}

Using the same non-centered parameterization set above we can immediately fit.

text
fit <- stan(file='stan_programs/marginal_residual_mixed.stan',
            data=data, seed=4838282, refresh=1000)

With no indications of computational problems we can move onto investigating the posterior.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

As with any residual model we start with the baseline parameter.

text
samples <- extract(fit)

par(mfrow=c(1, 1), mar=c(5, 1, 3, 1))

hist(samples$baseline, breaks=seq(0, 15, 0.1), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 11), xlab="Baseline", yaxt='n', ylab="")

Then we can consider the level parameters that capture the marginal heterogeneity.

text
layout(matrix(c(1, 1, 2), nrow=1))

L <- data$N_factor_levels
idx <- rep(1:L, each=2)
x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:L, function(l)
  quantile(samples$delta_factor[,l], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

mean_tau <- mean(samples$delta_factor_tau)

lb <- min(c(-2.25 * mean_tau, cred[1,]))
ub <- max(c(2.25 * mean_tau,  cred[9,]))

par(mar=c(5, 5, 3, 1))
plot(1, type="n", main="Marginal Heterogeneity",
     xlim=c(0.5, L + 0.5), xlab="", xaxt="n",
     ylim=c(lb, ub), ylab="Marginal Posterior")

lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
for (l in 1:L)
  lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

axis(1, at=1:L, labels=sapply(1:L, function(l) paste("l", l, sep="")))

par(mar=c(5, 1, 3, 1))
u <- 1.25 * max(samples$delta_factor_tau)
hist(samples$delta_factor_tau, breaks=seq(0, u, u / 50), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
abline(v=mean_tau, col="gray80", lwd=2, lty=3)

4.2 Nested Multifactor Models in Action

Now let's advance to multiple factors with nested levels.

text
data <- read_rdump("data/nested_multifactor.data.R")

names(data)
text
[1] "factor2_to_factor1" "y"                  "sigma"             
[4] "N_factor2_levels"   "N_factor3_levels"   "N_factor1_levels"  
[7] "N"                  "obs_to_factor3"     "factor3_to_factor2"

We have three three nested factors. At the top Factor 3 has N_factor3_levels = 125 levels over which the N = 750 observations are relatively uniformly distributed.

text
par(mar=c(5, 5, 3, 5))
par(mfrow=c(1, 1))

hist(data$obs_to_factor3, breaks=seq(0.5, data$N_factor3_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor3_levels + 0.5), xlab="Factor Three Levels",
     ylim=c(0, 12), ylab="Number of Observations")

The Factor 3 levels are then nested within N_factor2_levels = 25 Factor 2 levels.

text
hist(data$factor3_to_factor2, breaks=seq(0.5, data$N_factor2_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor2_levels + 0.5), xlab="Factor Two Levels",
     ylim=c(0, 12), ylab="Number of Factor Three Levels")

The observations associated with the Factor 2 levels are also relatively uniform.

text
hist(data$factor3_to_factor2[data$obs_to_factor3],
     breaks=seq(0.5, data$N_factor2_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor2_levels + 0.5), xlab="Factor Two Levels",
     ylim=c(0, 70), ylab="Number of Observations")

Finally the Factor 2 levels are nested within N_factor1_levels = 5 Factor 1 levels.

text
hist(data$factor2_to_factor1, breaks=seq(0.5, data$N_factor1_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor1_levels + 0.5), xlab="Factor One Levels",
     ylim=c(0, 8), ylab="Number of Factor Two Levels")

Each of these five Factor 1 levels is associated with many observations, which also means that many more observations inform the behavior in those levels than in the levels of the higher factors.

text
hist(data$factor2_to_factor1[data$factor3_to_factor2[data$obs_to_factor3]],
     breaks=seq(0.5, data$N_factor1_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor1_levels + 0.5), xlab="Factor One Levels",
     ylim=c(0, 250), ylab="Number of Observations")

A general three factor nested model is similar to the full marginal conditional model we build for a single factor, only with one more layers of nesting. Knowing that we might need flexibility we start with a general implementation where we can readily configure the parameterization of each hierarchical parameter.

text
writeLines(readLines("stan_programs/nested_factors_residual.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  int<lower=0, upper=N_factor1_levels> L_factor1_ncp;
  int<lower=1, upper=N_factor1_levels> factor1_ncp_idx[L_factor1_ncp];

  int<lower=0, upper=N_factor1_levels> L_factor1_cp;
  int<lower=1, upper=N_factor1_levels> factor1_cp_idx[L_factor1_cp];
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  int<lower=0, upper=N_factor2_levels> L_factor2_ncp;
  int<lower=1, upper=N_factor2_levels> factor2_ncp_idx[L_factor2_ncp];

  int<lower=0, upper=N_factor2_levels> L_factor2_cp;
  int<lower=1, upper=N_factor2_levels> factor2_cp_idx[L_factor2_cp];
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  int<lower=0, upper=N_factor3_levels> L_factor3_ncp;
  int<lower=1, upper=N_factor3_levels> factor3_ncp_idx[L_factor3_ncp];

  int<lower=0, upper=N_factor3_levels> L_factor3_cp;
  int<lower=1, upper=N_factor3_levels> factor3_cp_idx[L_factor3_cp];
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

transformed data {
  // Expand nesting to simplify residual summation
  int<lower=1, upper=N_factor2_levels> obs_to_factor2[N] 
    = factor3_to_factor2[obs_to_factor3];
  int<lower=1, upper=N_factor2_levels> obs_to_factor1[N] 
    = factor2_to_factor1[obs_to_factor2];
}

parameters {  
  // Baseline
  real baseline;
  
  // Hierarchical model for the first factor residuals
  vector[L_factor1_ncp] delta_factor1_ncp;
  vector[L_factor1_cp] delta_factor1_cp;
  real<lower=0> delta_factor1_tau;
  
  // Hierarchical models for the second factor residuals
  vector[L_factor2_ncp] delta_factor2_ncp;
  vector[L_factor2_cp]  delta_factor2_cp;
  vector<lower=0>[N_factor1_levels] delta_factor2_tau;
  
  // Hierarchical models for the third factor residuals
  vector[L_factor3_ncp] delta_factor3_ncp;
  vector[L_factor3_cp]  delta_factor3_cp;
  vector<lower=0>[N_factor2_levels] delta_factor3_tau;
}

transformed parameters {
  vector[N_factor1_levels] delta_factor1;
  vector[N_factor2_levels] delta_factor2;
  vector[N_factor3_levels] delta_factor3;

  // Reconstruct first factor residuals
  delta_factor1[factor1_ncp_idx] = delta_factor1_tau * delta_factor1_ncp;
  delta_factor1[factor1_cp_idx] = delta_factor1_cp;

  // Reconstruct second factor residuals
  delta_factor2[factor2_ncp_idx] 
    =   delta_factor2_tau[factor2_to_factor1[factor2_ncp_idx]] .* delta_factor2_ncp;
  delta_factor2[factor2_cp_idx] = delta_factor2_cp;

  // Reconstruct third factor residuals
  delta_factor3[factor3_ncp_idx] 
    =   delta_factor3_tau[factor3_to_factor2[factor3_ncp_idx]] .* delta_factor3_ncp;
  delta_factor3[factor3_cp_idx] = delta_factor3_cp;
}

model {
  vector[N] theta =  baseline
                   + delta_factor1[obs_to_factor1]
                   + delta_factor2[obs_to_factor2]
                   + delta_factor3[obs_to_factor3];
    
  baseline ~ normal(0, 5);

  delta_factor1_cp ~ normal(0, delta_factor1_tau);
  delta_factor1_ncp ~ normal(0, 1);
  delta_factor1_tau ~ normal(0, 2);
    
  delta_factor2_cp ~ normal(0, delta_factor2_tau[factor2_to_factor1[factor2_cp_idx]]);
  delta_factor2_ncp ~ normal(0, 1);
  delta_factor2_tau ~ normal(0, 2);
  
  delta_factor3_cp ~ normal(0, delta_factor3_tau[factor3_to_factor2[factor3_cp_idx]]);
  delta_factor3_ncp ~ normal(0, 1);
  delta_factor3_tau ~ normal(0, 2);
  
  y ~ normal(theta, sigma);
}

Let's first consider a fully non-centered parameterization.

text
data$factor1_cp_idx <- vector()
data$L_factor1_cp <- length(data$factor1_cp_idx)

data$factor1_ncp_idx <- setdiff(1:data$N_factor1_levels, data$factor1_cp_idx)
data$L_factor1_ncp <- length(data$factor1_ncp_idx)

data$factor2_cp_idx <- vector()
data$L_factor2_cp <- length(data$factor2_cp_idx)

data$factor2_ncp_idx <- setdiff(1:data$N_factor2_levels, data$factor2_cp_idx)
data$L_factor2_ncp <- length(data$factor2_ncp_idx)

data$factor3_cp_idx <- vector()
data$L_factor3_cp <- length(data$factor3_cp_idx)

data$factor3_ncp_idx <- setdiff(1:data$N_factor3_levels, data$factor3_cp_idx)
data$L_factor3_ncp <- length(data$factor3_ncp_idx)
text
fit <- stan(file='stan_programs/nested_factors_residual.stan',
            data=data, seed=4838282, refresh=1000)

Divergences: our sworn enemy.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "5 of 4000 iterations ended with a divergence (0.125%)"
[1] "  Try running with larger adapt_delta to remove the divergences"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

We can't let them escape.

text
partition <- util$partition_div(fit)
div_samples <- partition[[1]]
nondiv_samples <- partition[[2]]

The population parameters for the first factor don't show any indication of problematic geometry.

text
par(mfrow=c(1, 1))

name_x <- "baseline"
name_y <- "delta_factor1_tau"

plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
     col=c_dark_trans, pch=16, main="Factor One Population",
     xlab=name_x, xlim=c(-8, 8),
     ylab=paste("log(", name_y, ")", sep=''), ylim=c(-7, 4))
points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
       col=c_green_trans, pch=16)

Nor do the population parameters for the hierarchical models nested within the Factor 1 levels. While there is some funnel-like behavior the divergences don't indicate that the sampler is having any problem exploring it.

text
par(mar=c(5, 5, 4, 1))

par(mfrow=c(1, 4))

for (l in 1:data$N_factor1_levels) {
  if (l %in% data$factor1_cp_idx) {
    cp_idx <- which(l == data$factor1_cp_idx)
    name_x <- paste("delta_factor1_cp[", cp_idx, "]", sep='')
  } else {
    ncp_idx <- which(l == data$factor1_ncp_idx)
    name_x <- paste("delta_factor1_ncp[", ncp_idx, "]", sep='')
  }
  name_y <- paste("delta_factor2_tau[", l, "]", sep='')

  title <- paste("Factor Two Population\nNested Within\nFactor One Level", l);

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-7, 4))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

The same is true for the population parameters for the hierarchical models nested within the Factor 2 levels.

text
par(mfrow=c(1, 4))

for (l in 1:data$N_factor2_levels) {
  if (l %in% data$factor2_cp_idx) {
    cp_idx <- which(l == data$factor2_cp_idx)
    name_x <- paste("delta_factor2_cp[", cp_idx, "]", sep='')
  } else {
    ncp_idx <- which(l == data$factor2_ncp_idx)
    name_x <- paste("delta_factor2_ncp[", ncp_idx, "]", sep='')
  }
  name_y <- paste("delta_factor3_tau[", l, "]", sep='')

  title <- paste("Factor Three Population\nNested Within\nFactor Two Level", l);

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-7, 4))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

We are then left to consider the correlation between the individual parameters and the population scales. Within the Factor 1 levels we see signs of an inverted funnel, and the concentration of the divergences towards the tip of the funnel suggests that these may be problematic to Stan's Hamiltonian Monte Carlo sampler.

text
par(mar=c(5, 5, 3, 1))

par(mfrow=c(1, 4))

for (l in 1:data$N_factor1_levels) {
  if (l %in% data$factor1_cp_idx) {
    cp_idx <- which(l == data$factor1_cp_idx)
    name_x <- paste("delta_factor1_cp[", cp_idx, "]", sep='')
  } else {
    ncp_idx <- which(l == data$factor1_ncp_idx)
    name_x <- paste("delta_factor1_ncp[", ncp_idx, "]", sep='')
  }
  name_y <- "delta_factor1_tau"

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=paste("l1 =", l),
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-7, 4))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

The individual parameters in the Factor 2 levels look somewhat suspicious, but less so that the those nested in the Factor 1 levels.

text
for (l1 in 1:data$N_factor1_levels) {
  nested_factor2_idx <- which(data$factor2_to_factor1 == l1)

  par(mfrow=c(1, 4))
 
  for (l2 in nested_factor2_idx) {
    if (l2 %in% data$factor2_cp_idx) {
      cp_idx <- which(l2 == data$factor2_cp_idx)
      name_x <- paste("delta_factor2_cp[", cp_idx, "]", sep='')
    } else {
      ncp_idx <- which(l2 == data$factor2_ncp_idx)
      name_x <- paste("delta_factor2_ncp[", ncp_idx, "]", sep='')
    }
    name_y <- paste("delta_factor2_tau[", l1, "]", sep='')

    plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
         col=c_dark_trans, pch=16,
         main=paste("l1 = ", l1, ", l2 = ", l2, sep=""),
         xlab=name_x, xlim=c(-8, 8),
         ylab=paste("log(", name_y, ")", sep=''), ylim=c(-7, 4))
    points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
           col=c_green_trans, pch=16)
  }
}

Within the Factor 3 levels the individual parameters are even better behaved.

text
for (l2 in 1:data$N_factor2_levels) {
  nested_factor3_idx <- which(data$factor3_to_factor2 == l2)

  par(mfrow=c(1, 4))

  for (l3 in nested_factor3_idx) {
    if (l3 %in% data$factor3_cp_idx) {
      cp_idx <- which(l3 == data$factor3_cp_idx)
      name_x <- paste("delta_factor3_cp[", cp_idx, "]", sep='')
    } else {
      ncp_idx <- which(l3 == data$factor3_ncp_idx)
      name_x <- paste("delta_factor3_ncp[", ncp_idx, "]", sep='')
    }
    name_y <- paste("delta_factor3_tau[", l2, "]", sep='')
 
    plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
         col=c_dark_trans, pch=16,
         main=paste("l2 = ", l2, ", l3 = ", l3, sep=""),
         xlab=name_x, xlim=c(-8, 8),
         ylab=paste("log(", name_y, ")", sep=''), ylim=c(-7, 4))
    points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
           col=c_green_trans, pch=16)
  }
 
  mtext(paste("Factor Three Hierarchy Nested Within Factor Two Level", l2), outer = TRUE)
}

The fact that the lower parameters in the nested hierarchy behave more poorly when non-centered is not surprising. As we go deeper into the nested hierarchy the data aggregates and more strongly informs the levels in the deeper factors relative to the levels in the shallower factor levels. In general the shallower factor levels will be more well-suited to non-centered parameterizations while the deeper factor levels will be more well-suited to centered parameterizations.

Let's start by centering just the individual parameters for the Factor 1 levels.

text
data$factor1_cp_idx <- 1:data$N_factor1_levels
data$L_factor1_cp <- length(data$factor1_cp_idx)

data$factor1_ncp_idx <- setdiff(1:data$N_factor1_levels, data$factor1_cp_idx)
data$L_factor1_ncp <- length(data$factor1_ncp_idx)

data$factor2_cp_idx <- vector()
data$L_factor2_cp <- length(data$factor2_cp_idx)

data$factor2_ncp_idx <- setdiff(1:data$N_factor2_levels, data$factor2_cp_idx)
data$L_factor2_ncp <- length(data$factor2_ncp_idx)

data$factor3_cp_idx <- vector()
data$L_factor3_cp <- length(data$factor3_cp_idx)

data$factor3_ncp_idx <- setdiff(1:data$N_factor3_levels, data$factor3_cp_idx)
data$L_factor3_ncp <- length(data$factor3_ncp_idx)
text
fit <- stan(file='stan_programs/nested_factors_residual.stan',
            data=data, seed=4838282, refresh=1000)

This seems to have done the trick as the divergences have vanished.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

Somewhat confident in the faithfulness of our computational fit we can start examining our posterior inferences. First we have the baseline parameter.

text
samples <- extract(fit)

par(mfrow=c(1, 1), mar=c(5, 1, 3, 1))

hist(samples$baseline, breaks=seq(0, 15, 0.1), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 11), xlab="Baseline", yaxt='n', ylab="")

Then the Factor 1 hierarchy.

text
layout(matrix(c(1, 1, 2), nrow=1))

L <- data$N_factor1_levels
idx <- rep(1:L, each=2)
x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:L, function(l)
                    quantile(samples$delta_factor1[,l], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

mean_tau <- mean(samples$delta_factor1_tau)

lb <- min(c(-2.25 * mean_tau, cred[1,]))
ub <- max(c(+2.25 * mean_tau, cred[9,]))

par(mar=c(5, 5, 3, 1))
plot(1, type="n", main="Factor One Contributions",
     xlim=c(0.5, L + 1.5), xlab="", xaxt="n",
     ylim=c(lb, ub), ylab="Marginal Posterior")

lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
for (l in 1:L)
  lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

axis(1, at=1:L, labels=sapply(1:L, function(l) paste("l1_", l, sep="")))

par(mar=c(5, 1, 3, 1))
u <- 1.25 * max(samples$delta_factor1_tau)
hist(samples$delta_factor1_tau, breaks=seq(0, u, u / 50), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
abline(v=mean_tau, col="gray80", lwd=2, lty=3)

Next the 25 Factor 2 hierarchies within the Factor 1 levels.

text
for (l1 in 1:data$N_factor1_levels) {
  layout(matrix(c(1, 1, 2), nrow=1))

  level_idx <- which(data$factor2_to_factor1 == l1)
  L <- length(level_idx)
  idx <- rep(1:L, each=2)
  x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

  probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
  cred <- sapply(level_idx, function(l)
                            quantile(samples$delta_factor2[,l], probs=probs))
  pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

  mean_tau <- mean(samples$delta_factor2_tau[,l1])

  lb <- min(c(-2.25 * mean_tau, cred[1,]))
  ub <- max(c(+2.25 * mean_tau,cred[9,]))

  title <- paste("Factor Two Contributions Nested\nWithin Factor One Level", l1)

  par(mar=c(5, 5, 3, 1))
  plot(1, type="n", main=title,
       xlim=c(0.5, L + 0.5), xlab="", xaxt="n",
       ylim=c(lb, ub), ylab="Marginal Posterior")

  lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

  polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
          col = c_light, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
          col = c_light_highlight, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
          col = c_mid, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
          col = c_mid_highlight, border = NA)
  for (l in 1:L)
    lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

  axis(1, at=1:L, sapply(level_idx, function(l) paste("l2_", l, sep="")))

  par(mar=c(5, 1, 3, 1))
  u <- 1.25 * max(samples$delta_factor2_tau[,l1])
  hist(samples$delta_factor2_tau[,l1], breaks=seq(0, u, u / 50), main="",
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
  abline(v=mean_tau, col="gray80", lwd=2, lty=3)
}

Finally we have the 125 Factor 3 hierarchies nested within the Factor 2 levels.

text
for (l2 in 1:data$N_factor2_levels) {
  layout(matrix(c(1, 1, 2), nrow=1))

  level_idx <- which(data$factor3_to_factor2 == l2)
  L <- length(level_idx)
  idx <- rep(1:L, each=2)
  x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

  probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
  cred <- sapply(level_idx, function(l)
    quantile(samples$delta_factor3[,l], probs=probs))
  pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

  mean_tau <- mean(samples$delta_factor3_tau[,l2])

  lb <- min(c(-2.25 * mean_tau, cred[1,]))
  ub <- max(c(+2.25 * mean_tau, cred[9,]))

  title <- paste("Factor Three Contributions Nested\nWithin Factor Two Level", l2)

  par(mar=c(5, 5, 3, 1))
  plot(1, type="n", main=title,
       xlim=c(0.5, L + 0.5), xlab="", xaxt="n",
       ylim=c(lb, ub), ylab="Marginal Posterior")

  lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

  polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
          col = c_light, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
          col = c_light_highlight, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
          col = c_mid, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
          col = c_mid_highlight, border = NA)
  for (l in 1:L)
    lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

  axis(1, at=1:L, sapply(level_idx, function(l) paste("l2_", l, sep="")))

  par(mar=c(5, 1, 3, 1))
  u <- 1.25 * max(samples$delta_factor3_tau[,l2])
  hist(samples$delta_factor3_tau[,l2], breaks=seq(0, u, u / 50), main="",
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
  abline(v=mean_tau, col="gray80", lwd=2, lty=3)
}

4.3 Overlapping Factor Models in Action

Finally let's consider the basic implementation of an overlapping multifactor model.

text
data <- read_rdump("data/overlapping_multifactor.data.R")

names(data)
text
[1] "y"                     "sigma"                 "main_factor_level_idx"
[4] "N"                     "N_main_factor_levels"  "N_main_factors"       

Here we have three overlapping factors. The first contains five levels, the second eight levels, and the third four levels.

text
par(mar=c(5, 5, 3, 5))

par(mfrow=c(3, 1))

main_factor_names <- c("Main Factor 1", "Main Factor 2", "Main Factor 3")
for(f in 1:3) {
  hist(data$main_factor_level_idx[f,],
       breaks=seq(0.5, data$N_main_factor_levels[f] + 0.5, 1),
       main="", col=c_dark, border=c_dark_highlight,
       xlim=c(0.5, data$N_main_factor_levels[f]+ 0.5), xlab=main_factor_names[f],
       ylim=c(0, 200), ylab="Number of\nObservations")
}

In order to build the most general multifactor model possible we'll also need the interaction levels derived from these three main factors. In particular we'll need three first-order interaction factors, one for each of the three pairs of main factors, and one second-order interaction factor.

Fortunately we can construct these interaction factors programmatically in Stan.

text
writeLines(readLines("stan_programs/construct_inter_idx_general.stan"))
text
data {
   // Number of observations
  int<lower=0> N;
  
  // Main factor indices
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
}

transformed data {
  int N1 = choose(N_main_factors, 2);
  int N2 = choose(N_main_factors, 3);
  
  if (N_main_factors < 2)
    reject("Need at least 2 main factors to construct first-order interactions")
  if (N_main_factors < 3)
    reject("Need at least 3 main factors to construct second-order interactions")
}

generated quantities {
  // First-order interaction indices
  int N_inter1_factors = N1;          // Number of interaction factors
  int N_inter1_factor_levels[N1];     // Number of levels within each interaction factor
  int inter1_factor1_idx[N1];         // First main factor in interaction
  int inter1_factor2_idx[N1];         // Second main factor in interaction
  int inter1_factor_level_idx[N1, N]; // Interaction level assignments for each observation
  
  // Second-order interaction indices
  int N_inter2_factors = N2;          // Number of interaction factors
  int N_inter2_factor_levels[N2];     // Number of levels within each interaction factor
  int inter2_factor1_idx[N2];         // First main factor in interaction
  int inter2_factor2_idx[N2];         // Second main factor in interaction
  int inter2_factor3_idx[N2];         // Third main factor in interaction
  int inter2_factor_level_idx[N2, N]; // Interaction level assignments for each observation
  
  // Construct first-order interactions
  for (i in 1:N_main_factors) {
    // Number of first-order interactions with first index less than i
    int N_i = (i - 1) * N_main_factors - (i - 1) * i / 2;
    
    for (j in (i + 1):N_main_factors) {
      int idx = N_i + j - i;
      N_inter1_factor_levels[idx] = N_main_factor_levels[i] * N_main_factor_levels[j];
      inter1_factor1_idx[idx] = i;
      inter1_factor2_idx[idx] = j;
    }
  }

  // Construct second-order interactions
  for (i in 1:N_main_factors) {
    // Number of second-order interactions with first index less than i
    int N_i =   (i - 1) * N_main_factors * (N_main_factors - 1) / 2 
              - N_main_factors * (i - 1) * i / 2
              + (i - 1) * i * (i + 1) / 6;
              
    for (j in (i + 1):N_main_factors) {
      // Number of second-order interactions with first index equal to i
      // and second index less than j
      int N_j =   (j - 1) * N_main_factors - (j - 1) * j / 2 
                - (N_main_factors * i - i * (i + 1) / 2); 
      
      for (k in (j + 1):N_main_factors) {
        int idx = N_i + N_j + (k - j);
        N_inter2_factor_levels[idx] =   N_main_factor_levels[i] 
                                      * N_main_factor_levels[j] 
                                      * N_main_factor_levels[k];
        inter2_factor1_idx[idx] = i;
        inter2_factor2_idx[idx] = j;
        inter2_factor3_idx[idx] = k;
      }
    }
  }
  
  for (n in 1:N) {
    // Assign first-order interactions
    for (i in 1:N_main_factors) {
      int N_i = (i - 1) * N_main_factors - (i - 1) * i / 2;
                
      for (j in (i + 1):N_main_factors) {
        int idx = N_i + j - i;
        inter1_factor_level_idx[idx, n] 
          =   (main_factor_level_idx[i, n] - 1) * N_main_factor_levels[j]
            +  main_factor_level_idx[j, n];
      }
    }
      
    // Assign second-order interactions
    for (i in 1:N_main_factors) {
      int N_i =   (i - 1) * N_main_factors * (N_main_factors - 1) / 2 
                - N_main_factors * (i - 1) * i / 2
                + (i - 1) * i * (i + 1) / 6;
                
      for (j in (i + 1):N_main_factors) {
        int N_j =   (j - 1) * N_main_factors - (j - 1) * j / 2 
                  - (N_main_factors * i - i * (i + 1) / 2); 
        
        for (k in (j + 1):N_main_factors) {
          int idx = N_i + N_j + (k - j);
          inter2_factor_level_idx[idx, n] 
            =   (main_factor_level_idx[i, n] - 1) * N_main_factor_levels[j] * N_main_factor_levels[k]
              + (main_factor_level_idx[j, n] - 1) * N_main_factor_levels[k]
              +  main_factor_level_idx[k, n];
        }
      }
    }
  }
}
text
inter <- stan(file='stan_programs/construct_inter_idx_general.stan',
             data=data, iter=1, warmup=0, chains=1,
             algorithm="Fixed_param")
text
DIAGNOSTIC(S) FROM PARSER:
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * N_main_factors * N_main_factors - 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: N_main_factors * i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i * i + 1 / 6
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: j - 1 * j / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i * i + 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * N_main_factors * N_main_factors - 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: N_main_factors * i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i * i + 1 / 6
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: j - 1 * j / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i * i + 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.


SAMPLING FOR MODEL 'construct_inter_idx_general' NOW (CHAIN 1).
Chain 1: Iteration: 1 / 1 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0 seconds (Warm-up)
Chain 1:                7.1e-05 seconds (Sampling)
Chain 1:                7.1e-05 seconds (Total)
Chain 1: 
text
inter_output <- extract(inter)

data$N_inter1_factors <- inter_output$N_inter1_factors[1]
data$N_inter1_factor_levels <- array(inter_output$N_inter1_factor_levels[1,])
data$inter1_factor1_idx <- inter_output$inter1_factor1_idx[1,]
data$inter1_factor2_idx <- inter_output$inter1_factor2_idx[1,]
data$inter1_factor_level_idx <- inter_output$inter1_factor_level_idx[1,,]
dim(data$inter1_factor_level_idx) <- c(data$N_inter1_factors, data$N)

data$N_inter2_factors <- inter_output$N_inter2_factors[1]
data$N_inter2_factor_levels <- array(inter_output$N_inter2_factor_levels[1,])
data$inter2_factor1_idx <- inter_output$inter2_factor1_idx[1,]
data$inter2_factor2_idx <- inter_output$inter2_factor2_idx[1,]
data$inter2_factor3_idx <- inter_output$inter2_factor3_idx[1,]
data$inter2_factor_level_idx <- inter_output$inter2_factor_level_idx[1,,]
dim(data$inter2_factor_level_idx) <- c(data$N_inter2_factors, data$N)

The first-order interaction factors feature many more levels and, consequently, each of those levels are less populated than the main factor levels.

text
par(mfrow=c(3, 1))

inter1_factor_names <- c("Interaction Factor 12",
                         "Interaction Factor 13",
                         "Interaction Factor 23")
for(f in 1:3) {
  hist(data$inter1_factor_level_idx[f,],
       breaks=seq(0.5, data$N_inter1_factor_levels[f] + 0.5, 1),
       main="", col=c_dark, border=c_dark_highlight,
       xlim=c(0.5, data$N_inter1_factor_levels[f]+ 0.5), xlab=inter1_factor_names[f],
       ylim=c(0, 60), ylab="Number of\nObservations")
}

This is only amplified in the second-order interaction factor. Moreover the deviations from uniformity in the main factors level occupancies are amplified, and a few second-order interaction levels are significantly more populated than the others.

text
par(mfrow=c(1, 1))

inter2_factor_names <- c("Interaction Factor 123")
hist(data$inter2_factor_level_idx[1,],
     breaks=seq(0.5, data$N_inter2_factor_levels[1] + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_inter2_factor_levels[1]+ 0.5), xlab=inter2_factor_names[1],
     ylim=c(0, 25), ylab="Number of Observations")

Knowing that we have only three main factors we could code up all of the contributions from the full residual expansion by hand.

text
writeLines(readLines('stan_programs/overlapping_factors_hand.stan'))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability
  
  // Factor information
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N];

  // Second-order factor interaction contributions logistics
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
  int<lower=1> inter2_factor_level_idx[N_inter2_factors, N];
}

parameters {  
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // First-order contributions (Main Effects)
  vector[N_main_factor_levels[1]] delta1;
  real<lower=0> delta1_tau;
  
  vector[N_main_factor_levels[2]] delta2;
  real<lower=0> delta2_tau;
  
  vector[N_main_factor_levels[3]] delta3;
  real<lower=0> delta3_tau;
  
  // Second-order contributions (First-order interactions)
  vector[N_inter1_factor_levels[1]] delta12;
  real<lower=0> delta12_tau;
  
  vector[N_inter1_factor_levels[2]] delta13;
  real<lower=0> delta13_tau;
  
  vector[N_inter1_factor_levels[3]] delta23;
  real<lower=0> delta23_tau;
  
  // Third-order contributions (Second-order interactions)
  vector[N_inter2_factor_levels[1]] delta123;
  real<lower=0> delta123_tau;
}

model {
  vector[N] theta =  baseline
                   + delta1[main_factor_level_idx[1]]
                   + delta2[main_factor_level_idx[2]]
                   + delta3[main_factor_level_idx[3]]
                   + delta12[inter1_factor_level_idx[1]]
                   + delta13[inter1_factor_level_idx[2]]
                   + delta23[inter1_factor_level_idx[3]]
                   + delta123[inter2_factor_level_idx[1]];
    
  baseline ~ normal(0, 8);
  
  delta1 ~ normal(0, delta1_tau);
  delta1_tau ~ normal(0, 4);
  
  delta2 ~ normal(0, delta2_tau);
  delta2_tau ~ normal(0, 4);
  
  delta3 ~ normal(0, delta3_tau);
  delta3_tau ~ normal(0, 4);
  
  delta12 ~ normal(0, delta12_tau);
  delta12_tau ~ normal(0, 2);
  
  delta23 ~ normal(0, delta23_tau);
  delta23_tau ~ normal(0, 2);
  
  delta13 ~ normal(0, delta13_tau);
  delta13_tau ~ normal(0, 2);
  
  delta123 ~ normal(0, delta123_tau);
  delta123_tau ~ normal(0, 1);

  y ~ normal(theta, sigma);
}

This brute force approach, however, doesn't scale well when we have more than three factors. To allow for an arbitrary number of factors we can pack the factor levels at each order into single arrays. Note that this packing is equivalent to the direct sum introduced in Section 3.4!

text
writeLines(readLines("stan_programs/pack_idx.stan"))
text
data {
  // Main factor indices
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  
  // First-order interaction indices
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  
  // Second-order factor indices
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
}

transformed data {
  int N_all_main = sum(N_main_factor_levels);
  int N_all_inter1 = sum(N_inter1_factor_levels);
  int N_all_inter2 = sum(N_inter2_factor_levels);
}

generated quantities {
  // Flattened indices
  int<lower=0> N_all_main_factor_levels = N_all_main;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main];
  int<lower=1, upper=N_all_main> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main> main_factor_end_idx[N_main_factors];
  
  int<lower=0> N_all_inter1_factor_levels = N_all_inter1;
  int<lower=1, upper=N_inter1_factors> packed_inter1_factor_idx[N_all_inter1];
  int<lower=1, upper=N_all_inter1> inter1_factor_start_idx[N_inter1_factors];
  int<lower=1, upper=N_all_inter1> inter1_factor_end_idx[N_inter1_factors];
  
  int<lower=0> N_all_inter2_factor_levels = N_all_inter2;
  int<lower=1, upper=N_inter2_factors> packed_inter2_factor_idx[N_all_inter2];
  int<lower=1, upper=N_all_inter2> inter2_factor_start_idx[N_inter2_factors];
  int<lower=1, upper=N_all_inter2> inter2_factor_end_idx[N_inter2_factors];

  {
    int cumsum = 0;
    for (f in 1:N_main_factors) {
      main_factor_start_idx[f] = cumsum + 1;
      main_factor_end_idx[f] = cumsum + N_main_factor_levels[f];
      packed_main_factor_idx[main_factor_start_idx[f]:main_factor_end_idx[f]] 
        = rep_array(f, N_main_factor_levels[f]);
      cumsum += N_main_factor_levels[f];
    }
    
    cumsum = 0;
    for (f in 1:N_inter1_factors) {
      inter1_factor_start_idx[f] = cumsum + 1;
      inter1_factor_end_idx[f] = cumsum + N_inter1_factor_levels[f];
      packed_inter1_factor_idx[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]] 
        = rep_array(f, N_inter1_factor_levels[f]);
      cumsum += N_inter1_factor_levels[f];
    }
    
    cumsum = 0;
    for (f in 1:N_inter2_factors) {
      inter2_factor_start_idx[f] = cumsum + 1;
      inter2_factor_end_idx[f] = cumsum + N_inter2_factor_levels[f];
      packed_inter2_factor_idx[inter2_factor_start_idx[f]:inter2_factor_end_idx[f]] 
        = rep_array(f, N_inter2_factor_levels[f]);
      cumsum += N_inter2_factor_levels[f];
    }
  }
}
text
pack <- stan(file='stan_programs/pack_idx.stan', data=data,
             iter=1, warmup=0, chains=1, algorithm="Fixed_param")
text
SAMPLING FOR MODEL 'pack_idx' NOW (CHAIN 1).
Chain 1: Iteration: 1 / 1 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0 seconds (Warm-up)
Chain 1:                2.9e-05 seconds (Sampling)
Chain 1:                2.9e-05 seconds (Total)
Chain 1: 
text
pack_output <- extract(pack)

data$N_all_main_factor_levels <- pack_output$N_all_main_factor_levels[1]
data$packed_main_factor_idx <- array(pack_output$packed_main_factor_idx[1,])
data$main_factor_start_idx <- array(pack_output$main_factor_start_idx[1,])
data$main_factor_end_idx <- array(pack_output$main_factor_end_idx[1,])

data$N_all_inter1_factor_levels <- pack_output$N_all_inter1_factor_levels[1]
data$packed_inter1_factor_idx <- array(pack_output$packed_inter1_factor_idx[1,])
data$inter1_factor_start_idx <- array(pack_output$inter1_factor_start_idx[1,])
data$inter1_factor_end_idx <- array(pack_output$inter1_factor_end_idx[1,])

data$N_all_inter2_factor_levels <- pack_output$N_all_inter2_factor_levels[1]
data$packed_inter2_factor_idx <- array(pack_output$packed_inter2_factor_idx[1,])
data$inter2_factor_start_idx <- array(pack_output$inter2_factor_start_idx[1,])
data$inter2_factor_end_idx <- array(pack_output$inter2_factor_end_idx[1,])

This allows us to build a Stan program that can accommodate any number of main factors. For example we could implement a monolithically centered parameterization.

text
writeLines(readLines('stan_programs/overlapping_factors_cp.stan'))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability
  
  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N];
  
  int<lower=0> N_all_inter1_factor_levels;
  int<lower=1, upper=N_inter1_factors> packed_inter1_factor_idx[N_all_inter1_factor_levels];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_start_idx[N_inter1_factors];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_end_idx[N_inter1_factors];

  // Second-order factor interaction contributions logistics
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
  int<lower=1> inter2_factor_level_idx[N_inter2_factors, N];
  
  int<lower=0> N_all_inter2_factor_levels;
  int<lower=1, upper=N_inter2_factors> packed_inter2_factor_idx[N_all_inter2_factor_levels];
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_factor_start_idx[N_inter2_factors];
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_factor_end_idx[N_inter2_factors];
}

parameters {  
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[N_all_main_factor_levels] packed_delta_main; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // First-order factor interaction contributions
  vector[N_all_inter1_factor_levels] packed_delta_inter1; 
  vector<lower=0>[N_inter1_factors] delta_inter1_tau;
  
  // Second-order factor interaction contributions
  vector[N_all_inter2_factor_levels] packed_delta_inter2;
  vector<lower=0>[N_inter2_factors] delta_inter2_tau;
}

model {
  // Baseline contribution
  vector[N] theta =  rep_vector(baseline, N);
  baseline ~ normal(0, 8);
  
  // Main factor contributions
  for (f in 1:N_main_factors) {
    // Extract level parameters of fth main factor
    vector[N_main_factor_levels[f]] delta_main
      = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      
    // Add contribution to total heterogeneity
    theta += delta_main[main_factor_level_idx[f]];
  }
  
  // Main factor hierarchial models
  packed_delta_main ~ normal(0, delta_main_tau[packed_main_factor_idx]);
  delta_main_tau ~ normal(0, 4);

  // First-order factor interaction contributions
  for (f in 1:N_inter1_factors) {
    // Extract level parameters of fth first-order interaction factor
    vector[N_inter1_factor_levels[f]] delta_inter1
      = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
      
    // Add contribution to total heterogeneity
    theta += delta_inter1[inter1_factor_level_idx[f]];
  }

  // First-order interaction factor hierarchial models
  packed_delta_inter1 ~ normal(0, delta_inter1_tau[packed_inter1_factor_idx]);
  delta_inter1_tau ~ normal(0, 2);
  
  // Second-order factor interaction contributions
  for (f in 1:N_inter2_factors) {
    // Extract level parameters of fth second-order interaction factor
    vector[N_inter2_factor_levels[f]] delta_inter2
      = packed_delta_inter2[inter2_factor_start_idx[f]:inter2_factor_end_idx[f]];
      
    // Add contribution to total heterogeneity
    theta += delta_inter2[inter2_factor_level_idx[f]];
  }
  
  // Second-order interaction factor hierarchial models
  packed_delta_inter2 ~ normal(0, delta_inter2_tau[packed_inter2_factor_idx]);
  delta_inter2_tau ~ normal(0, 1);

  // Observational model
  y ~ normal(theta, sigma);
}

Knowing how fragile the monolithically centered parameterization is, however, we really want a Stan program where we can configure the parameterization of all of the hierarchical parameters across all orders of the residual expansion.

text
writeLines(readLines('stan_programs/overlapping_factors_mixed.stan'))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability
  
  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N];
  
  int<lower=0> N_all_inter1_factor_levels;
  int<lower=1, upper=N_inter1_factors> packed_inter1_factor_idx[N_all_inter1_factor_levels];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_start_idx[N_inter1_factors];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_end_idx[N_inter1_factors];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_ncp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_ncp_idx[L_inter1_ncp];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_cp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_cp_idx[L_inter1_cp];

  // Second-order factor interaction contributions logistics
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
  int<lower=1> inter2_factor_level_idx[N_inter2_factors, N];
  
  int<lower=0> N_all_inter2_factor_levels;
  int<lower=1, upper=N_inter2_factors> packed_inter2_factor_idx[N_all_inter2_factor_levels];
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_factor_start_idx[N_inter2_factors];
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_factor_end_idx[N_inter2_factors];
  
  int<lower=0, upper=N_all_inter2_factor_levels> L_inter2_ncp;
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_ncp_idx[L_inter2_ncp];
  
  int<lower=0, upper=N_all_inter2_factor_levels> L_inter2_cp;
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_cp_idx[L_inter2_cp];
}

parameters {  
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // First-order factor interaction contributions
  vector[L_inter1_ncp] packed_delta_inter1_ncp;
  vector[L_inter1_cp] packed_delta_inter1_cp; 
  vector<lower=0>[N_inter1_factors] delta_inter1_tau;
  
  // Second-order factor interaction contributions
  vector[L_inter2_ncp] packed_delta_inter2_ncp;
  vector[L_inter2_cp] packed_delta_inter2_cp; 
  vector<lower=0>[N_inter2_factors] delta_inter2_tau;
}

transformed parameters {
  vector[N_all_main_factor_levels] packed_delta_main;
  vector[N_all_inter1_factor_levels] packed_delta_inter1;
  vector[N_all_inter2_factor_levels] packed_delta_inter2;
  
  packed_delta_main[main_ncp_idx] 
    = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
  packed_delta_main[main_cp_idx] = packed_delta_main_cp;
  
  packed_delta_inter1[inter1_ncp_idx] 
    = delta_inter1_tau[packed_inter1_factor_idx[inter1_ncp_idx]] .* packed_delta_inter1_ncp;
  packed_delta_inter1[inter1_cp_idx] = packed_delta_inter1_cp;
  
  packed_delta_inter2[inter2_ncp_idx] 
    = delta_inter2_tau[packed_inter2_factor_idx[inter2_ncp_idx]] .* packed_delta_inter2_ncp;
  packed_delta_inter2[inter2_cp_idx] = packed_delta_inter2_cp;
}

model {
  // Baseline contribution
  vector[N] theta =  rep_vector(baseline, N);
  baseline ~ normal(0, 8);
  
  // Main factor contributions
  for (f in 1:N_main_factors) {
    // Extract level parameters of fth main factor
    vector[N_main_factor_levels[f]] delta_main
      = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
    
    // Add contribution to total heterogeneity
    theta += delta_main[main_factor_level_idx[f]];
  }
  
  // Main factor hierarchial models
  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 4);

  // First-order factor interaction contributions
  for (f in 1:N_inter1_factors) {
    // Extract level parameters of fth first-order interaction factor
    vector[N_inter1_factor_levels[f]] delta_inter1
      = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
      
    // Add contribution to total heterogeneity
    theta += delta_inter1[inter1_factor_level_idx[f]];
  }
  
  // First-order interaction factor hierarchial models
  packed_delta_inter1_ncp ~ normal(0, 1);
  packed_delta_inter1_cp ~ normal(0, delta_inter1_tau[packed_inter1_factor_idx[inter1_cp_idx]]);
  delta_inter1_tau ~ normal(0, 2);
  
  // Second-order factor interaction contributions
  for (f in 1:N_inter2_factors) {
    // Extract level parameters of fth second-order interaction factor
    vector[N_inter2_factor_levels[f]] delta_inter2
      = packed_delta_inter2[inter2_factor_start_idx[f]:inter2_factor_end_idx[f]];
      
    // Add contribution to total heterogeneity
    theta += delta_inter2[inter2_factor_level_idx[f]];
  }
  
  // Second-order interaction factor hierarchial models
  packed_delta_inter2_ncp ~ normal(0, 1);
  packed_delta_inter2_cp ~ normal(0, delta_inter2_tau[packed_inter2_factor_idx[inter2_cp_idx]]);
  delta_inter2_tau ~ normal(0, 1);

  // Observational model
  y ~ normal(theta, sigma);
}

That said, let's not get ahead of ourselves. Instead of trying to fit the entire residual expansion at once let's incorporate the contributions from each order incrementally.

To critique each iteration of the overlapping multifactor model we'll use a regularized FF statistic that is common in frequentist analysis of variance estimation. In each sufficiently occupied factor level, where a sufficiently occupied level requires at least two observations, we'll compare the empirical mean of the empirical variances, or the within group variation, to the empirical variance of the empirical means, or the between group variation. Because the factor heterogeneity should manifest directly in the mean of the observations here this regularized FF statistic should be relatively sensitive to excess heterogeneity.

text
writeLines(readLines('stan_programs/compute_f_stat.stan'))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N; // Number of observations
  vector[N] y;    // Observations

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N];

  // Second-order factor interaction contributions logistics
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
  int<lower=1> inter2_factor_level_idx[N_inter2_factors, N];
}

generated quantities {
  real F_main_obs[N_main_factors];
  real F_inter1_obs[N_inter1_factors];
  real F_inter2_obs[N_inter2_factors];
  
  for (f in 1:N_main_factors)
    F_main_obs[f] = F_stat(y, N, main_factor_level_idx[f], N_main_factor_levels[f]);
  
  for (f in 1:N_inter1_factors)
    F_inter1_obs[f] = F_stat(y, N, inter1_factor_level_idx[f], N_inter1_factor_levels[f]);

  for (f in 1:N_inter2_factors)
    F_inter2_obs[f] = F_stat(y, N, inter2_factor_level_idx[f], N_inter2_factor_levels[f]);
}
text
fit <- stan(file='stan_programs/compute_f_stat.stan', data=data, seed=93585393,
             iter=1, warmup=0, chains=1, algorithm="Fixed_param")
text
SAMPLING FOR MODEL 'compute_f_stat' NOW (CHAIN 1).
Chain 1: Iteration: 1 / 1 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0 seconds (Warm-up)
Chain 1:                9e-05 seconds (Sampling)
Chain 1:                9e-05 seconds (Total)
Chain 1: 
text
F_main_obs <- extract(fit)$F_main_obs[1,]
F_inter1_obs <- extract(fit)$F_inter1_obs[1,]
F_inter2_obs <- extract(fit)$F_inter2_obs[1,]

With the observed summary statistics evaluated and saved we can start working through the residual expansion. We begin with a baseline only model.

text
writeLines(readLines("stan_programs/overlapping_factors_ver0.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
}

parameters {  
  // Zeroth-order contribution (Baseline)
  real baseline;
}

model {
  // Baseline contribution
  vector[N] theta =  rep_vector(baseline, N);
  
  baseline ~ normal(0, 8);

  // Observational model
  y ~ normal(theta, sigma);
}

generated quantities {
  real y_post_pred[N] = normal_rng(rep_vector(baseline, N), sigma);
  
  real F_main_post_pred[N_main_factors];
  
  for (f in 1:N_main_factors) {
    F_main_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                 main_factor_level_idx[f], 
                                 N_main_factor_levels[f]);
  }
}
text
fit <- stan(file='stan_programs/overlapping_factors_ver0.stan',
            data=data, seed=4838282, refresh=2000)

There are no indications of computational problems.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

The posterior retrodictive check based on the FF statistic, however, suggests that the baseline model is poorly capturing the heterogeneity across the main factor levels observed in the data.

text
samples <- extract(fit)

par(mfrow=c(1, 3))
par(mar=c(5, 5, 3, 1))

lims <- c(100, 600, 100)
deltas <- c(2, 10, 2)

for (f in 1:3) {
  hist(samples$F_main_post_pred[,f], breaks=seq(0, 900, deltas[f]),
       main=main_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_main_obs[f], col="black", lty=1, lw=2)
}

To do better we incorporate the contributions from the main factor levels.

text
writeLines(readLines("stan_programs/overlapping_factors_ver1.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N];
}

parameters {  
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
}

transformed parameters {
  vector[N_all_main_factor_levels] packed_delta_main;
  
  packed_delta_main[main_ncp_idx] 
    = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
  packed_delta_main[main_cp_idx] = packed_delta_main_cp;
}

model {
  // Baseline contribution
  vector[N] theta =  rep_vector(baseline, N);
  
  baseline ~ normal(0, 8);
  
  // Main factor contributions
  for (f in 1:N_main_factors) {
    vector[N_main_factor_levels[f]] delta_main
      = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
    theta += delta_main[main_factor_level_idx[f]];
  }

  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 4);
  
  // Observational model
  y ~ normal(theta, sigma);
}

generated quantities {
  real y_post_pred[N];
  
  real F_main_post_pred[N_main_factors];
  real F_inter1_post_pred[N_inter1_factors];
  
  {
    vector[N] theta =  rep_vector(baseline, N);

    for (f in 1:N_main_factors) {
      vector[N_main_factor_levels[f]] delta_main
        = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      theta += delta_main[main_factor_level_idx[f]];
    }
    
    y_post_pred = normal_rng(theta, sigma);
  
    for (f in 1:N_main_factors) {
      F_main_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                   main_factor_level_idx[f], 
                                   N_main_factor_levels[f]);
    }
    
    for (f in 1:N_inter1_factors) {
      F_inter1_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                     inter1_factor_level_idx[f], 
                                     N_inter1_factor_levels[f]);
    }
  }
}

We start with a monolithically non-centered parameterization.

text
data$main_cp_idx <- vector()
data$L_main_cp <- length(data$main_cp_idx)

data$main_ncp_idx <- setdiff(1:data$N_all_main_factor_levels, data$main_cp_idx)
data$L_main_ncp <- length(data$main_ncp_idx)
text
fit <- stan(file='stan_programs/overlapping_factors_ver1.stan',
            data=data, seed=4838282, refresh=2000)

Fortunately there don't seem to be any computational problems.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

The posterior retrodictive checks, however, look unsatisfying. Our model is unable to capture not only the heterogeneity across the first-order interaction levels but also the heterogeneity across the Main Factor 2 levels, even though we've already added a hierarchy for this factor!

text
samples <- extract(fit)

par(mfrow=c(2, 3))

lims <- c(100, 900, 200)
deltas <- c(1, 10, 2)

for (f in 1:3) {
  hist(samples$F_main_post_pred[,f], breaks=seq(0, 900, deltas[f]),
       main=main_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_main_obs[f], col="black", lty=1, lw=2)
}

lims <- c(2000, 250, 2500)
deltas <- c(20, 5, 20)

for (f in 1:3) {
  hist(samples$F_inter1_post_pred[,f], breaks=seq(0, 2500, deltas[f]),
       main=inter1_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_inter1_obs[f], col="black", lty=1, lw=2)
}

Poor modeling of the heterogeneity across main factor levels despite modeling those levels is a common indicator of strong interaction heterogeneity, further supporting the need to incorporate the first-order interaction factors.

text
writeLines(readLines("stan_programs/overlapping_factors_ver2.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N];
  
  int<lower=0> N_all_inter1_factor_levels;
  int<lower=1, upper=N_inter1_factors> packed_inter1_factor_idx[N_all_inter1_factor_levels];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_start_idx[N_inter1_factors];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_end_idx[N_inter1_factors];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_ncp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_ncp_idx[L_inter1_ncp];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_cp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_cp_idx[L_inter1_cp];

  // Second-order factor interaction contributions logistics
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
  int<lower=1> inter2_factor_level_idx[N_inter2_factors, N];
}

parameters {  
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // First-order factor interaction contributions
  vector[L_inter1_ncp] packed_delta_inter1_ncp;
  vector[L_inter1_cp] packed_delta_inter1_cp; 
  vector<lower=0>[N_inter1_factors] delta_inter1_tau;
}

transformed parameters {
  vector[N_all_main_factor_levels] packed_delta_main;
  vector[N_all_inter1_factor_levels] packed_delta_inter1;
    
  packed_delta_main[main_ncp_idx] 
    = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
  packed_delta_main[main_cp_idx] = packed_delta_main_cp;
  
  packed_delta_inter1[inter1_ncp_idx] 
    = delta_inter1_tau[packed_inter1_factor_idx[inter1_ncp_idx]] .* packed_delta_inter1_ncp;
  packed_delta_inter1[inter1_cp_idx] = packed_delta_inter1_cp;
}

model {
  // Baseline contribution
  vector[N] theta =  rep_vector(baseline, N);
  
  baseline ~ normal(0, 8);
  
  // Main factor contributions
  for (f in 1:N_main_factors) {
    vector[N_main_factor_levels[f]] delta_main
      = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
    theta += delta_main[main_factor_level_idx[f]];
  }
  
  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 4);
  
  // First-order factor interaction contributions
  for (f in 1:N_inter1_factors) {
    vector[N_inter1_factor_levels[f]] delta_inter1
      = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
    theta += delta_inter1[inter1_factor_level_idx[f]];
  }
  
  packed_delta_inter1_ncp ~ normal(0, 1);
  packed_delta_inter1_cp ~ normal(0, delta_inter1_tau[packed_inter1_factor_idx[inter1_cp_idx]]);
  delta_inter1_tau ~ normal(0, 2);

  // Observational model
  y ~ normal(theta, sigma);
}

generated quantities {
  real y_post_pred[N];
  
  real F_main_post_pred[N_main_factors];
  real F_inter1_post_pred[N_inter1_factors];
  real F_inter2_post_pred[N_inter2_factors];
  
  {
    vector[N] theta =  rep_vector(baseline, N);

    for (f in 1:N_main_factors) {
      vector[N_main_factor_levels[f]] delta_main
        = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      theta += delta_main[main_factor_level_idx[f]];
    }
    
    for (f in 1:N_inter1_factors) {
      vector[N_inter1_factor_levels[f]] delta_inter1
        = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
      theta += delta_inter1[inter1_factor_level_idx[f]];
    }
    
    y_post_pred = normal_rng(theta, sigma);
  
    for (f in 1:N_main_factors) {
      F_main_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                   main_factor_level_idx[f], 
                                   N_main_factor_levels[f]);
    }
    
    for (f in 1:N_inter1_factors) {
      F_inter1_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                     inter1_factor_level_idx[f], 
                                     N_inter1_factor_levels[f]);
    }
    
    for (f in 1:N_inter2_factors) {
      F_inter2_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                     inter2_factor_level_idx[f], 
                                     N_inter2_factor_levels[f]);
    }
  }
}

Again we begin with a non-centered parameterization.

text
data$inter1_cp_idx <- vector()
data$L_inter1_cp <- length(data$inter1_cp_idx)

data$inter1_ncp_idx <- setdiff(1:data$N_all_inter1_factor_levels,
                                    data$inter1_cp_idx)
data$L_inter1_ncp <- length(data$inter1_ncp_idx)
text
fit <- stan(file='stan_programs/overlapping_factors_ver2.stan',
            data=data, seed=4838282, refresh=2000)

Diagnostics are clean.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

The posterior retrodictive checks for the main factors and the first-order interaction factors all look much better, and the check for the second-order interaction factor suggests that we can't resolve any higher-order contributions.

text
samples <- extract(fit)

par(mfrow=c(3, 3))

lims <- c(100, 700, 200)
deltas <- c(1, 10, 2)

for (f in 1:3) {
  hist(samples$F_main_post_pred[,f], breaks=seq(0, 900, deltas[f]),
       main=main_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_main_obs[f], col="black", lty=1, lw=2)
}

lims <- c(1500, 250, 2000)
deltas <- c(20, 5, 20)

for (f in 1:3) {
  hist(samples$F_inter1_post_pred[,f], breaks=seq(0, 2500, deltas[f]),
       main=inter1_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_inter1_obs[f], col="black", lty=1, lw=2)
}

plot.new()
for (f in 1:1) {
  hist(samples$F_inter2_post_pred[,f], breaks=seq(4000, 20000, 100),
       main=inter2_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(5000, 16000), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_inter2_obs[f], col="black", lty=1, lw=2)
}

To be safe, however, let's include the second-order interactions and investigate the corresponding inferences.

text
writeLines(readLines("stan_programs/overlapping_factors_ver3.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N];
  
  int<lower=0> N_all_inter1_factor_levels;
  int<lower=1, upper=N_inter1_factors> packed_inter1_factor_idx[N_all_inter1_factor_levels];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_start_idx[N_inter1_factors];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_end_idx[N_inter1_factors];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_ncp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_ncp_idx[L_inter1_ncp];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_cp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_cp_idx[L_inter1_cp];

  // Second-order factor interaction contributions logistics
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
  int<lower=1> inter2_factor_level_idx[N_inter2_factors, N];
  
  int<lower=0> N_all_inter2_factor_levels;
  int<lower=1, upper=N_inter2_factors> packed_inter2_factor_idx[N_all_inter2_factor_levels];
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_factor_start_idx[N_inter2_factors];
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_factor_end_idx[N_inter2_factors];
  
  int<lower=0, upper=N_all_inter2_factor_levels> L_inter2_ncp;
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_ncp_idx[L_inter2_ncp];
  
  int<lower=0, upper=N_all_inter2_factor_levels> L_inter2_cp;
  int<lower=1, upper=N_all_inter2_factor_levels> inter2_cp_idx[L_inter2_cp];
}

parameters {  
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // First-order factor interaction contributions
  vector[L_inter1_ncp] packed_delta_inter1_ncp;
  vector[L_inter1_cp] packed_delta_inter1_cp; 
  vector<lower=0>[N_inter1_factors] delta_inter1_tau;
  
  // Second-order factor interaction contributions
  vector[L_inter2_ncp] packed_delta_inter2_ncp;
  vector[L_inter2_cp] packed_delta_inter2_cp; 
  vector<lower=0>[N_inter2_factors] delta_inter2_tau;
}

transformed parameters {
  vector[N_all_main_factor_levels] packed_delta_main;
  vector[N_all_inter1_factor_levels] packed_delta_inter1;
  vector[N_all_inter2_factor_levels] packed_delta_inter2;
    
  packed_delta_main[main_ncp_idx] 
    = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
  packed_delta_main[main_cp_idx] = packed_delta_main_cp;
  
  packed_delta_inter1[inter1_ncp_idx] 
    = delta_inter1_tau[packed_inter1_factor_idx[inter1_ncp_idx]] .* packed_delta_inter1_ncp;
  packed_delta_inter1[inter1_cp_idx] = packed_delta_inter1_cp;
  
  packed_delta_inter2[inter2_ncp_idx] 
    = delta_inter2_tau[packed_inter2_factor_idx[inter2_ncp_idx]] .* packed_delta_inter2_ncp;
  packed_delta_inter2[inter2_cp_idx] = packed_delta_inter2_cp;
}

model {
  // Baseline contribution
  vector[N] theta =  rep_vector(baseline, N);
  
  baseline ~ normal(0, 8);
  
  // Main factor contributions
  for (f in 1:N_main_factors) {
    vector[N_main_factor_levels[f]] delta_main
      = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
    theta += delta_main[main_factor_level_idx[f]];
  }
  
  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 4);
  
  // First-order factor interaction contributions
  for (f in 1:N_inter1_factors) {
    vector[N_inter1_factor_levels[f]] delta_inter1
      = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
    theta += delta_inter1[inter1_factor_level_idx[f]];
  }
  
  packed_delta_inter1_ncp ~ normal(0, 1);
  packed_delta_inter1_cp ~ normal(0, delta_inter1_tau[packed_inter1_factor_idx[inter1_cp_idx]]);
  delta_inter1_tau ~ normal(0, 2);
  
  // Second-order factor interaction contributions
  for (f in 1:N_inter2_factors) {
    vector[N_inter2_factor_levels[f]] delta_inter2
      = packed_delta_inter2[inter2_factor_start_idx[f]:inter2_factor_end_idx[f]];
    theta += delta_inter2[inter2_factor_level_idx[f]];
  }
  
  packed_delta_inter2_ncp ~ normal(0, 1);
  packed_delta_inter2_cp ~ normal(0, delta_inter2_tau[packed_inter2_factor_idx[inter2_cp_idx]]);
  delta_inter2_tau ~ normal(0, 1);

  // Observational model
  y ~ normal(theta, sigma);
}

generated quantities {
  real y_post_pred[N];
  
  real F_main_post_pred[N_main_factors];
  real F_inter1_post_pred[N_inter1_factors];
  real F_inter2_post_pred[N_inter2_factors];
  
  {
    vector[N] theta =  rep_vector(baseline, N);

    for (f in 1:N_main_factors) {
      vector[N_main_factor_levels[f]] delta_main
        = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      theta += delta_main[main_factor_level_idx[f]];
    }
    
    for (f in 1:N_inter1_factors) {
      vector[N_inter1_factor_levels[f]] delta_inter1
        = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
      theta += delta_inter1[inter1_factor_level_idx[f]];
    }
    
    for (f in 1:N_inter2_factors) {
      vector[N_inter2_factor_levels[f]] delta_inter2
        = packed_delta_inter2[inter2_factor_start_idx[f]:inter2_factor_end_idx[f]];
      theta += delta_inter2[inter2_factor_level_idx[f]];
    }
    
    y_post_pred = normal_rng(theta, sigma);
  
    for (f in 1:N_main_factors) {
      F_main_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                   main_factor_level_idx[f], 
                                   N_main_factor_levels[f]);
    }
    
    for (f in 1:N_inter1_factors) {
      F_inter1_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                     inter1_factor_level_idx[f], 
                                     N_inter1_factor_levels[f]);
    }
    
    for (f in 1:N_inter2_factors) {
      F_inter2_post_pred[f] = F_stat(to_vector(y_post_pred), N, 
                                     inter2_factor_level_idx[f], 
                                     N_inter2_factor_levels[f]);
    }
  }
}

Per usual we default to non-centering the residual parameters for the levels within this new factor.

text
data$inter2_cp_idx <- vector()
data$L_inter2_cp <- length(data$inter2_cp_idx)

data$inter2_ncp_idx <- setdiff(1:data$N_all_inter2_factor_levels,
                               data$inter2_cp_idx)
data$L_inter2_ncp <- length(data$inter2_ncp_idx)
text
fit <- stan(file='stan_programs/overlapping_factors_ver3.stan',
            data=data, seed=4838282, refresh=2000)

Unfortunately this proves to be a poor choice.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "4 of 4000 iterations ended with a divergence (0.1%)"
[1] "  Try running with larger adapt_delta to remove the divergences"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

While there are only a few divergences we cannot let down our guard.

text
partition <- util$partition_div(fit)
div_samples <- partition[[1]]
nondiv_samples <- partition[[2]]

The levels of Main Factor 1 exhibit some mild inverted funnel geometry, but nothing too problematic.

text
f <- 1
par(mfrow=c(1, 3))

for (l in data$main_factor_start_idx[f]:data$main_factor_end_idx[f]) {
  if (l %in% data$main_cp_idx) {
    cp_idx <- which(l == data$main_cp_idx)
    name_x <- paste("packed_delta_main_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$main_ncp_idx)
    name_x <- paste("packed_delta_main_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  }

  title=paste(main_factor_names[f],
              ",\nLevel = ", l - data$main_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-4, 3))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

Main Factor 2 enjoys stronger partial pooling, but maybe not enough to suppress the inverted funnel geometry towards larger population scales. These are our chief suspects.

text
f <- 2
par(mfrow=c(1, 3))

for (l in data$main_factor_start_idx[f]:data$main_factor_end_idx[f]) {
  if (l %in% data$main_cp_idx) {
    cp_idx <- which(l == data$main_cp_idx)
    name_x <- paste("packed_delta_main_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$main_ncp_idx)
    name_x <- paste("packed_delta_main_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  }

  title=paste(main_factor_names[f],
              ", Level = ", l - data$main_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(0, 3))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

Similarly Main Factor 3 looks okay, likely due to the stronger aggregation of data into each of the fewer levels.

text
f <- 3
par(mfrow=c(2, 2))

for (l in data$main_factor_start_idx[f]:data$main_factor_end_idx[f]) {
  if (l %in% data$main_cp_idx) {
    cp_idx <- which(l == data$main_cp_idx)
    name_x <- paste("packed_delta_main_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$main_ncp_idx)
    name_x <- paste("packed_delta_main_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  }

  title=paste(main_factor_names[f],
              ", Level = ", l - data$main_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-1, 3))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

What about the first-order interactions? Nothing too suspicious.

text
par(mar=c(5, 5, 3, 1))

f <- 1
par(mfrow=c(1, 4))

for (l in data$inter1_factor_start_idx[f]:data$inter1_factor_end_idx[f]) {
  if (l %in% data$inter1_cp_idx) {
    cp_idx <- which(l == data$inter1_cp_idx)
    name_x <- paste("packed_delta_inter1_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_inter1_tau[", data$packed_inter1_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$inter1_ncp_idx)
    name_x <- paste("packed_delta_inter1_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_inter1_tau[", data$packed_inter1_factor_idx[l], "]", sep='')
  }

  title=paste(inter1_factor_names[f],
              ",\nLevel = ", l - data$inter1_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(0, 2))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

text
f <- 2
par(mfrow=c(1, 4))

for (l in data$inter1_factor_start_idx[f]:data$inter1_factor_end_idx[f]) {
  if (l %in% data$inter1_cp_idx) {
    cp_idx <- which(l == data$inter1_cp_idx)
    name_x <- paste("packed_delta_inter1_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_inter1_tau[", data$packed_inter1_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$inter1_ncp_idx)
    name_x <- paste("packed_delta_inter1_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_inter1_tau[", data$packed_inter1_factor_idx[l], "]", sep='')
  }

  title=paste(inter1_factor_names[f],
              ",\nLevel = ", l - data$inter1_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-8, 1))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

text
f <- 3
par(mfrow=c(1, 4))

for (l in data$inter1_factor_start_idx[f]:data$inter1_factor_end_idx[f]) {
  if (l %in% data$inter1_cp_idx) {
    cp_idx <- which(l == data$inter1_cp_idx)
    name_x <- paste("packed_delta_inter1_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_inter1_tau[", data$packed_inter1_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$inter1_ncp_idx)
    name_x <- paste("packed_delta_inter1_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_inter1_tau[", data$packed_inter1_factor_idx[l], "]", sep='')
  }

  title=paste(inter1_factor_names[f],
              ",\nLevel = ", l - data$inter1_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-1, 2))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

Finally the second-order interaction levels also look unproblematic. To avoid an overwhelming number of plots let's peruse just the first sixteen levels.

text
f <- 1
par(mfrow=c(1, 4))

for (l in 1:16) {
  if (l %in% data$inter2_cp_idx) {
    cp_idx <- which(l == data$inter2_cp_idx)
    name_x <- paste("packed_delta_inter2_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_inter2_tau[", data$packed_inter2_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$inter2_ncp_idx)
    name_x <- paste("packed_delta_inter2_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_inter2_tau[", data$packed_inter2_factor_idx[l], "]", sep='')
  }

  title=paste(inter2_factor_names[f],
              ",\nLevel = ", l - data$inter2_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-8, 8),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-8, 1))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

Because the Main Factor 2 levels exhibited the worst geometry let's try centering those parameters and trying the fit again.

text
data$main_cp_idx <- data$main_factor_start_idx[2]:data$main_factor_end_idx[2]
data$L_main_cp <- length(data$main_cp_idx)

data$main_ncp_idx <- setdiff(1:data$N_all_main_factor_levels, data$main_cp_idx)
data$L_main_ncp <- length(data$main_ncp_idx)

data$inter2_cp_idx <- vector()
data$L_inter2_cp <- length(data$inter2_cp_idx)

data$inter2_ncp_idx <- setdiff(1:data$N_all_inter2_factor_levels,
                               data$inter2_cp_idx)
data$L_inter2_ncp <- length(data$inter2_ncp_idx)
text
fit <- stan(file='stan_programs/overlapping_factors_ver3.stan',
            data=data, seed=4838282, refresh=2000)

Fortunately that resolved all of our problems!

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

Why did we have to center the Main Factor 2 levels only after adding the second-order interaction factors but not before? Remember that none of the residual contributions influence the likelihood function independently of the others. When higher-order contributions are non-zero their addition can give the lower-order residuals freedom to explore different configurations, and unfortunately sometimes even more computationally pathological configurations.

In any case our careful centering seems to have done the trick and we can move onto posterior inferences. First our posterior retrodicive checks have not gotten any worse.

text
samples <- extract(fit)

par(mfrow=c(3, 3))

lims <- c(100, 700, 200)
deltas <- c(2, 10, 2)

for (f in 1:3) {
  hist(samples$F_main_post_pred[,f], breaks=seq(0, 700, deltas[f]),
       main=main_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_main_obs[f], col="black", lty=1, lw=2)
}

lims <- c(1500, 250, 2000)
deltas <- c(20, 5, 20)

for (f in 1:3) {
  hist(samples$F_inter1_post_pred[,f], breaks=seq(0, 1500, deltas[f]),
       main=inter1_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_inter1_obs[f], col="black", lty=1, lw=2)
}

plot.new()
for (f in 1:1) {
  hist(samples$F_inter2_post_pred[,f], breaks=seq(4000, 20000, 100),
       main=inter2_factor_names[f],
       col=c_dark, border=c_dark_highlight,
       xlim=c(5000, 16000), xlab="F Statistic", yaxt='n', ylab="")
  abline(v=F_inter2_obs[f], col="black", lty=1, lw=2)
}

Satisfied that the full residual expansion adequately captures the features of the true data generating process that we can resolve with the given data, we can now consider posterior inferences. First let's look at the baseline parameter.

text
par(mfrow=c(1, 1))
par(mar=c(5, 5, 3, 5))

hist(samples$baseline, breaks=seq(-10, 20, 0.25), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(-10, 20), xlab="Baseline", yaxt='n', ylab="")

Then we can consider the main factor contributions to the overall heterogeneity.

text
plot_factor_posteriors <- function(type, title, f) {
  layout(matrix(c(1, 1, 2), nrow=1))
 
  par(mar=c(5, 5, 3, 1))

  L <- data[paste("N_", type, "_factor_levels", sep="")][[1]][f]
  level_idx <- data[paste(type, "_factor_start_idx", sep="")][[1]][f]:
               data[paste(type, "_factor_end_idx", sep="")][[1]][f]

  idx <- rep(1:L, each=2)
  x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

  probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
  cred <- sapply(level_idx, function(l)
                   quantile(samples[paste("packed_delta_", type, sep="")][[1]][,l], probs=probs))
  pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9,n]))

  mean_tau <- mean(samples[paste("delta_", type, "_tau", sep="")][[1]][,f])

  l <- min(c(-2.25 * mean_tau, cred[1,]))
  u <- max(c(2.25 * mean_tau,  cred[9,]))
 
  plot(1, type="n", main=title,
       xlim=c(0.5, L + 0.5), xlab="Level",
       ylim=c(l, u), ylab="Marginal Posterior")

  lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

  polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
          col = c_light, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
          col = c_light_highlight, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
          col = c_mid, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
          col = c_mid_highlight, border = NA)
  for (l in 1:L)
    lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

  par(mar=c(5, 1, 3, 1))

  u <- 1.25 * max(samples[paste("delta_", type, "_tau", sep="")][[1]][,f])
  hist(samples[paste("delta_", type, "_tau", sep="")][[1]][,f], breaks=seq(0, u, u / 50),
       main=title,
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
  abline(v=mean_tau, col="gray80", lwd=2, lty=3)
}

plot_factor_posteriors("main", "Main Factor 1", 1)

text
plot_factor_posteriors("main", "Main Factor 2", 2)

text
plot_factor_posteriors("main", "Main Factor 3", 3)

Then the first-order interaction contributions to the overall heterogeneity.

text
plot_factor_posteriors("inter1", "Interaction 12", 1)

text
plot_factor_posteriors("inter1", "Interaction 13", 2)

text
plot_factor_posteriors("inter1", "Interaction 23", 3)

Finally we can examine the second-order interaction contributions, which are largely consistent with zero given the resolution afforded by the observed data. This in particular verifies the previous Interaction 123 posterior retrodictive check.

text
plot_factor_posteriors("inter2", "Interaction 123", 1)

Once we have an adequate model we can then consider applying its inferences beyond the scope of the given measurement. For example let's consider using our inferences to inform predictions for an entirely new circumstance.

text
pred_data <- read_rdump("data/overlapping_multifactor_pred.data.R")

names(pred_data)
text
[1] "main_factor_level_idx" "N"                     "N_main_factor_levels" 
[4] "N_main_factors"       

Because the main factor level occupancies vary considerably in this new circumstance we can't just naively extrapolate predictions from our previous fit.

text
par(mfrow=c(1, 3))

for (f in 1:data$N_main_factors) {
  hist(data$main_factor_level_idx[f,],
       breaks=1:(data$N_main_factor_levels[f]+1)-0.5,
       main=main_factor_names[f], col=c_light_trans, border=c_light,
       xlim=c(0, data$N_main_factor_levels[f]+1), xlab="Level",
       ylim=c(0, 200), yaxt='n', ylab="")
  hist(pred_data$main_factor_level_idx[f,],
       breaks=1:(data$N_main_factor_levels[f]+1)-0.45,
       col=c_dark_trans, border=c_dark, add=T)
  text(0, 185, label="In-Sample", pos=4, col=c_light)
  text(0, 175, label="Out-of-Sample", pos=4, col=c_dark)
}

What we can do, however, is reconstruct the proper heterogeneity in the new factor configurations to generate predictions specific to the new circumstance. First we have to build all of the interaction factors for these new factor configurations.

text
inter <- stan(file='stan_programs/construct_inter_idx_general.stan',
              data=pred_data, iter=1, warmup=0, chains=1,
              algorithm="Fixed_param")
text
DIAGNOSTIC(S) FROM PARSER:
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * N_main_factors * N_main_factors - 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: N_main_factors * i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i * i + 1 / 6
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: j - 1 * j / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i * i + 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * N_main_factors * N_main_factors - 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: N_main_factors * i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i * i + 1 / 6
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: j - 1 * j / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i * i + 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.


SAMPLING FOR MODEL 'construct_inter_idx_general' NOW (CHAIN 1).
Chain 1: Iteration: 1 / 1 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0 seconds (Warm-up)
Chain 1:                7.2e-05 seconds (Sampling)
Chain 1:                7.2e-05 seconds (Total)
Chain 1: 
text
inter_output <- extract(inter)

data$pred_N <- pred_data$N
data$pred_main_factor_level_idx <- pred_data$main_factor_level_idx
data$pred_inter1_factor_level_idx <- inter_output$inter1_factor_level_idx[1,,]
dim(data$pred_inter1_factor_level_idx) <- c(data$N_inter1_factors, data$pred_N)
data$pred_inter2_factor_level_idx <- inter_output$inter2_factor_level_idx[1,,]
dim(data$pred_inter2_factor_level_idx) <- c(data$N_inter2_factors, data$pred_N)

Unsurprisingly the interaction factor level occupancies also vary considerably.

text
par(mfrow=c(2, 3))

names <- c("Interaction Factor 12", "Interaction Factor 13", "Interaction Factor 23")
for (f in 1:data$N_inter1_factors) {
  hist(data$inter1_factor_level_idx[f,],
       breaks=1:(data$N_inter1_factor_levels[f]+1)-0.5,
       main=names[f], col=c_light_trans, border=c_light,
       xlim=c(0, data$N_inter1_factor_levels[f]+1), xlab="Level",
       ylim=c(0, 100), yaxt='n', ylab="")
  hist(data$pred_inter1_factor_level_idx[f,],
       breaks=1:(data$N_inter1_factor_levels[f]+1)-0.45,
       col=c_dark_trans, border=c_dark, add=T)
}

plot.new()

names <- c("Interaction Factor 123")
for (f in 1:data$N_inter2_factors) {
  hist(data$inter2_factor_level_idx[f,],
       breaks=1:(data$N_inter2_factor_levels[f]+1)-0.5,
       main=names[f], col=c_light_trans, border=c_light,
       xlim=c(0, data$N_inter2_factor_levels[f]+1), xlab="Level",
       ylim=c(0, 25), yaxt='n', ylab="")
  hist(data$pred_inter2_factor_level_idx[f,],
       breaks=1:(data$N_inter2_factor_levels[f]+1)-0.45,
       col=c_dark_trans, border=c_dark, add=T)
}

For each factor configuration in this new, external data set we can reconstruct the expected behavior using the posterior inferences for the residual contributions. Provided that whatever latent process that generates the heterogeneity generalizes to the new circumstance this should yield reasonably accurate predictions.

text
writeLines(readLines("stan_programs/overlapping_factors_ver2_pred.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  vector[N] y;         // Observations
  real<lower=0> sigma; // Measurement variability

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N];
  
  int<lower=0> N_all_inter1_factor_levels;
  int<lower=1, upper=N_inter1_factors> packed_inter1_factor_idx[N_all_inter1_factor_levels];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_start_idx[N_inter1_factors];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_end_idx[N_inter1_factors];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_ncp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_ncp_idx[L_inter1_ncp];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_cp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_cp_idx[L_inter1_cp];

  // Out of sample prediction data
  int<lower=0> pred_N;
  int<lower=1> pred_main_factor_level_idx[N_main_factors, pred_N];
  int<lower=1> pred_inter1_factor_level_idx[N_inter1_factors, pred_N];
}

parameters {  
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // First-order factor interaction contributions
  vector[L_inter1_ncp] packed_delta_inter1_ncp;
  vector[L_inter1_cp] packed_delta_inter1_cp; 
  vector<lower=0>[N_inter1_factors] delta_inter1_tau;
}

transformed parameters {
  vector[N_all_main_factor_levels] packed_delta_main;
  vector[N_all_inter1_factor_levels] packed_delta_inter1;
    
  packed_delta_main[main_ncp_idx] 
    = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
  packed_delta_main[main_cp_idx] = packed_delta_main_cp;
  
  packed_delta_inter1[inter1_ncp_idx] 
    = delta_inter1_tau[packed_inter1_factor_idx[inter1_ncp_idx]] .* packed_delta_inter1_ncp;
  packed_delta_inter1[inter1_cp_idx] = packed_delta_inter1_cp;
}

model {
  // Baseline contribution
  vector[N] theta =  rep_vector(baseline, N);
  
  baseline ~ normal(0, 5);
  
  // Main factor contributions
  for (f in 1:N_main_factors) {
    vector[N_main_factor_levels[f]] delta_main
      = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
    theta += delta_main[main_factor_level_idx[f]];
  }
  
  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 3);
  
  // First-order factor interaction contributions
  for (f in 1:N_inter1_factors) {
    vector[N_inter1_factor_levels[f]] delta_inter1
      = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
    theta += delta_inter1[inter1_factor_level_idx[f]];
  }
  
  packed_delta_inter1_ncp ~ normal(0, 1);
  packed_delta_inter1_cp ~ normal(0, delta_inter1_tau[packed_inter1_factor_idx[inter1_cp_idx]]);
  delta_inter1_tau ~ normal(0, 2);

  // Observational model
  y ~ normal(theta, sigma);
}

generated quantities {
  real y_post_pred[N];
  real y_post_out_pred[pred_N];
  {
    vector[N] theta =  rep_vector(baseline, N);
    vector[pred_N] pred_theta =  rep_vector(baseline, pred_N);

    for (f in 1:N_main_factors) {
      vector[N_main_factor_levels[f]] delta_main
        = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      theta += delta_main[main_factor_level_idx[f]];
      pred_theta += delta_main[pred_main_factor_level_idx[f]];
    }
    
    for (f in 1:N_inter1_factors) {
      vector[N_inter1_factor_levels[f]] delta_inter1
        = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
      theta += delta_inter1[inter1_factor_level_idx[f]];
      pred_theta += delta_inter1[pred_inter1_factor_level_idx[f]];
    }
    
    y_post_pred = normal_rng(theta, sigma);
    y_post_out_pred = normal_rng(pred_theta, sigma);
  }
}
text
fit <- stan(file='stan_programs/overlapping_factors_ver2_pred.stan',
            data=data, seed=4838282, refresh=2000)

Indeed the reconstructed predictions using the new factor configurations are substantially different to those generated from the the old factor configurations.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(samples$y_post_pred, breaks=seq(-15, 40, 0.25),
     main="Aggregate Predictions", col=c_light_trans, border=c_light,
     xlim=c(-15, 25), xlab="y",
     ylim=c(0, 30000), yaxt='n', ylab="")
hist(samples$y_post_out_pred, breaks=seq(-15, 40, 0.25),
     col=c_dark_trans, border=c_dark, add=T)
text(-10, 7000, label="In-Sample", pos=4, col=c_light)
text(-10, 5000, label="Out-of-Sample", pos=4, col=c_dark)

In this case naively extrapolating predictions from our initial fit would lead to poor predictive performance. Because we learn how each main factor, and their interactions, contribute to the overall behavior, however, we can readily adapt to new factor configurations and ensure much better predictive performance. That is at least whenever the actual source of the heterogeneity is constant.

5 Case Studies

Comfortable with the basics of implementing factor models we can now consider some slightly less artificial examples that demonstrate how we might use this modeling technique in actual practice. Our first case study will utilize nested multifactor modeling while our second will utilize overlapping factor modeling.

5.1 Batch Variation

Let's begin by expanding upon the analog-to-digital example from my hierarchical modeling case study.

Recall that an analog-to-digital detector converts some continuous, or analog, input to some discrete, or digital, output. If the input signal II is measured relative to some reference input, I0I_{0}, then we might model the discrete output with a Poisson observational model,

y∼Poisson(λ)λ=ψ⋅II0≡ψ⋅ρI,\begin{align*} y &\sim \text{Poisson}(\lambda) \\ \lambda &= \psi \cdot \frac{I}{I_{0}} \\ &\equiv \psi \cdot \rho_{I}, \end{align*}
where ψ\psi is the calibration coefficient.

In this case we receive sixteen detectors from the manufacturer in four shipments, but we're not sure how consistently the calibration coefficient behaves both between shipments and within shipments. Moreover the output of each detector might also vary depending on exactly where the input signal strikes, suggesting additional heterogeneity in the calibration coefficient across four spatial regions in the active area of each detector.

Because the spatial regions are nested within each detector, and each detector is nested within a shipment, we are naturally lead to consider a nested multifactor model for the calibration coefficient, with Factor 1 identifying each shipment, Factor 2 identifying each detector, and Factor 3 identifying each of the possible spatial regions across all of those detectors.

text
data <- read_rdump("data/batch.data.R")

names(data)
text
[1] "factor2_to_factor1" "y"                  "N_factor2_levels"  
[4] "log_rho_I"          "N_factor3_levels"   "N_factor1_levels"  
[7] "N"                  "obs_to_factor3"     "factor3_to_factor2"

The four spatial regions across the sixteen detectors yields N_factor3_levels = 64 levels in the shallowest factor. For each of these factors we record the digital output from fifteen analog input signals.

text
par(mfrow=c(1, 1))
par(mar=c(5, 5, 3, 5))

hist(data$obs_to_factor3, breaks=seq(0.5, data$N_factor3_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor3_levels + 0.5), xlab="Factor Three Levels",
     ylim=c(0, 20), ylab="Number of Observations")

Factor 2 contains sixteen levels, one for each of the delivered detectors. The four Factor 3 levels corresponding to the spatial regions of each detector nest within the Factor 2 levels.

text
hist(data$factor3_to_factor2, breaks=seq(0.5, data$N_factor2_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor2_levels + 0.5), xlab="Factor Two Levels",
     ylim=c(0, 5), ylab="Number of Factor Three Levels")

text
hist(data$factor3_to_factor2[data$obs_to_factor3],
     breaks=seq(0.5, data$N_factor2_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor2_levels + 0.5), xlab="Factor Two Levels",
     ylim=c(0, 75), ylab="Number of Observations")

Finally those sixteen detector levels nest within four shipment levels.

text
hist(data$factor2_to_factor1, breaks=seq(0.5, data$N_factor1_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor1_levels + 0.5), xlab="Factor One Levels",
     ylim=c(0, 5), ylab="Number of Factor Two Levels")

text
hist(data$factor2_to_factor1[data$factor3_to_factor2[data$obs_to_factor3]],
     breaks=seq(0.5, data$N_factor1_levels + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_factor1_levels + 0.5), xlab="Factor One Levels",
     ylim=c(0, 250), ylab="Number of Observations")

To isolate heterogeneity due to the calibration coefficient for posterior retrodictive checks let's consider the variation of the normalized digital outputs,

ynρI,n,\frac{ y_{n} }{ \rho_{I, n} },
across the Factor 3 levels. As before we summarize this variation with a regularized FF statistic.

text
writeLines(readLines("stan_programs/batch_f_stat.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] log_rho_I; // Observed input signal
  int y[N];            // Observered output counts
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

generated quantities {
  real F = F_stat(to_vector(y) ./ exp(log_rho_I), 
                  N, obs_to_factor3, N_factor3_levels);
}
text
fit <- stan(file='stan_programs/batch_f_stat.stan', data=data, seed=93585393,
            iter=1, warmup=0, chains=1, algorithm="Fixed_param")
text
SAMPLING FOR MODEL 'batch_f_stat' NOW (CHAIN 1).
Chain 1: Iteration: 1 / 1 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0 seconds (Warm-up)
Chain 1:                5.2e-05 seconds (Sampling)
Chain 1:                5.2e-05 seconds (Total)
Chain 1: 
text
F_obs <- extract(fit)$F[1]

For a less overwhelming modeling experience we start simple and iterate, beginning with a baseline only model. Before fitting, however, we want to look at the prior consequences for the population of calibration coefficients to ensure that they don't conflict with our domain expertise.

Here we generate prior samples using Hamiltonian Monte Carlo.

text
writeLines(readLines("stan_programs/batch_ver0_prior.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

parameters {  
  // Baseline
  real baseline;
}

transformed parameters {
  vector[N_factor3_levels] log_psi = rep_vector(baseline, N_factor3_levels);
}

model {  
  baseline ~ normal(0, 1);
}
text
fit <- stan(file='stan_programs/batch_ver0_prior.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

With no indications of computational problems we can investigate the prior behavior for the calibration coefficients, ψ\psi, in the spatial region of each detector. In this case the calibration coefficients are identical and distributed exactly the same as the exponential of the baseline parameter. The exponential does induce a heavy tail towards large values, but nothing outrageous.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(exp(samples$log_psi), breaks=seq(0, 35, 0.25), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 15), xlab="psi", yaxt='n', ylab="")

To fit the posterior we just have to add the observations to the data block, the contribution of the observational model to the model block, and the evaluation of the FF statistic in the functions and generated quantities blocks.

text
writeLines(readLines("stan_programs/batch_ver0.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] log_rho_I; // Observed input signal
  int y[N];            // Observered output counts
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

parameters {  
  // Baseline
  real baseline;
}

transformed parameters {
  vector[N_factor3_levels] log_psi = rep_vector(baseline, N_factor3_levels);
}

model {  
  baseline ~ normal(0, 1);

  y ~ poisson_log(log_psi[obs_to_factor3] + log_rho_I);
}

generated quantities {
  int y_post_pred[N] = poisson_log_rng(log_psi[obs_to_factor3] + log_rho_I);
  real F_post_pred = F_stat(to_vector(y_post_pred) ./ exp(log_rho_I), 
                            N, obs_to_factor3, N_factor3_levels);
}
text
fit <- stan(file='stan_programs/batch_ver0.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

With the fit looking okay we next consider the posterior retrodictive checks. Unfortunately our baseline only model does a terrible job of capturing the heterogeneity observed in the data.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(samples$F_post_pred, breaks=seq(0, 6000, 50),
     main="Posterior Retrodictive Checks",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 6000), xlab="F Statistic", yaxt='n', ylab="")
abline(v=F_obs, col="white", lty=1, lw=3)
abline(v=F_obs, col="black", lty=1, lw=2)

At the same time the posterior retrodictive distribution of digital outputs is remarkably different between the observed outputs, corroborating the inadequacy of our initial model.

text
B <- 101
breaks <- seq(-0.5, B - 0.5, 1)

idx <- rep(1:B, each=2)
xs <- sapply(1:length(idx), function(b) if(b %% 2 == 0) idx[b] + 0.5 else idx[b] - 0.5)

obs <- hist(data$y, breaks=breaks, plot=FALSE)$counts
pad_obs <- do.call(cbind, lapply(idx, function(n) obs[n]))

post_pred <- sapply(1:4000, function(n) hist(samples$y_post_pred[n,],
                                             breaks=breaks, plot=FALSE)$counts)
probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:B, function(b) quantile(post_pred[b,], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

plot(1, type="n", main="Posterior Retrodictive Distribution",
     xlim=c(-0.5, B - 0.5), xlab="y",
     ylim=c(0, max(c(obs, cred[9,]))), ylab="")

polygon(c(xs, rev(xs)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
lines(xs, pad_cred[5,], col=c_dark, lwd=2)

lines(xs, pad_obs, col="white", lty=1, lw=2.5)
lines(xs, pad_obs, col="black", lty=1, lw=2)

To improve our model we next incorporate heterogeneity across the four shipments. First we check the prior model, fitting a non-centered parameterization of the Factor 1 hierarchy with Hamiltonian Monte Carlo.

text
writeLines(readLines("stan_programs/batch_ver1_prior.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  int<lower=0, upper=N_factor1_levels> L_factor1_ncp;
  int<lower=1, upper=N_factor1_levels> factor1_ncp_idx[L_factor1_ncp];

  int<lower=0, upper=N_factor1_levels> L_factor1_cp;
  int<lower=1, upper=N_factor1_levels> factor1_cp_idx[L_factor1_cp];
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

parameters {  
  // Baseline
  real baseline;
  
  // Hierarchical model for the first factor residuals
  vector[L_factor1_ncp] delta_factor1_ncp;
  vector[L_factor1_cp] delta_factor1_cp;
  real<lower=0> delta_factor1_tau;
}

transformed parameters {
  vector[N_factor1_levels] delta_factor1;

  vector[N_factor3_levels] log_psi;

  // Reconstruct first factor residuals
  delta_factor1[factor1_ncp_idx] = delta_factor1_tau * delta_factor1_ncp;
  delta_factor1[factor1_cp_idx] = delta_factor1_cp;
  
  log_psi =  baseline
           + delta_factor1[factor2_to_factor1[factor3_to_factor2]];
}

model {  
  baseline ~ normal(0, 1);

  delta_factor1_cp ~ normal(0, delta_factor1_tau);
  delta_factor1_ncp ~ normal(0, 1);
  delta_factor1_tau ~ normal(0, 1);
}
text
data$factor1_cp_idx <- vector()
data$L_factor1_cp <- length(data$factor1_cp_idx)

data$factor1_ncp_idx <- setdiff(1:data$N_factor1_levels, data$factor1_cp_idx)
data$L_factor1_ncp <- length(data$factor1_ncp_idx)
text
fit <- stan(file='stan_programs/batch_ver1_prior.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

The added variation around the logarithmic baseline induces an even heavier tail on the prior model for the calibration coefficients, but that tail is still reasonable with only a relatively small probability allocated to extreme calibration coefficients.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(exp(samples$log_psi[samples$log_psi < 4]),
     breaks=seq(0, 100, 0.25), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 25), xlab="Psi", yaxt='n', ylab="")

Adding the observational model updates the prior Stan program into a posterior Stan program.

text
writeLines(readLines("stan_programs/batch_ver1.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] log_rho_I; // Observed input signal
  int y[N];            // Observered output counts
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  int<lower=0, upper=N_factor1_levels> L_factor1_ncp;
  int<lower=1, upper=N_factor1_levels> factor1_ncp_idx[L_factor1_ncp];

  int<lower=0, upper=N_factor1_levels> L_factor1_cp;
  int<lower=1, upper=N_factor1_levels> factor1_cp_idx[L_factor1_cp];
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

parameters {  
  // Baseline
  real baseline;
  
  // Hierarchical model for the first factor residuals
  vector[L_factor1_ncp] delta_factor1_ncp;
  vector[L_factor1_cp] delta_factor1_cp;
  real<lower=0> delta_factor1_tau;
}

transformed parameters {
  vector[N_factor1_levels] delta_factor1;

  vector[N_factor3_levels] log_psi;

  // Reconstruct first factor residuals
  delta_factor1[factor1_ncp_idx] = delta_factor1_tau * delta_factor1_ncp;
  delta_factor1[factor1_cp_idx] = delta_factor1_cp;
  
  log_psi =  baseline
           + delta_factor1[factor2_to_factor1[factor3_to_factor2]];
}

model {  
  baseline ~ normal(0, 1);

  delta_factor1_cp ~ normal(0, delta_factor1_tau);
  delta_factor1_ncp ~ normal(0, 1);
  delta_factor1_tau ~ normal(0, 1);
  
  y ~ poisson_log(log_psi[obs_to_factor3] + log_rho_I);
}

generated quantities {
  int y_post_pred[N] = poisson_log_rng(log_psi[obs_to_factor3] + log_rho_I);
  real F_post_pred = F_stat(to_vector(y_post_pred) ./ exp(log_rho_I), 
                            N, obs_to_factor3, N_factor3_levels);
}

We'll fit using the same non-centered parameterization we set just above.

text
fit <- stan(file='stan_programs/batch_ver1.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)

Ooph.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "25 of 4000 iterations ended with a divergence (0.625%)"
[1] "  Try running with larger adapt_delta to remove the divergences"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

Let's go hunting.

text
partition <- util$partition_div(fit)
div_samples <- partition[[1]]
nondiv_samples <- partition[[2]]

Because we have only one hierarchy here the investigation is pretty straightforward. All of the Factor 1 level parameters exhibit an inverted funnel, and the divergences concentrate at large values of the population scale.

text
par(mfrow=c(1, data$N_factor1_levels))
par(mar=c(5, 4, 3, 2), oma = c(0, 0, 2, 0))

for (l in 1:data$N_factor1_levels) {
  if (l %in% data$factor1_cp_idx) {
    cp_idx <- which(l == data$factor1_cp_idx)
    name_x <- paste("delta_factor1_cp[", cp_idx, "]", sep='')
  } else {
    ncp_idx <- which(l == data$factor1_ncp_idx)
    name_x <- paste("delta_factor1_ncp[", ncp_idx, "]", sep='')
  }
  name_y <- "delta_factor1_tau"

  title=paste("Factor One Level = ", l, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-6, 6),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-2, 1))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

mtext("Factor One Hierarchy", outer=TRUE)

This immediately suggests a monolithically centered parameterization, which in hindsight isn't that surprising given the strong aggregation of data into these deeper levels.

text
data$factor1_cp_idx <- 1:data$N_factor1_levels
data$L_factor1_cp <- length(data$factor1_cp_idx)

data$factor1_ncp_idx <- setdiff(1:data$N_factor1_levels, data$factor1_cp_idx)
data$L_factor1_ncp <- length(data$factor1_ncp_idx)
text
fit <- stan(file='stan_programs/batch_ver1.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)

Much better.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

Unfortunately while the shipment heterogeneity does improve our fit, the data still exhibits significantly more variation.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(samples$F_post_pred, breaks=seq(0, 6000, 50),
     main="Posterior Retrodictive Checks",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 6000), xlab="F Statistic", yaxt='n', ylab="")
abline(v=F_obs, col="white", lty=1, lw=3)
abline(v=F_obs, col="black", lty=1, lw=2)

The overall distribution of the observations also hints as a poor fit. The observed data are skewed towards lower values and don't exhibit the shoulder seen in the posterior retrodictions.

text
B <- 101
breaks <- seq(-0.5, B - 0.5, 1)

idx <- rep(1:B, each=2)
xs <- sapply(1:length(idx), function(b) if(b %% 2 == 0) idx[b] + 0.5 else idx[b] - 0.5)

obs <- hist(data$y, breaks=breaks, plot=FALSE)$counts
pad_obs <- do.call(cbind, lapply(idx, function(n) obs[n]))

post_pred <- sapply(1:4000, function(n) hist(samples$y_post_pred[n,],
                                             breaks=breaks,
                                             plot=FALSE)$counts)
probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:B, function(b) quantile(post_pred[b,], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

plot(1, type="n", main="Posterior Retrodictive Distribution",
     xlim=c(-0.5, B - 0.5), xlab="y",
     ylim=c(0, max(c(obs, cred[9,]))), ylab="")

polygon(c(xs, rev(xs)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
lines(xs, pad_cred[5,], col=c_dark, lwd=2)

lines(xs, pad_obs, col="white", lty=1, lw=2.5)
lines(xs, pad_obs, col="black", lty=1, lw=2)

And so we continue on, this time incorporating the detector heterogeneity within each shipment.

text
writeLines(readLines("stan_programs/batch_ver2_prior.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  int<lower=0, upper=N_factor1_levels> L_factor1_ncp;
  int<lower=1, upper=N_factor1_levels> factor1_ncp_idx[L_factor1_ncp];

  int<lower=0, upper=N_factor1_levels> L_factor1_cp;
  int<lower=1, upper=N_factor1_levels> factor1_cp_idx[L_factor1_cp];
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  int<lower=0, upper=N_factor2_levels> L_factor2_ncp;
  int<lower=1, upper=N_factor2_levels> factor2_ncp_idx[L_factor2_ncp];

  int<lower=0, upper=N_factor2_levels> L_factor2_cp;
  int<lower=1, upper=N_factor2_levels> factor2_cp_idx[L_factor2_cp];
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

parameters {  
  // Baseline
  real baseline;
  
  // Hierarchical model for the first factor residuals
  vector[L_factor1_ncp] delta_factor1_ncp;
  vector[L_factor1_cp] delta_factor1_cp;
  real<lower=0> delta_factor1_tau;
  
  // Hierarchical models for the second factor residuals
  vector[L_factor2_ncp] delta_factor2_ncp;
  vector[L_factor2_cp]  delta_factor2_cp;
  vector<lower=0>[N_factor1_levels] delta_factor2_tau;
}

transformed parameters {
  vector[N_factor1_levels] delta_factor1;
  vector[N_factor2_levels] delta_factor2;

  vector[N_factor3_levels] log_psi;

  // Reconstruct first factor residuals
  delta_factor1[factor1_ncp_idx] = delta_factor1_tau * delta_factor1_ncp;
  delta_factor1[factor1_cp_idx] = delta_factor1_cp;

  // Reconstruct second factor residuals
  delta_factor2[factor2_ncp_idx] 
    =   delta_factor2_tau[factor2_to_factor1[factor2_ncp_idx]] .* delta_factor2_ncp;
  delta_factor2[factor2_cp_idx] = delta_factor2_cp;
  
  log_psi =  baseline
           + delta_factor1[factor2_to_factor1[factor3_to_factor2]]
           + delta_factor2[factor3_to_factor2];
}

model {  
  baseline ~ normal(0, 1);

  delta_factor1_cp ~ normal(0, delta_factor1_tau);
  delta_factor1_ncp ~ normal(0, 1);
  delta_factor1_tau ~ normal(0, 1);
    
  delta_factor2_cp ~ normal(0, delta_factor2_tau[factor2_to_factor1[factor2_cp_idx]]);
  delta_factor2_ncp ~ normal(0, 1);
  delta_factor2_tau ~ normal(0, 0.5);
}

For the prior fit we want to make sure to monolithically non-center all of the hierarchies.

text
data$factor1_cp_idx <- vector()
data$L_factor1_cp <- length(data$factor1_cp_idx)

data$factor1_ncp_idx <- setdiff(1:data$N_factor1_levels, data$factor1_cp_idx)
data$L_factor1_ncp <- length(data$factor1_ncp_idx)

data$factor2_cp_idx <- vector()
data$L_factor2_cp <- length(data$factor2_cp_idx)

data$factor2_ncp_idx <- setdiff(1:data$N_factor2_levels, data$factor2_cp_idx)
data$L_factor2_ncp <- length(data$factor2_ncp_idx)
text
fit <- stan(file='stan_programs/batch_ver2_prior.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

As before the added variation fattens the tail on the calibration coefficients a bit, but there is still no real cause for concern.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(exp(samples$log_psi[samples$log_psi < 4]),
     breaks=seq(0, 100, 0.25), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 25), xlab="Psi", yaxt='n', ylab="")

On to Cincinnati. I mean the posterior distribution.

text
writeLines(readLines("stan_programs/batch_ver2.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] log_rho_I; // Observed input signal
  int y[N];            // Observered output counts
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  int<lower=0, upper=N_factor1_levels> L_factor1_ncp;
  int<lower=1, upper=N_factor1_levels> factor1_ncp_idx[L_factor1_ncp];

  int<lower=0, upper=N_factor1_levels> L_factor1_cp;
  int<lower=1, upper=N_factor1_levels> factor1_cp_idx[L_factor1_cp];
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  int<lower=0, upper=N_factor2_levels> L_factor2_ncp;
  int<lower=1, upper=N_factor2_levels> factor2_ncp_idx[L_factor2_ncp];

  int<lower=0, upper=N_factor2_levels> L_factor2_cp;
  int<lower=1, upper=N_factor2_levels> factor2_cp_idx[L_factor2_cp];
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

parameters {  
  // Baseline
  real baseline;
  
  // Hierarchical model for the first factor residuals
  vector[L_factor1_ncp] delta_factor1_ncp;
  vector[L_factor1_cp] delta_factor1_cp;
  real<lower=0> delta_factor1_tau;
  
  // Hierarchical models for the second factor residuals
  vector[L_factor2_ncp] delta_factor2_ncp;
  vector[L_factor2_cp]  delta_factor2_cp;
  vector<lower=0>[N_factor1_levels] delta_factor2_tau;
}

transformed parameters {
  vector[N_factor1_levels] delta_factor1;
  vector[N_factor2_levels] delta_factor2;

  vector[N_factor3_levels] log_psi;

  // Reconstruct first factor residuals
  delta_factor1[factor1_ncp_idx] = delta_factor1_tau * delta_factor1_ncp;
  delta_factor1[factor1_cp_idx] = delta_factor1_cp;

  // Reconstruct second factor residuals
  delta_factor2[factor2_ncp_idx] 
    =   delta_factor2_tau[factor2_to_factor1[factor2_ncp_idx]] .* delta_factor2_ncp;
  delta_factor2[factor2_cp_idx] = delta_factor2_cp;
  
  log_psi =  baseline
           + delta_factor1[factor2_to_factor1[factor3_to_factor2]]
           + delta_factor2[factor3_to_factor2];
}

model {  
  baseline ~ normal(0, 1);

  delta_factor1_cp ~ normal(0, delta_factor1_tau);
  delta_factor1_ncp ~ normal(0, 1);
  delta_factor1_tau ~ normal(0, 1);
    
  delta_factor2_cp ~ normal(0, delta_factor2_tau[factor2_to_factor1[factor2_cp_idx]]);
  delta_factor2_ncp ~ normal(0, 1);
  delta_factor2_tau ~ normal(0, 0.5);
  
  y ~ poisson_log(log_psi[obs_to_factor3] + log_rho_I);
}

generated quantities {
  int y_post_pred[N] = poisson_log_rng(log_psi[obs_to_factor3] + log_rho_I);
  real F_post_pred = F_stat(to_vector(y_post_pred) ./ exp(log_rho_I), 
                            N, obs_to_factor3, N_factor3_levels);
}

Given the lessons from the fit of the previous model we'll want to center the shipment levels again, but we'll start with a non-centered parameterization of the detector levels.

text
data$factor1_cp_idx <- 1:data$N_factor1_levels
data$L_factor1_cp <- length(data$factor1_cp_idx)

data$factor1_ncp_idx <- setdiff(1:data$N_factor1_levels, data$factor1_cp_idx)
data$L_factor1_ncp <- length(data$factor1_ncp_idx)
text
fit <- stan(file='stan_programs/batch_ver2.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)

Looks like we hit on a decent parameterization.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

The posterior retrodictive distribution for the FF statistic crawls up towards the observed value, but still not enough.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(samples$F_post_pred, breaks=seq(0, 6000, 50),
     main="Posterior Retrodictive Checks",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 6000), xlab="F Statistic", yaxt='n', ylab="")
abline(v=F_obs, col="white", lty=1, lw=3)
abline(v=F_obs, col="black", lty=1, lw=2)

Similarly the posterior retrodictive histograms for the entire observation are still not able to capture the skew of the observed histogram.

text
B <- 101
breaks <- seq(-0.5, B - 0.5, 1)

idx <- rep(1:B, each=2)
xs <- sapply(1:length(idx), function(b) if(b %% 2 == 0) idx[b] + 0.5 else idx[b] - 0.5)

obs <- hist(data$y, breaks=breaks, plot=FALSE)$counts
pad_obs <- do.call(cbind, lapply(idx, function(n) obs[n]))

post_pred <- sapply(1:4000, function(n) hist(samples$y_post_pred[n,], breaks=breaks, plot=FALSE)$counts)
probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:B, function(b) quantile(post_pred[b,], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

plot(1, type="n", main="Posterior Retrodictive Distribution",
     xlim=c(-0.5, B - 0.5), xlab="y",
     ylim=c(0, max(c(obs, cred[9,]))), ylab="")

polygon(c(xs, rev(xs)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
lines(xs, pad_cred[5,], col=c_dark, lwd=2)

lines(xs, pad_obs, col="white", lty=1, lw=2.5)
lines(xs, pad_obs, col="black", lty=1, lw=2)

We now finally consider the spatial heterogeneity within each detector as encoded in Factor 3. As always we start with a prior check.

text
writeLines(readLines("stan_programs/batch_ver3_prior.stan"))
text
data {
  int<lower=0> N;      // Number of observations
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  int<lower=0, upper=N_factor1_levels> L_factor1_ncp;
  int<lower=1, upper=N_factor1_levels> factor1_ncp_idx[L_factor1_ncp];

  int<lower=0, upper=N_factor1_levels> L_factor1_cp;
  int<lower=1, upper=N_factor1_levels> factor1_cp_idx[L_factor1_cp];
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  int<lower=0, upper=N_factor2_levels> L_factor2_ncp;
  int<lower=1, upper=N_factor2_levels> factor2_ncp_idx[L_factor2_ncp];

  int<lower=0, upper=N_factor2_levels> L_factor2_cp;
  int<lower=1, upper=N_factor2_levels> factor2_cp_idx[L_factor2_cp];
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  int<lower=0, upper=N_factor3_levels> L_factor3_ncp;
  int<lower=1, upper=N_factor3_levels> factor3_ncp_idx[L_factor3_ncp];

  int<lower=0, upper=N_factor3_levels> L_factor3_cp;
  int<lower=1, upper=N_factor3_levels> factor3_cp_idx[L_factor3_cp];
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

parameters {  
  // Baseline
  real baseline;
  
  // Hierarchical model for the first factor residuals
  vector[L_factor1_ncp] delta_factor1_ncp;
  vector[L_factor1_cp] delta_factor1_cp;
  real<lower=0> delta_factor1_tau;
  
  // Hierarchical models for the second factor residuals
  vector[L_factor2_ncp] delta_factor2_ncp;
  vector[L_factor2_cp]  delta_factor2_cp;
  vector<lower=0>[N_factor1_levels] delta_factor2_tau;
  
  // Hierarchical models for the third factor residuals
  vector[L_factor3_ncp] delta_factor3_ncp;
  vector[L_factor3_cp]  delta_factor3_cp;
  vector<lower=0>[N_factor2_levels] delta_factor3_tau;
}

transformed parameters {
  vector[N_factor1_levels] delta_factor1;
  vector[N_factor2_levels] delta_factor2;
  vector[N_factor3_levels] delta_factor3;

  vector[N_factor3_levels] log_psi;

  // Reconstruct first factor residuals
  delta_factor1[factor1_ncp_idx] = delta_factor1_tau * delta_factor1_ncp;
  delta_factor1[factor1_cp_idx] = delta_factor1_cp;

  // Reconstruct second factor residuals
  delta_factor2[factor2_ncp_idx] 
    =   delta_factor2_tau[factor2_to_factor1[factor2_ncp_idx]] .* delta_factor2_ncp;
  delta_factor2[factor2_cp_idx] = delta_factor2_cp;

  // Reconstruct third factor residuals
  delta_factor3[factor3_ncp_idx] 
    =   delta_factor3_tau[factor3_to_factor2[factor3_ncp_idx]] .* delta_factor3_ncp;
  delta_factor3[factor3_cp_idx] = delta_factor3_cp;
  
  log_psi =  baseline
           + delta_factor1[factor2_to_factor1[factor3_to_factor2]]
           + delta_factor2[factor3_to_factor2]
           + delta_factor3;
}

model {  
  baseline ~ normal(0, 1);

  delta_factor1_cp ~ normal(0, delta_factor1_tau);
  delta_factor1_ncp ~ normal(0, 1);
  delta_factor1_tau ~ normal(0, 1);
    
  delta_factor2_cp ~ normal(0, delta_factor2_tau[factor2_to_factor1[factor2_cp_idx]]);
  delta_factor2_ncp ~ normal(0, 1);
  delta_factor2_tau ~ normal(0, 0.5);
  
  delta_factor3_cp ~ normal(0, delta_factor3_tau[factor3_to_factor2[factor3_cp_idx]]);
  delta_factor3_ncp ~ normal(0, 1);
  delta_factor3_tau ~ normal(0, 0.25);
}
text
data$factor1_cp_idx <- vector()
data$L_factor1_cp <- length(data$factor1_cp_idx)

data$factor1_ncp_idx <- setdiff(1:data$N_factor1_levels, data$factor1_cp_idx)
data$L_factor1_ncp <- length(data$factor1_ncp_idx)

data$factor2_cp_idx <- vector()
data$L_factor2_cp <- length(data$factor2_cp_idx)

data$factor2_ncp_idx <- setdiff(1:data$N_factor2_levels, data$factor2_cp_idx)
data$L_factor2_ncp <- length(data$factor2_ncp_idx)

data$factor3_cp_idx <- vector()
data$L_factor3_cp <- length(data$factor3_cp_idx)

data$factor3_ncp_idx <- setdiff(1:data$N_factor3_levels, data$factor3_cp_idx)
data$L_factor3_ncp <- length(data$factor3_ncp_idx)
text
fit <- stan(file='stan_programs/batch_ver3_prior.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

The tail on the calibration coefficients is starting to approach concern, with increased mass not only as extreme values above 10 but also increased mass at more moderately large values, such as those in the interval between 5 and 10. Given the informativeness of the likelihood function in the previous models, however, this prior model should be okay. That said we'll have to remain vigilant when investigating the posterior distribution for any signs of unacceptably degenerate inferences.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(exp(samples$log_psi[samples$log_psi < 4]),
     breaks=seq(0, 100, 0.25), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 25), xlab="Psi", yaxt='n', ylab="")

Our final Stan program incorporates the contributions to the heterogeneity in the calibration coefficients from all three nested factors.

text
writeLines(readLines("stan_programs/batch_ver3.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;      // Number of observations
  vector[N] log_rho_I; // Observed input signal
  int y[N];            // Observered output counts
  
  // First factor information
  int<lower=0> N_factor1_levels;
  
  int<lower=0, upper=N_factor1_levels> L_factor1_ncp;
  int<lower=1, upper=N_factor1_levels> factor1_ncp_idx[L_factor1_ncp];

  int<lower=0, upper=N_factor1_levels> L_factor1_cp;
  int<lower=1, upper=N_factor1_levels> factor1_cp_idx[L_factor1_cp];
  
  // Second factor information
  int<lower=0> N_factor2_levels;
  
  int<lower=0, upper=N_factor2_levels> L_factor2_ncp;
  int<lower=1, upper=N_factor2_levels> factor2_ncp_idx[L_factor2_ncp];

  int<lower=0, upper=N_factor2_levels> L_factor2_cp;
  int<lower=1, upper=N_factor2_levels> factor2_cp_idx[L_factor2_cp];
  
  // Third factor information
  int<lower=0> N_factor3_levels;
  
  int<lower=0, upper=N_factor3_levels> L_factor3_ncp;
  int<lower=1, upper=N_factor3_levels> factor3_ncp_idx[L_factor3_ncp];

  int<lower=0, upper=N_factor3_levels> L_factor3_cp;
  int<lower=1, upper=N_factor3_levels> factor3_cp_idx[L_factor3_cp];
  
  // Nesting configuration
  int<lower=1, upper=N_factor3_levels> obs_to_factor3[N];
  int<lower=1, upper=N_factor2_levels> factor3_to_factor2[N_factor3_levels];
  int<lower=1, upper=N_factor1_levels> factor2_to_factor1[N_factor2_levels];
}

parameters {  
  // Baseline
  real baseline;
  
  // Hierarchical model for the first factor residuals
  vector[L_factor1_ncp] delta_factor1_ncp;
  vector[L_factor1_cp] delta_factor1_cp;
  real<lower=0> delta_factor1_tau;
  
  // Hierarchical models for the second factor residuals
  vector[L_factor2_ncp] delta_factor2_ncp;
  vector[L_factor2_cp]  delta_factor2_cp;
  vector<lower=0>[N_factor1_levels] delta_factor2_tau;
  
  // Hierarchical models for the third factor residuals
  vector[L_factor3_ncp] delta_factor3_ncp;
  vector[L_factor3_cp]  delta_factor3_cp;
  vector<lower=0>[N_factor2_levels] delta_factor3_tau;
}

transformed parameters {
  vector[N_factor1_levels] delta_factor1;
  vector[N_factor2_levels] delta_factor2;
  vector[N_factor3_levels] delta_factor3;

  vector[N_factor3_levels] log_psi;

  // Reconstruct first factor residuals
  delta_factor1[factor1_ncp_idx] = delta_factor1_tau * delta_factor1_ncp;
  delta_factor1[factor1_cp_idx] = delta_factor1_cp;

  // Reconstruct second factor residuals
  delta_factor2[factor2_ncp_idx] 
    =   delta_factor2_tau[factor2_to_factor1[factor2_ncp_idx]] .* delta_factor2_ncp;
  delta_factor2[factor2_cp_idx] = delta_factor2_cp;

  // Reconstruct third factor residuals
  delta_factor3[factor3_ncp_idx] 
    =   delta_factor3_tau[factor3_to_factor2[factor3_ncp_idx]] .* delta_factor3_ncp;
  delta_factor3[factor3_cp_idx] = delta_factor3_cp;
  
  log_psi =  baseline
           + delta_factor1[factor2_to_factor1[factor3_to_factor2]]
           + delta_factor2[factor3_to_factor2]
           + delta_factor3;
}

model {  
  baseline ~ normal(0, 1);

  delta_factor1_cp ~ normal(0, delta_factor1_tau);
  delta_factor1_ncp ~ normal(0, 1);
  delta_factor1_tau ~ normal(0, 1);
    
  delta_factor2_cp ~ normal(0, delta_factor2_tau[factor2_to_factor1[factor2_cp_idx]]);
  delta_factor2_ncp ~ normal(0, 1);
  delta_factor2_tau ~ normal(0, 0.5);
  
  delta_factor3_cp ~ normal(0, delta_factor3_tau[factor3_to_factor2[factor3_cp_idx]]);
  delta_factor3_ncp ~ normal(0, 1);
  delta_factor3_tau ~ normal(0, 0.25);
  
  y ~ poisson_log(log_psi[obs_to_factor3] + log_rho_I);
}

generated quantities {
  int y_post_pred[N] = poisson_log_rng(log_psi[obs_to_factor3] + log_rho_I);
  real F_post_pred = F_stat(to_vector(y_post_pred) ./ exp(log_rho_I), 
                            N, obs_to_factor3, N_factor3_levels);
}

Because the Factor 2 hierarchical parameters performed well with a non-centered parameterization the Factor 3 hierarchical parameters, which are even less informed by the likelihood function, should also be suited to a non-centered parameterization.

text
data$factor1_cp_idx <- 1:data$N_factor1_levels
data$L_factor1_cp <- length(data$factor1_cp_idx)

data$factor1_ncp_idx <- setdiff(1:data$N_factor1_levels, data$factor1_cp_idx)
data$L_factor1_ncp <- length(data$factor1_ncp_idx)

data$factor2_cp_idx <- vector()
data$L_factor2_cp <- length(data$factor2_cp_idx)

data$factor2_ncp_idx <- setdiff(1:data$N_factor2_levels, data$factor2_cp_idx)
data$L_factor2_ncp <- length(data$factor2_ncp_idx)

data$factor3_cp_idx <- vector()
data$L_factor3_cp <- length(data$factor3_cp_idx)

data$factor3_ncp_idx <- setdiff(1:data$N_factor3_levels, data$factor3_cp_idx)
data$L_factor3_ncp <- length(data$factor3_ncp_idx)
text
fit <- stan(file='stan_programs/batch_ver3.stan',
            data=data, init_r=1, seed=4838282, refresh=1000)

Indeed there are no hints of computational problems.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

But what about the posterior retrodictive checks? It doesn't get much better than this for the FF statistic, indicating that we've finally incorporated enough variation in the calibration coefficients. At least, that is, given the resolution of the observed data.

text
samples <- extract(fit)

par(mfrow=c(1, 1))

hist(samples$F_post_pred, breaks=seq(3000, 7000, 50),
     main="Posterior Retrodictive Checks",
     col=c_dark, border=c_dark_highlight,
     xlim=c(3000, 7000), xlab="F Statistic", yaxt='n', ylab="")
abline(v=F_obs, col="white", lty=1, lw=3)
abline(v=F_obs, col="black", lty=1, lw=2)

At the same time posterior retrodiction distribution for the binned data now aligns well with the observed histogram. While there are various fluctuations there are no systematic deviations that indicate serious model deficiencies.

text
B <- 126
breaks <- seq(-0.5, B - 0.5, 1)

idx <- rep(1:B, each=2)
xs <- sapply(1:length(idx), function(b) if(b %% 2 == 0) idx[b] + 0.5 else idx[b] - 0.5)

obs <- hist(data$y, breaks=breaks, plot=FALSE)$counts
pad_obs <- do.call(cbind, lapply(idx, function(n) obs[n]))

post_pred <- sapply(1:4000, function(n) hist(samples$y_post_pred[n,], breaks=breaks, plot=FALSE)$counts)
probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:B, function(b) quantile(post_pred[b,], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

plot(1, type="n", main="Posterior Retrodictive Distribution",
     xlim=c(-0.5, B - 0.5), xlab="y",
     ylim=c(0, max(c(obs, cred[9,]))), ylab="")

polygon(c(xs, rev(xs)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(xs, rev(xs)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
lines(xs, pad_cred[5,], col=c_dark, lwd=2)

lines(xs, pad_obs, col="white", lty=1, lw=2.5)
lines(xs, pad_obs, col="black", lty=1, lw=2)

Confident in the adequacy of our model we can now start looking through the posterior inferences, starting with the baseline parameter.

text
par(mfrow=c(1, 1), mar=c(5, 1, 3, 1))

hist(samples$baseline, breaks=seq(-3, 3, 0.1), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(-3, 3), xlab="Baseline", yaxt='n', ylab="")

The posterior distribution for all of the calibration coefficients spans a pretty wide range of values; if we were expecting precision instruments then we might need to consider another supplier! At the same time the clustering is characteristic of the systematic trends across the nested factor levels.

text
par(mfrow=c(1, 1), mar=c(5, 3, 3, 1))

hist(exp(samples$log_psi), breaks=seq(0, 1.25, 0.025), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 1.25), xlab="psi", yaxt='n', ylab="")

That said with our calibration data and full model we can separate the different contributions to this heterogeneity relatively well. First we can infer the variation common to each shipment.

text
layout(matrix(c(1, 1, 2), nrow=1))

L <- data$N_factor1_levels
idx <- rep(1:L, each=2)
x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:L, function(l)
  quantile(samples$delta_factor1[,l], probs=probs))
pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

mean_tau <- mean(samples$delta_factor1_tau)

lb <- min(c(-2.25 * mean_tau, cred[1,]))
ub <- max(c(+2.25 * mean_tau, cred[9,]))

par(mar=c(5, 5, 3, 1))
plot(1, type="n", main="Shipment Heterogenity",
     xlim=c(0.5, L + 0.5), xlab="", xaxt="n",
     ylim=c(lb, ub), ylab="Marginal Posterior")

lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
        col = c_light, border = NA)
polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
        col = c_mid, border = NA)
polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
        col = c_mid_highlight, border = NA)
for (l in 1:L)
  lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

axis(1, at=1:L, labels=sapply(1:L, function(l) paste("l1_", l, sep="")))

par(mar=c(5, 1, 3, 1))
u <- 1.25 * max(samples$delta_factor1_tau)
hist(samples$delta_factor1_tau, breaks=seq(0, u, u / 50), main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
abline(v=mean_tau, col="gray80", lwd=2, lty=3)

Then we can investigate the variations common to each detector.

text
for (l1 in 1:data$N_factor1_levels) {
  layout(matrix(c(1, 1, 2), nrow=1))

  level_idx <- which(data$factor2_to_factor1 == l1)
  L <- length(level_idx)
  idx <- rep(1:L, each=2)
  x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

  probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
  cred <- sapply(level_idx, function(l)
    quantile(samples$delta_factor2[,l], probs=probs))
  pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

  mean_tau <- mean(samples$delta_factor2_tau[,l1])

  lb <- min(c(-2.25 * mean_tau, cred[1,]))
  ub <- max(c(+2.25 * mean_tau,cred[9,]))

  title <- paste("Detector Heterogeneity Within Shipment", l1)

  par(mar=c(5, 5, 3, 1))
  plot(1, type="n", main=title,
       xlim=c(0.5, L + 0.5), xlab="", xaxt="n",
       ylim=c(lb, ub), ylab="Marginal Posterior")

  lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

  polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
          col = c_light, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
          col = c_light_highlight, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
          col = c_mid, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
          col = c_mid_highlight, border = NA)
  for (l in 1:L)
    lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

  axis(1, at=1:L, sapply(level_idx, function(l) paste("l2_", l, sep="")))

  par(mar=c(5, 1, 3, 1))
  u <- 1.25 * max(samples$delta_factor2_tau[,l1])
  hist(samples$delta_factor2_tau[,l1], breaks=seq(0, u, u / 50), main="",
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
  abline(v=mean_tau, col="gray80", lwd=2, lty=3)
}

Finally we learn the variations within each detector.

text
for (l2 in 1:data$N_factor2_levels) {
  layout(matrix(c(1, 1, 2), nrow=1))

  level_idx <- which(data$factor3_to_factor2 == l2)
  L <- length(level_idx)
  idx <- rep(1:L, each=2)
  x <- sapply(1:length(idx), function(l) if(l %% 2 == 0) idx[l] + 0.5 else idx[l] - 0.5)

  probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
  cred <- sapply(level_idx, function(l)
    quantile(samples$delta_factor3[,l], probs=probs))
  pad_cred <- do.call(cbind, lapply(idx, function(n) cred[1:9, n]))

  mean_tau <- mean(samples$delta_factor3_tau[,l2])

  lb <- min(c(-2.25 * mean_tau, cred[1,]))
  ub <- max(c(+2.25 * mean_tau, cred[9,]))

  title <- paste("Spatial Heterogeneity Within Detector", l2)

  par(mar=c(5, 5, 3, 1))
  plot(1, type="n", main=title,
       xlim=c(0.5, L + 0.5), xlab="", xaxt="n",
       ylim=c(lb, ub), ylab="Marginal Posterior")

  lines(c(0.5, L + 0.5), c(2 * mean_tau, 2 * mean_tau), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(0, 0), col="gray80", lwd=3, lty=2)
  lines(c(0.5, L + 0.5), c(-2 * mean_tau, -2 * mean_tau), col="gray80", lwd=3, lty=2)

  polygon(c(x, rev(x)), c(pad_cred[1,], rev(pad_cred[9,])),
          col = c_light, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[2,], rev(pad_cred[8,])),
          col = c_light_highlight, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[3,], rev(pad_cred[7,])),
          col = c_mid, border = NA)
  polygon(c(x, rev(x)), c(pad_cred[4,], rev(pad_cred[6,])),
          col = c_mid_highlight, border = NA)
  for (l in 1:L)
    lines(x[(2*l-1):(2*l)], pad_cred[5,(2*l-1):(2*l)], col=c_dark, lwd=2)

  axis(1, at=1:L, sapply(level_idx, function(l) paste("l2_", l, sep="")))

  par(mar=c(5, 1, 3, 1))
  u <- 1.25 * max(samples$delta_factor3_tau[,l2])
  hist(samples$delta_factor3_tau[,l2], breaks=seq(0, u, u / 50), main="",
       col=c_dark, border=c_dark_highlight,
       xlim=c(0, u), xlab="Population Scale", yaxt='n', ylab="")
  abline(v=mean_tau, col="gray80", lwd=2, lty=3)
}

The detector performance may not be as consistent as we might have hoped, and we still don't know why the performance varies so strongly. These precise inferences from the calibration data and the nested multifactor model, however, does allow us individually calibrate each detector, correcting for the heterogeneous behavior well enough that the detectors should be useful as more than just door stops.

5.2 Quality Assurance

Consider an industrial setting where we are responsible for understanding how well a new manufacturing process performs in factories across the world. This manufacturing process consumes some input material to produce some manufactured good, but the process isn't perfect. With some probability a manufactured item will fail quality assurance and have to be discarded.

One concern with this new process is that the probability of passing quality assurance standards is expected to decay with time due to wear and tear on the mechanical components of the new technology. This decay, however, may not be constant. For example environmental factors at each factory location might accelerate or decelerate the attrition of the machines. Similarly the decay might vary over the different maintenance methods used by different operators. At the same time different sources of the input material might introduce different contaminants that could influence the decay.

To get a handle on all of these contributions performance data have been collected at multiple factories.

text
data <- read_rdump('data/qa.data.R')

names(data)
text
 [1] "method_idx"        "t"                 "y"                
 [4] "N_source"          "N_location"        "location_idx"     
 [7] "factor_config_idx" "N_samples"         "N"                
[10] "N_method"          "source_idx"        "N_factor_configs" 

In total the observations span data$N_factor_configs = 250 different configurations of the three observed factors -- N_location = 9 different factory locations, N_method = 5 different maintenance methods, and N_source = 7 different sources of the input material. The data collection was designed to cover the levels in each of these main factors relatively uniformly, although that may not be representative of the conditions under which the process might be implemented in full production.

text
par(mfrow=c(3, 1))
par(mar=c(5, 5, 3, 1))

hist(data$location_idx,
     breaks=seq(0.5, data$N_location + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_location + 0.5), xlab="Location Levels",
     ylim=c(0, 40), ylab="Number of\nObservations")

hist(data$method_idx,
     breaks=seq(0.5, data$N_method + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_method+ 0.5), xlab="Method Levels",
     ylim=c(0, 60), ylab="Number of\nObservations")

hist(data$source_idx,
     breaks=seq(0.5, data$N_source + 0.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(0.5, data$N_source + 0.5), xlab="Source Levels",
     ylim=c(0, 50), ylab="Number of\nObservations")

That said note that the 250 observed factor configurations are less than the N_locations * N_methods * N_sources = 360 full interaction levels. Consequently we can't infer the behavior of each possible factor configuration independently.

In each of the 250 contexts identical manufacturing equipment was installed and measurements were taken about every three months over the course of a year of production. Each individual measurement applied quality assurance testing to N_samples = 25 items randomly selected from the production line, recording the number of passing items y.

text
par(mfrow=c(1, 3))

hist(data$y, breaks=seq(-0.5, 25.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(-0.5, 25.5), xlab="Passing Items",
     ylim=c(0, 100), yaxt='n', ylab="")

hist(data$t, breaks=seq(-10.5, 370.5, 1),
     main="", col=c_dark, border=c_dark_highlight,
     xlim=c(-10.5, 370.5), xlab="Observation Times\n(Days Since Installation)",
     ylim=c(0, 125), yaxt='n', ylab="")

plot(data$t, data$y, type="p", pch=16, col=c_dark,
     xlim=c(-10.5, 370.5), xlab="Observation Times\n(Days Since Installation)",
     ylim=c(-0.5, 25.5), ylab="Passing Items")

To facilitate fitting an overlapping multifactor model we have to organize the three main factors into a matrix.

text
data$N_main_factors <- 3
data$N_main_factor_levels <- c(data$N_location, data$N_method, data$N_source)
data$main_factor_level_idx <- rbind(data$location_idx, data$method_idx, data$source_idx)

Now we can programmatically construct the first and second-order interactions.

text
inter_data <-  NULL
inter_data$N <- data$N_factor_configs
inter_data$N_main_factors <- data$N_main_factors
inter_data$N_main_factor_levels <- data$N_main_factor_levels
inter_data$main_factor_level_idx <- data$main_factor_level_idx

inter <- stan(file='stan_programs/construct_inter_idx_general.stan',
              data=inter_data, iter=1, warmup=0, chains=1,
              algorithm="Fixed_param")
text
DIAGNOSTIC(S) FROM PARSER:
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * N_main_factors * N_main_factors - 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: N_main_factors * i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i * i + 1 / 6
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: j - 1 * j / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i * i + 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * N_main_factors * N_main_factors - 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: N_main_factors * i - 1 * i / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i - 1 * i * i + 1 / 6
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: j - 1 * j / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.
Info: integer division implicitly rounds to integer. Found int division: i * i + 1 / 2
 Positive values rounded down, negative values rounded up or down in platform-dependent way.


SAMPLING FOR MODEL 'construct_inter_idx_general' NOW (CHAIN 1).
Chain 1: Iteration: 1 / 1 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0 seconds (Warm-up)
Chain 1:                5.8e-05 seconds (Sampling)
Chain 1:                5.8e-05 seconds (Total)
Chain 1: 
text
inter_output <- extract(inter)

data$N_inter1_factors <- inter_output$N_inter1_factors[1]
data$N_inter1_factor_levels <- array(inter_output$N_inter1_factor_levels[1,])
data$inter1_factor1_idx <- inter_output$inter1_factor1_idx[1,]
data$inter1_factor2_idx <- inter_output$inter1_factor2_idx[1,]
data$inter1_factor_level_idx <- inter_output$inter1_factor_level_idx[1,,]
dim(data$inter1_factor_level_idx) <- c(data$N_inter1_factors, data$N_factor_configs)

data$N_inter2_factors <- inter_output$N_inter2_factors[1]
data$N_inter2_factor_levels <- array(inter_output$N_inter2_factor_levels[1,])
data$inter2_factor1_idx <- inter_output$inter2_factor1_idx[1,]
data$inter2_factor2_idx <- inter_output$inter2_factor2_idx[1,]
data$inter2_factor3_idx <- inter_output$inter2_factor3_idx[1,]
data$inter2_factor_level_idx <- inter_output$inter2_factor_level_idx[1,,]
dim(data$inter2_factor_level_idx) <- c(data$N_inter2_factors, data$N_factor_configs)

While we're here let's give everything readable names.

text
main_factor_names <- c("Location Factor", "Method Factor", "Source Factor")
inter1_factor_names <- c("Location/Method Factor", "Location/Source Factor", "Method/Source Factor")
inter2_factor_names <- c("Location/Method/Source Factor")

Finally we can pack all of the main and interaction factors into one-dimensional arrays to facilitate specifying the overlapping factor models in Stan.

text
pack <- stan(file='stan_programs/pack_idx.stan', data=data,
             iter=1, warmup=0, chains=1, algorithm="Fixed_param")
text
SAMPLING FOR MODEL 'pack_idx' NOW (CHAIN 1).
Chain 1: Iteration: 1 / 1 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0 seconds (Warm-up)
Chain 1:                3.2e-05 seconds (Sampling)
Chain 1:                3.2e-05 seconds (Total)
Chain 1: 
text
pack_output <- extract(pack)

data$N_all_main_factor_levels <- pack_output$N_all_main_factor_levels[1]
data$packed_main_factor_idx <- array(pack_output$packed_main_factor_idx[1,])
data$main_factor_start_idx <- array(pack_output$main_factor_start_idx[1,])
data$main_factor_end_idx <- array(pack_output$main_factor_end_idx[1,])

data$N_all_inter1_factor_levels <- pack_output$N_all_inter1_factor_levels[1]
data$packed_inter1_factor_idx <- array(pack_output$packed_inter1_factor_idx[1,])
data$inter1_factor_start_idx <- array(pack_output$inter1_factor_start_idx[1,])
data$inter1_factor_end_idx <- array(pack_output$inter1_factor_end_idx[1,])

data$N_all_inter2_factor_levels <- pack_output$N_all_inter2_factor_levels[1]
data$packed_inter2_factor_idx <- array(pack_output$packed_inter2_factor_idx[1,])
data$inter2_factor_start_idx <- array(pack_output$inter2_factor_start_idx[1,])
data$inter2_factor_end_idx <- array(pack_output$inter2_factor_end_idx[1,])

Before fitting an initial model we have to consider the summary statistics appropriate for posterior retrodictive checks. Our domain expertise suggests that any heterogeneity should manifest in the rate of performance decay, but it's not straightforward to construct summaries of the data that are directly sensitive to the rate of decay, especially with the variable measurement times.

One alternative is to look at measurements that were made on exactly the same day. By fixing the measurement time any heterogeneity in the decay will manifest as heterogeneity in the number of passing items which will then increase the value of the corresponding FF statistic. Because most of the measurements are made quarterly let's make posterior retrodictive checks every 90 days.

text
data$N_checks <- 5

q0_obs <- which(data$t == 0)
q1_obs <- which(data$t == 90)
q2_obs <- which(data$t == 180)
q3_obs <- which(data$t == 270)
q4_obs <- which(data$t == 360)

data$N_check_obs <- min(c(length(q0_obs), length(q1_obs),
                          length(q2_obs), length(q3_obs),
                          length(q4_obs)))
data$check_idx <- matrix(0, nrow=data$N_checks, data$N_check_obs)
data$check_idx[1,] <- sample(q0_obs, data$N_check_obs)
data$check_idx[2,] <- sample(q1_obs, data$N_check_obs)
data$check_idx[3,] <- sample(q2_obs, data$N_check_obs)
data$check_idx[4,] <- sample(q3_obs, data$N_check_obs)
data$check_idx[5,] <- sample(q4_obs, data$N_check_obs)

By restricting the posterior retrodictive checks to the measurements collected only on the same day we do limit how well we'll be able to resolve any deviant behavior, especially with regard to the factor heterogeneity.

text
writeLines(readLines("stan_programs/qa_f_stat.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;                     // Number of observations
  int<lower=0> N_samples;             // Number of items sampled at each observation
  int<lower=0, upper=N_samples> y[N]; // Number of passing items at each observation
  vector[N] t;                        // Observation times (days)
  
  // Days for conditional retrodictive checks
  int<lower=0> N_checks;
  int<lower=0> N_check_obs;
  int<lower=1, upper=N> check_idx[N_checks, N_check_obs]; 
  
  // Total factor configuration information
  int<lower=0> N_factor_configs;
  int<lower=0, upper=N_factor_configs> factor_config_idx[N];
  
  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N_factor_configs];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N_factor_configs];

  // Second-order factor interaction contributions logistics
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
  int<lower=1> inter2_factor_level_idx[N_inter2_factors, N_factor_configs];
}

generated quantities {
  real F_main_obs[N_main_factors, N_checks];
  real F_inter1_obs[N_inter1_factors, N_checks];
  real F_inter2_obs[N_inter2_factors, N_checks];
  
  for (c in 1:N_checks) {
    int check_to_factor[N_check_obs] = factor_config_idx[check_idx[c]];
    
    for (f in 1:N_main_factors)
      F_main_obs[f, c] = F_stat(to_vector(y[check_idx[c]]), N_check_obs, 
                                main_factor_level_idx[f][check_to_factor], 
                                N_main_factor_levels[f]);
      
    for (f in 1:N_inter1_factors)
      F_inter1_obs[f, c] = F_stat(to_vector(y[check_idx[c]]), N_check_obs,
                                  inter1_factor_level_idx[f][check_to_factor], 
                                  N_inter1_factor_levels[f]);
    for (f in 1:N_inter2_factors)
      F_inter2_obs[f, c] = F_stat(to_vector(y[check_idx[c]]), N_check_obs, 
                                  inter2_factor_level_idx[f][check_to_factor], 
                                  N_inter2_factor_levels[f]);  
  }
}
text
fit <- stan(file='stan_programs/qa_f_stat.stan', data=data, seed=93585393,
            iter=1, warmup=0, chains=1, algorithm="Fixed_param")
text
SAMPLING FOR MODEL 'qa_f_stat' NOW (CHAIN 1).
Chain 1: Iteration: 1 / 1 [100%]  (Sampling)
Chain 1: 
Chain 1:  Elapsed Time: 0 seconds (Warm-up)
Chain 1:                0.000233 seconds (Sampling)
Chain 1:                0.000233 seconds (Total)
Chain 1: 
text
F_main_obs <- extract(fit)$F_main_obs[1,,]
F_inter1_obs <- extract(fit)$F_inter1_obs[1,,]
F_inter2_obs <- extract(fit)$F_inter2_obs[1,,]

Now we're ready to start modeling. Let's begin without any heterogeneity and assume that the rate of decay is constant across all measurements.

Our domain expertise motivates high success probabilities upon installation with significant decay possible over the course of a year. To ensure that our prior model is reasonable we can plot the evolution of the success probability for model configurations sampled from the prior distribution.

text
data$fine_t <- 10*(1:37)
data$N_fine_t <- length(data$fine_t)
text
writeLines(readLines("stan_programs/qa_ver0_prior.stan"))
text
data {
  int<lower=0> N_fine_t;
  vector[N_fine_t] fine_t;
}

parameters {    
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Logit probability at time zero
  real alpha;
}

model {
  baseline ~ normal(-3, 2);
  alpha ~ normal(4, 2);
}

generated quantities {
  vector[N_fine_t] p = inv_logit(alpha + baseline * fine_t / 365.0);
}
text
fit <- stan(file='stan_programs/qa_ver0_prior.stan',
            data=data, seed=4838282, refresh=2000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

As is the case for any distribution over functions, we have to make a few compromises when visualizing the prior pushforward distribution over the success probability evolutions. On the left we plot an ensemble of some of the evolutions and on the right we plot marginal quantiles that provide a quantification of the range of point-wise behaviors.

Neither demonstrates any behavior that strongly conflicts with our domain expertise.

text
samples <- extract(fit)

par(mfrow=c(1, 2))

library(colormap)
nom_colors <- c("#DCBCBC", "#C79999", "#B97C7C", "#A25050", "#8F2727", "#7C0000")

plot_idx <- seq(1, 1000, 10)
N_plot <- length(plot_idx)
line_colors <- colormap(colormap=nom_colors, nshades=N_plot)

plot(1, type="n", main="Spaghetti",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
for (n in 1:N_plot)
  lines(data$fine_t, samples$p[plot_idx[n],], col=line_colors[n], lwd=2)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:data$N_fine_t, function(n) quantile(samples$p[,n], probs=probs))

plot(1, type="n", main="Quantile Ribbons",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[1,], rev(cred[9,])),
        col = c_light, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[2,], rev(cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[3,], rev(cred[7,])),
        col = c_mid, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[4,], rev(cred[6,])),
        col = c_mid_highlight, border = NA)
lines(data$fine_t, cred[5,], col=c_dark, lwd=2)

We then continue by incorporating the observational model and fitting the corresponding posterior distribution.

text
writeLines(readLines("stan_programs/qa_ver0.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;                     // Number of observations
  int<lower=0> N_samples;             // Number of items sampled at each observation
  int<lower=0, upper=N_samples> y[N]; // Number of passing items at each observation
  vector[N] t;                        // Observation times (days)
  
  // Days for conditional retrodictive checks
  int<lower=0> N_checks;
  int<lower=0> N_check_obs;
  int<lower=1, upper=N> check_idx[N_checks, N_check_obs]; 
  
  // Timing for probability time evolution inferences
  int<lower=0> N_fine_t;
  vector[N_fine_t] fine_t;
  
  // Total factor configuration information
  int<lower=0> N_factor_configs;
  int<lower=0, upper=N_factor_configs> factor_config_idx[N];

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N_factor_configs];
}

parameters {
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Logit probability at time zero
  real alpha;
}

model {
  // Baseline contribution
  vector[N_factor_configs] kappa = rep_vector(baseline, N_factor_configs);
  
  baseline ~ normal(-3, 2);

  alpha ~ normal(4, 2);

  // Observational model -- slice across times for optimal vectorization
  y ~ binomial(N_samples, inv_logit(alpha + kappa[factor_config_idx] .* t / 365.0));
}

generated quantities {
  vector[N_fine_t] p[N_factor_configs];
  real F_main_post_pred[N_main_factors, N_checks];
  {
    int y_post_pred[N];
    vector[N_factor_configs] kappa =  rep_vector(baseline, N_factor_configs);
    
    for (c in 1:N_factor_configs)
      p[c] = inv_logit(alpha + kappa[c] * fine_t / 365.0);
    
    y_post_pred = binomial_rng(N_samples, 
                               inv_logit(alpha + kappa[factor_config_idx] .* t / 365.0));

    for (c in 1:N_checks) {
      int check_to_factor[N_check_obs] = factor_config_idx[check_idx[c]];
      
      for (f in 1:N_main_factors)
        F_main_post_pred[f, c] = F_stat(to_vector(y_post_pred[check_idx[c]]), 
                                        N_check_obs, 
                                        main_factor_level_idx[f][check_to_factor], 
                                        N_main_factor_levels[f]);
    }
  }
}
text
fit <- stan(file='stan_programs/qa_ver0.stan',
            data=data, seed=4838282, refresh=2000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

The computation looks okay so let's run the posterior retrodictive checks. Although these checks are not the most sensitive we do see a strong indication of heterogeneity across the location levels.

text
samples <- extract(fit)

par(mfrow=c(3, data$N_checks))
par(mar=c(5, 1, 3, 1))

lims <- c(200, 50, 50)

for (f in 1:3) {
  for (c in 1:data$N_checks) {
    title <- paste(main_factor_names[f], ",\n Check ", c, sep='')
    hist(samples$F_main_post_pred[, f, c], breaks=seq(0, 200, 1),
         main=title, col=c_dark, border=c_dark_highlight,
         xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
    abline(v=F_main_obs[f, c], col="white", lty=1, lw=3)
    abline(v=F_main_obs[f, c], col="black", lty=1, lw=2)       
  }
}

While we're suspicious of how well this model fits the observed data let's take a minute to examine its posterior inferences. The marginal posterior distribution for both the logit intercept \alpha and the baseline strongly contract from the prior model.

text
par(mfrow=c(1, 2))

hist(samples$baseline, breaks=seq(-7, 1, 0.2),  main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(-7, 1), xlab="Baseline Logit Slope", yaxt='n', ylab="")

hist(samples$alpha, breaks=seq(1.75, 2.25, 0.01),  main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(1.75, 2.25), xlab="Logit Intercept", yaxt='n', ylab="")

This implies that only a relatively small set of the success probability evolutions supported by the model are consistent with the observed data.

text
par(mfrow=c(1, 2))
par(mar=c(5, 5, 3, 1))

N_plot <- 100
line_colors <- colormap(colormap=nom_colors, nshades=N_plot)
config_plot_idx <- rep(20*(1:10), each=10)
sample_plot_idx <- rep(400*(1:10), 10)

plot(1, type="n", main="Spaghetti",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
for (n in 1:N_plot)
  lines(data$fine_t, samples$p[sample_plot_idx[n], config_plot_idx[n],],
        col=line_colors[n], lwd=2)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:data$N_fine_t, function(n) quantile(samples$p[,,n], probs=probs))

plot(1, type="n", main="Quantile Ribbons",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[1,], rev(cred[9,])),
        col = c_light, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[2,], rev(cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[3,], rev(cred[7,])),
        col = c_mid, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[4,], rev(cred[6,])),
        col = c_mid_highlight, border = NA)
lines(data$fine_t, cred[5,], col=c_dark, lwd=2)

The posterior retrodictive checks, however, are worrisome, especially when coupled with our domain expertise that factor heterogeneity is not unexpected. Consequently let's consider a first-order model where we add the main factor contributions.

Again we start with a prior pushforward check.

text
writeLines(readLines("stan_programs/qa_ver1_prior.stan"))
text
data {
  // Timing for probability time evolution inferences
  int<lower=0> N_fine_t;
  vector[N_fine_t] fine_t;
  
  // Total factor configuration information
  int<lower=0> N_factor_configs;

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N_factor_configs];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
}

parameters {
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // Logit probability at time zero
  real alpha;
}

model {
  // Baseline contribution
  baseline ~ normal(-3, 2);
  
  // Main factor contributions
  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 1);
  
  alpha ~ normal(4, 2);
}

generated quantities {
  vector[N_fine_t] p[N_factor_configs];
  {
    vector[N_factor_configs] kappa =  rep_vector(baseline, N_factor_configs);
    
    vector[N_all_main_factor_levels] packed_delta_main;
      
    packed_delta_main[main_ncp_idx] 
      = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
    packed_delta_main[main_cp_idx] = packed_delta_main_cp;
    
    for (f in 1:N_main_factors) {
      vector[N_main_factor_levels[f]] delta_main
        = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      kappa += delta_main[main_factor_level_idx[f]];
    }
    
    for (c in 1:N_factor_configs)
      p[c] = inv_logit(alpha + kappa[c] * fine_t / 365.0);
  }
}

We non-center the hierarchical parameters which are completely unconstrained by observations in the prior model.

text
data$main_cp_idx <- vector()
data$L_main_cp <- length(data$main_cp_idx)

data$main_ncp_idx <- setdiff(1:data$N_all_main_factor_levels, data$main_cp_idx)
data$L_main_ncp <- length(data$main_ncp_idx)
text
fit <- stan(file='stan_programs/qa_ver1_prior.stan',
            data=data, seed=4838282, refresh=2000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

By plotting a few prior samples for each of the sampled factor configurations we see some clustering in the prior pushforward spaghetti plot, although that substructure largely washes out in the marginal quantile ribbons.

text
samples <- extract(fit)

par(mfrow=c(1, 2))

N_plot <- 100
line_colors <- colormap(colormap=nom_colors, nshades=N_plot)
config_plot_idx <- rep(20*(1:10), each=10)
sample_plot_idx <- rep(400*(1:10), 10)

plot(1, type="n", main="Spaghetti",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
for (n in 1:N_plot)
  lines(data$fine_t, samples$p[sample_plot_idx[n], config_plot_idx[n],],
        col=line_colors[n], lwd=2)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:data$N_fine_t, function(n) quantile(samples$p[,,n], probs=probs))

plot(1, type="n", main="Quantile Ribbons",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[1,], rev(cred[9,])),
        col = c_light, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[2,], rev(cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[3,], rev(cred[7,])),
        col = c_mid, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[4,], rev(cred[6,])),
        col = c_mid_highlight, border = NA)
lines(data$fine_t, cred[5,], col=c_dark, lwd=2)

Either way the prior consequences look reasonable so we can continue on to the posterior distribution.

text
writeLines(readLines("stan_programs/qa_ver1.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;                     // Number of observations
  int<lower=0> N_samples;             // Number of items sampled at each observation
  int<lower=0, upper=N_samples> y[N]; // Number of passing items at each observation
  vector[N] t;                        // Observation times (days)
  
  // Days for conditional retrodictive checks
  int<lower=0> N_checks;
  int<lower=0> N_check_obs;
  int<lower=1, upper=N> check_idx[N_checks, N_check_obs]; 
  
  // Timing for probability time evolution inferences
  int<lower=0> N_fine_t;
  vector[N_fine_t] fine_t;
  
  // Total factor configuration information
  int<lower=0> N_factor_configs;
  int<lower=0, upper=N_factor_configs> factor_config_idx[N]; 

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N_factor_configs];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N_factor_configs];
}

parameters {
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // Logit probability at time zero
  real alpha;
}

transformed parameters {
  vector[N_all_main_factor_levels] packed_delta_main;
    
  packed_delta_main[main_ncp_idx] 
    = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
  packed_delta_main[main_cp_idx] = packed_delta_main_cp;
}

model {
  // Baseline contribution
  vector[N_factor_configs] kappa = rep_vector(baseline, N_factor_configs);
  
  baseline ~ normal(-3, 2);
  
  // Main factor contributions
  for (f in 1:N_main_factors) {
    vector[N_main_factor_levels[f]] delta_main
      = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
    kappa += delta_main[main_factor_level_idx[f]];
  }
  
  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 1);
  
  alpha ~ normal(4, 2);

  // Observational model
  y ~ binomial(N_samples, inv_logit(alpha + kappa[factor_config_idx] .* t / 365.0));
}

generated quantities {
  vector[N_fine_t] p[N_factor_configs];
  real F_main_post_pred[N_main_factors, N_checks];
  real F_inter1_post_pred[N_inter1_factors, N_checks];
  {
    int y_post_pred[N];
    vector[N_factor_configs] kappa =  rep_vector(baseline, N_factor_configs);
    
    for (f in 1:N_main_factors) {
      vector[N_main_factor_levels[f]] delta_main
        = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      kappa += delta_main[main_factor_level_idx[f]];
    }
    
    for (c in 1:N_factor_configs)
      p[c] = inv_logit(alpha + kappa[c] * fine_t / 365.0);
    
    y_post_pred = binomial_rng(N_samples, 
                               inv_logit(alpha + kappa[factor_config_idx] .* t / 365.0));
  
    for (c in 1:N_checks) {
      int check_to_factor[N_check_obs] = factor_config_idx[check_idx[c]];
      
      for (f in 1:N_main_factors) {
        F_main_post_pred[f, c] = F_stat(to_vector(y_post_pred[check_idx[c]]), 
                                        N_check_obs, 
                                        main_factor_level_idx[f][check_to_factor], 
                                        N_main_factor_levels[f]);
      }
      for (f in 1:N_inter1_factors) {
        F_inter1_post_pred[f, c] = F_stat(to_vector(y_post_pred[check_idx[c]]),
                                          N_check_obs,
                                          inter1_factor_level_idx[f][check_to_factor], 
                                          N_inter1_factor_levels[f]);
      }
    }
  }
}

Note that we maintain the non-centered parameterization that we used in the prior fit.

text
fit <- stan(file='stan_programs/qa_ver1.stan',
            data=data, seed=4838282, refresh=2000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

With no indications of computational problems let's consult the posterior retrodictive checks as we are wont to do. Adding heterogeneity across the main factors has resolved the posterior retrodictive discrepancy that we saw in the previous model.

text
samples <- extract(fit)

par(mfrow=c(3, data$N_checks))
par(mar=c(5, 1, 3, 1))

lims <- c(600, 50, 50)
deltas <- c(10, 1, 1)

for (f in 1:3) {
  for (c in 1:data$N_checks) {
    title <- paste(main_factor_names[f], ",\n Check ", c, sep='')
    hist(samples$F_main_post_pred[, f, c], breaks=seq(0, 1000, deltas[f]),
         main=title, col=c_dark, border=c_dark_highlight,
         xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
    abline(v=F_main_obs[f, c], col="white", lty=1, lw=3)
    abline(v=F_main_obs[f, c], col="black", lty=1, lw=2)
  }
}

The posterior retrodictive behavior across the first-order interaction factors is harder to judge given the limited sensitivity of our summary statistic. That said there are weak signs of trouble in the method/source interactions.

text
par(mfrow=c(3, data$N_checks))
lims <- c(700, 700, 100)
deltas <- c(20, 20, 1)

for (f in 1:3) {
  for (c in 1:data$N_checks) {
    title <- paste(inter1_factor_names[f], ",\n Check ", c, sep='')
    hist(samples$F_inter1_post_pred[, f, c], breaks=seq(0, 3000, deltas[f]),
         main=title, col=c_dark, border=c_dark_highlight,
         xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
    abline(v=F_inter1_obs[f, c], col="white", lty=1, lw=3)
    abline(v=F_inter1_obs[f, c], col="black", lty=1, lw=2)
  }
}

Putting our model adequacy concerns to the side for a second let's take a look at the posterior inferences for this model.

Note that the inferences for the baseline are now weaker -- this is not surprising as the introduction of the main factor heterogeneity impedes the direct influence of the data onto the baseline parameter.

text
par(mfrow=c(1, 2))

hist(samples$baseline, breaks=seq(-7, 1, 0.2),  main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(-7, 1), xlab="Baseline Logit Slope", yaxt='n', ylab="")

hist(samples$alpha, breaks=seq(1.75, 2.25, 0.01),  main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(1.75, 2.25), xlab="Logit Intercept", yaxt='n', ylab="")

The posterior distribution definitely takes advantage of the heterogeneity parameters, especially across the location levels.

text
plot_factor_posteriors("main", "Location Factor", 1)

text
plot_factor_posteriors("main", "Method Factor", 2)

text
plot_factor_posteriors("main", "Source Factor", 3)

The inferred heterogeneity across the main factor levels then manifests in clustered success probability evolutions.

text
par(mfrow=c(1, 2))
par(mar=c(5, 5, 3, 1))

N_plot <- 100
line_colors <- colormap(colormap=nom_colors, nshades=N_plot)
config_plot_idx <- rep(20*(1:10), each=10)
sample_plot_idx <- rep(400*(1:10), 10)

plot(1, type="n", main="Spaghetti",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
for (n in 1:N_plot)
  lines(data$fine_t, samples$p[sample_plot_idx[n], config_plot_idx[n],],
        col=line_colors[n], lwd=2)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:data$N_fine_t, function(n) quantile(samples$p[,,n], probs=probs))

plot(1, type="n", main="Quantile Ribbons",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[1,], rev(cred[9,])),
        col = c_light, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[2,], rev(cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[3,], rev(cred[7,])),
        col = c_mid, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[4,], rev(cred[6,])),
        col = c_mid_highlight, border = NA)
lines(data$fine_t, cred[5,], col=c_dark, lwd=2)

Can we do any better? Let's add the first-order interaction factors and see how much our fit improves, if at all. First we have to ensure that the added factors don't inflate our prior uncertainties to much.

text
writeLines(readLines("stan_programs/qa_ver2_prior.stan"))
text
data {
  // Timing for probability time evolution inferences
  int<lower=0> N_fine_t;
  vector[N_fine_t] fine_t;
  
  // Total factor configuration information
  int<lower=0> N_factor_configs;

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N_factor_configs];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N_factor_configs];
  
  int<lower=0> N_all_inter1_factor_levels;
  int<lower=1, upper=N_inter1_factors> packed_inter1_factor_idx[N_all_inter1_factor_levels];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_start_idx[N_inter1_factors];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_end_idx[N_inter1_factors];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_ncp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_ncp_idx[L_inter1_ncp];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_cp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_cp_idx[L_inter1_cp];
}

parameters {    
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // First-order factor interaction contributions
  vector[L_inter1_ncp] packed_delta_inter1_ncp;
  vector[L_inter1_cp] packed_delta_inter1_cp; 
  vector<lower=0>[N_inter1_factors] delta_inter1_tau;
  
  // Logit probability at time zero
  real alpha;
}

model {
  // Baseline contribution
  baseline ~ normal(-3, 2);
  
  // Main factor contributions
  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 1);
  
  // First-order factor interaction contributions
  packed_delta_inter1_ncp ~ normal(0, 1);
  packed_delta_inter1_cp ~ normal(0, delta_inter1_tau[packed_inter1_factor_idx[inter1_cp_idx]]);
  delta_inter1_tau ~ normal(0, 0.5);

  alpha ~ normal(4, 2);
}

generated quantities {
  vector[N_fine_t] p[N_factor_configs];
  {
    vector[N_factor_configs] kappa =  rep_vector(baseline, N_factor_configs);
    
    vector[N_all_main_factor_levels] packed_delta_main;
    vector[N_all_inter1_factor_levels] packed_delta_inter1;
      
    packed_delta_main[main_ncp_idx] 
      = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
    packed_delta_main[main_cp_idx] = packed_delta_main_cp;
    
    for (f in 1:N_main_factors) {
      vector[N_main_factor_levels[f]] delta_main
        = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      kappa += delta_main[main_factor_level_idx[f]];
    }
    
    packed_delta_inter1[inter1_ncp_idx] 
      = delta_inter1_tau[packed_inter1_factor_idx[inter1_ncp_idx]] .* packed_delta_inter1_ncp;
    packed_delta_inter1[inter1_cp_idx] = packed_delta_inter1_cp;
    
    for (f in 1:N_inter1_factors) {
      vector[N_inter1_factor_levels[f]] delta_inter1
        = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
      kappa += delta_inter1[inter1_factor_level_idx[f]];
    }
    
    for (c in 1:N_factor_configs)
      p[c] = inv_logit(alpha + kappa[c] * fine_t / 365.0);
  }
}
text
data$main_cp_idx <- vector()
data$L_main_cp <- length(data$main_cp_idx)

data$main_ncp_idx <- setdiff(1:data$N_all_main_factor_levels, data$main_cp_idx)
data$L_main_ncp <- length(data$main_ncp_idx)

data$inter1_cp_idx <- vector()
data$L_inter1_cp <- length(data$inter1_cp_idx)

data$inter1_ncp_idx <- setdiff(1:data$N_all_inter1_factor_levels,
                               data$inter1_cp_idx)
data$L_inter1_ncp <- length(data$inter1_ncp_idx)
text
fit <- stan(file='stan_programs/qa_ver2_prior.stan',
            data=data, seed=4838282, refresh=2000)
text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

While the prior pushforward distributions are a bit wider they're not so inflated to be a concern.

text
samples <- extract(fit)

par(mfrow=c(1, 2))

N_plot <- 100
line_colors <- colormap(colormap=nom_colors, nshades=N_plot)
config_plot_idx <- rep(20*(1:10), each=10)
sample_plot_idx <- rep(400*(1:10), 10)

plot(1, type="n", main="Spaghetti",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
for (n in 1:N_plot)
  lines(data$fine_t, samples$p[sample_plot_idx[n], config_plot_idx[n],],
        col=line_colors[n], lwd=2)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:data$N_fine_t, function(n) quantile(samples$p[,,n], probs=probs))

plot(1, type="n", main="Quantile Ribbons",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[1,], rev(cred[9,])),
        col = c_light, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[2,], rev(cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[3,], rev(cred[7,])),
        col = c_mid, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[4,], rev(cred[6,])),
        col = c_mid_highlight, border = NA)
lines(data$fine_t, cred[5,], col=c_dark, lwd=2)

And the posterior distribution?

text
writeLines(readLines("stan_programs/qa_ver2.stan"))
text
functions {
  real F_stat(vector y, int N, int[] indiv_idxs, int N_indiv) {
    real global_mean = 0;
    vector[N_indiv] total_counts = rep_vector(0, N_indiv);
    vector[N_indiv] running_counts = rep_vector(0, N_indiv);
    vector[N_indiv] means = rep_vector(0, N_indiv);
    vector[N_indiv] sum_squares = rep_vector(0, N_indiv);
    
    int N_min_occupunacy = 2; // Minimum occupuancy for included contexts
    real N_occupied = 0;      // Number of contexts with at least two counts
    real between = 0; // Empirical variance of empirical means in occupied contexts
    real within = 0;  // Empirical mean of emperical variances in occupied contexts

    for (n in 1:N) 
      total_counts[indiv_idxs[n]] += 1;
  
    for (n in 1:N) {
      int idx = indiv_idxs[n];
      real delta;
      
      // Skip (nearly) unoccupied contexts
      if (total_counts[idx] < N_min_occupunacy) continue;
      
      delta = y[n] - global_mean;
      global_mean += delta / n;

      running_counts[idx] += 1;
      delta = y[n] - means[idx];
      means[idx] += delta / running_counts[idx];
      sum_squares[idx] += (y[n] - means[idx]) * delta;
    }

    for (l in 1:N_indiv) {
      // Skip (nearly) unoccupied contexts
      if (total_counts[l] < N_min_occupunacy) continue;
      
      N_occupied += 1;
      between += total_counts[l] * square(means[l] - global_mean);
      within += (sum_squares[l] - within) / N_occupied;
    }
    
    // Return zero if not enough minimally occupied contexts
    if (N_occupied < 2) return 0; 
    
    between = between / (N_occupied - 1);
    within /= (N - N_occupied);
    return between / within;
  }
}

data {
  int<lower=0> N;                     // Number of observations
  int<lower=0> N_samples;             // Number of items sampled at each observation
  int<lower=0, upper=N_samples> y[N]; // Number of passing items at each observation
  vector[N] t;                        // Observation times (days)
  
  // Days for conditional retrodictive checks
  int<lower=0> N_checks;
  int<lower=0> N_check_obs;
  int<lower=1, upper=N> check_idx[N_checks, N_check_obs]; 
  
  // Timing for probability time evolution inferences
  int<lower=0> N_fine_t;
  vector[N_fine_t] fine_t;
  
  // Total factor configuration information
  int<lower=0> N_factor_configs;
  int<lower=0, upper=N_factor_configs> factor_config_idx[N];

  // Main factor contributions logistics
  int<lower=0> N_main_factors;
  int<lower=0> N_main_factor_levels[N_main_factors];
  int<lower=1> main_factor_level_idx[N_main_factors, N_factor_configs];
  
  int<lower=0> N_all_main_factor_levels;
  int<lower=1, upper=N_main_factors> packed_main_factor_idx[N_all_main_factor_levels];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_start_idx[N_main_factors];
  int<lower=1, upper=N_all_main_factor_levels> main_factor_end_idx[N_main_factors];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_ncp;
  int<lower=1, upper=N_all_main_factor_levels> main_ncp_idx[L_main_ncp];
  
  int<lower=0, upper=N_all_main_factor_levels> L_main_cp;
  int<lower=1, upper=N_all_main_factor_levels> main_cp_idx[L_main_cp];
  
  // First-order factor interaction contributions logistics
  int<lower=0> N_inter1_factors;
  int<lower=0> N_inter1_factor_levels[N_inter1_factors];
  int<lower=1> inter1_factor_level_idx[N_inter1_factors, N_factor_configs];
  
  int<lower=0> N_all_inter1_factor_levels;
  int<lower=1, upper=N_inter1_factors> packed_inter1_factor_idx[N_all_inter1_factor_levels];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_start_idx[N_inter1_factors];
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_factor_end_idx[N_inter1_factors];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_ncp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_ncp_idx[L_inter1_ncp];
  
  int<lower=0, upper=N_all_inter1_factor_levels> L_inter1_cp;
  int<lower=1, upper=N_all_inter1_factor_levels> inter1_cp_idx[L_inter1_cp];

  // Second-order factor interaction contributions logistics
  int<lower=0> N_inter2_factors;
  int<lower=0> N_inter2_factor_levels[N_inter2_factors];
  int<lower=1> inter2_factor_level_idx[N_inter2_factors, N_factor_configs];
}

parameters {    
  // Zeroth-order contribution (Baseline)
  real baseline;
  
  // Main factor contributions
  vector[L_main_ncp] packed_delta_main_ncp;
  vector[L_main_cp] packed_delta_main_cp; 
  vector<lower=0>[N_main_factors] delta_main_tau;
  
  // First-order factor interaction contributions
  vector[L_inter1_ncp] packed_delta_inter1_ncp;
  vector[L_inter1_cp] packed_delta_inter1_cp; 
  vector<lower=0>[N_inter1_factors] delta_inter1_tau;
  
  // Logit probability at time zero
  real alpha;
}

transformed parameters {
  vector[N_all_main_factor_levels] packed_delta_main;
  vector[N_all_inter1_factor_levels] packed_delta_inter1;
    
  packed_delta_main[main_ncp_idx] 
    = delta_main_tau[packed_main_factor_idx[main_ncp_idx]] .* packed_delta_main_ncp;
  packed_delta_main[main_cp_idx] = packed_delta_main_cp;
  
  packed_delta_inter1[inter1_ncp_idx] 
    = delta_inter1_tau[packed_inter1_factor_idx[inter1_ncp_idx]] .* packed_delta_inter1_ncp;
  packed_delta_inter1[inter1_cp_idx] = packed_delta_inter1_cp;
}

model {
  // Baseline contribution
  vector[N_factor_configs] kappa = rep_vector(baseline, N_factor_configs);
  
  baseline ~ normal(-3, 2);
  
  // Main factor contributions
  for (f in 1:N_main_factors) {
    vector[N_main_factor_levels[f]] delta_main
      = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
    kappa += delta_main[main_factor_level_idx[f]];
  }
  
  packed_delta_main_ncp ~ normal(0, 1);
  packed_delta_main_cp ~ normal(0, delta_main_tau[packed_main_factor_idx[main_cp_idx]]);
  delta_main_tau ~ normal(0, 1);
  
  // First-order factor interaction contributions
  for (f in 1:N_inter1_factors) {
    vector[N_inter1_factor_levels[f]] delta_inter1
      = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
    kappa += delta_inter1[inter1_factor_level_idx[f]];
  }
  
  packed_delta_inter1_ncp ~ normal(0, 1);
  packed_delta_inter1_cp ~ normal(0, delta_inter1_tau[packed_inter1_factor_idx[inter1_cp_idx]]);
  delta_inter1_tau ~ normal(0, 0.5);

  alpha ~ normal(4, 2);

  // Observational model
  y ~ binomial(N_samples, inv_logit(alpha + kappa[factor_config_idx] .* t / 365.0));
}

generated quantities {
  vector[N_fine_t] p[N_factor_configs];
  real F_main_post_pred[N_main_factors, N_checks];
  real F_inter1_post_pred[N_inter1_factors, N_checks];
  real F_inter2_post_pred[N_inter2_factors, N_checks];
  {
    int y_post_pred[N];
    vector[N_factor_configs] kappa =  rep_vector(baseline, N_factor_configs);

    for (f in 1:N_main_factors) {
      vector[N_main_factor_levels[f]] delta_main
        = packed_delta_main[main_factor_start_idx[f]:main_factor_end_idx[f]];
      kappa += delta_main[main_factor_level_idx[f]];
    }
    
    for (f in 1:N_inter1_factors) {
      vector[N_inter1_factor_levels[f]] delta_inter1
        = packed_delta_inter1[inter1_factor_start_idx[f]:inter1_factor_end_idx[f]];
      kappa += delta_inter1[inter1_factor_level_idx[f]];
    }
    
    for (c in 1:N_factor_configs)
      p[c] = inv_logit(alpha + kappa[c] * fine_t / 365.0);
    
    y_post_pred = binomial_rng(N_samples, 
                               inv_logit(alpha + kappa[factor_config_idx] .* t / 365.0));
  
    for (c in 1:N_checks) {
      int check_to_factor[N_check_obs] = factor_config_idx[check_idx[c]];
      
      for (f in 1:N_main_factors) {
        F_main_post_pred[f, c] = F_stat(to_vector(y_post_pred[check_idx[c]]), 
                                        N_check_obs, 
                                        main_factor_level_idx[f][check_to_factor], 
                                        N_main_factor_levels[f]);
      }
      for (f in 1:N_inter1_factors) {
        F_inter1_post_pred[f, c] = F_stat(to_vector(y_post_pred[check_idx[c]]),
                                          N_check_obs,
                                          inter1_factor_level_idx[f][check_to_factor], 
                                          N_inter1_factor_levels[f]);
      }
      for (f in 1:N_inter2_factors) {
        F_inter2_post_pred[f, c] = F_stat(to_vector(y_post_pred[check_idx[c]]), 
                                          N_check_obs, 
                                          inter2_factor_level_idx[f][check_to_factor], 
                                          N_inter2_factor_levels[f]);  
      }
    }
  }
}
text
data$main_cp_idx <- vector()
data$L_main_cp <- length(data$main_cp_idx)

data$main_ncp_idx <- setdiff(1:data$N_all_main_factor_levels, data$main_cp_idx)
data$L_main_ncp <- length(data$main_ncp_idx)

data$inter1_cp_idx <- vector()
data$L_inter1_cp <- length(data$inter1_cp_idx)

data$inter1_ncp_idx <- setdiff(1:data$N_all_inter1_factor_levels, data$inter1_cp_idx)
data$L_inter1_ncp <- length(data$inter1_ncp_idx)
text
fit <- stan(file='stan_programs/qa_ver2.stan',
            data=data, seed=4838282, refresh=2000)

In the words of the great philosopher Cathy: ACK!.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "3 of 4000 iterations ended with a divergence (0.075%)"
[1] "  Try running with larger adapt_delta to remove the divergences"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

We don't get discouraged but instead diligently track those divergences down.

text
partition <- util$partition_div(fit)
div_samples <- partition[[1]]
nondiv_samples <- partition[[2]]

With only three divergent transitions we'll have to consider the geometry of the non-divergent samples just as much as the divergent samples. Within the location factor the level 4 parameter looks a bit more extended than the rest.

text
f <- 1
par(mfrow=c(3, 3))
par(mar=c(5, 5, 3, 1))

for (l in data$main_factor_start_idx[f]:data$main_factor_end_idx[f]) {
  if (l %in% data$main_cp_idx) {
    cp_idx <- which(l == data$main_cp_idx)
    name_x <- paste("packed_delta_main_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$main_ncp_idx)
    name_x <- paste("packed_delta_main_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  }

  title=paste(main_factor_names[f],
              ",\nLevel = ", l - data$main_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-5, 5),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-2, 2))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

The method factor level parameters look better behaved in comparison.

text
f <- 2
par(mfrow=c(2, 3))

for (l in data$main_factor_start_idx[f]:data$main_factor_end_idx[f]) {
  if (l %in% data$main_cp_idx) {
    cp_idx <- which(l == data$main_cp_idx)
    name_x <- paste("packed_delta_main_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$main_ncp_idx)
    name_x <- paste("packed_delta_main_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  }

  title=paste(main_factor_names[f],
              ",\nLevel = ", l - data$main_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-5, 5),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-9, 2))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

As do the source factor level parameters.

text
f <- 3
par(mfrow=c(3, 3))

for (l in data$main_factor_start_idx[f]:data$main_factor_end_idx[f]) {
  if (l %in% data$main_cp_idx) {
    cp_idx <- which(l == data$main_cp_idx)
    name_x <- paste("packed_delta_main_cp[", cp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  } else {
    ncp_idx <- which(l == data$main_ncp_idx)
    name_x <- paste("packed_delta_main_ncp[", ncp_idx, "]", sep='')
    name_y <- paste("delta_main_tau[", data$packed_main_factor_idx[l], "]", sep='')
  }

  title=paste(main_factor_names[f],
              ",\nLevel = ", l - data$main_factor_start_idx[f] + 1, sep='')

  plot(nondiv_samples[name_x][,1], log(nondiv_samples[name_y][,1]),
       col=c_dark_trans, pch=16, main=title,
       xlab=name_x, xlim=c(-5, 5),
       ylab=paste("log(", name_y, ")", sep=''), ylim=c(-11, 1))
  points(div_samples[name_x][,1], log(div_samples[name_y][,1]),
         col=c_green_trans, pch=16)
}

Let's try centering just the parameter for the fourth level of the location factor.

text
data$main_cp_idx <- array(4)
data$L_main_cp <- length(data$main_cp_idx)

data$main_ncp_idx <- setdiff(1:data$N_all_main_factor_levels, data$main_cp_idx)
data$L_main_ncp <- length(data$main_ncp_idx)

data$inter1_cp_idx <- vector()
data$L_inter1_cp <- length(data$inter1_cp_idx)

data$inter1_ncp_idx <- setdiff(1:data$N_all_inter1_factor_levels, data$inter1_cp_idx)
data$L_inter1_ncp <- length(data$inter1_ncp_idx)
text
fit <- stan(file='stan_programs/qa_ver2.stan',
            data=data, seed=4838282, refresh=2000)

Delightfully that seems to have done the trick.

text
util$check_all_diagnostics(fit)
text
[1] "n_eff / iter looks reasonable for all parameters"
[1] "Rhat looks reasonable for all parameters"
[1] "0 of 4000 iterations ended with a divergence (0%)"
[1] "0 of 4000 iterations saturated the maximum tree depth of 10 (0%)"
[1] "E-FMI indicated no pathological behavior"

Now we can investigate the posterior retrodictive behavior. We don't see any significant deviations across the main factor levels for any of the check times.

text
samples <- extract(fit)

par(mfrow=c(3, data$N_checks))
par(mar=c(5, 1, 3, 1))

lims <- c(300, 50, 50)
delta <- c(5, 1, 1)

for (f in 1:3) {
  for (c in 1:data$N_checks) {
    title <- paste(main_factor_names[f], ",\n Check ", c, sep='')
    hist(samples$F_main_post_pred[, f, c], breaks=seq(0, 1000, delta[f]),
         main=title, col=c_dark, border=c_dark_highlight,
         xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
    abline(v=F_main_obs[f, c], col="white", lty=1, lw=3)
    abline(v=F_main_obs[f, c], col="black", lty=1, lw=2)
  }
}

Same for the first-order interactions.

text
par(mfrow=c(3, data$N_checks))
lims <- c(500, 700, 100)

for (f in 1:3) {
  for (c in 1:data$N_checks) {
    title <- paste(inter1_factor_names[f], ",\n Check ", c, sep='')
    hist(samples$F_inter1_post_pred[, f, c], breaks=seq(0, 3000, 2),
         main=title, col=c_dark, border=c_dark_highlight,
         xlim=c(0, lims[f]), xlab="F Statistic", yaxt='n', ylab="")
    abline(v=F_inter1_obs[f, c], col="white", lty=1, lw=3)
    abline(v=F_inter1_obs[f, c], col="black", lty=1, lw=2)
  }
}

Indeed there's no signs of problems across the second-order interaction levels, either. This doesn't mean that heterogeneity across the second-order interaction factors is negligible, however, just that the heterogeneity can't be resolved by our relatively inefficient summary statistics.

text
par(mfrow=c(1, data$N_checks))

for (f in 1:1) {
  for (c in 1:data$N_checks) {
    title <- paste("Check ", c, sep='')
    s <- samples$F_inter2_post_pred[, f, c]
    hist(s[is.finite(s)], breaks=seq(0, 200000, 1000),
         main=title, col=c_dark, border=c_dark_highlight,
         xlim=c(0, 25000), xlab="F Statistic", yaxt='n', ylab="")
    abline(v=F_inter2_obs[c], col="white", lty=1, lw=3)
    abline(v=F_inter2_obs[c], col="black", lty=1, lw=2)
  }
}

mtext(inter2_factor_names[f], outer = TRUE)

To confirm that the second-order interactions are not important within the context of this measurement we could try fitting one more model that includes the second-order interaction factor and see if the posterior distribution concentrates away from zero. Here, however, let's be satisfied with the current model.

Filled with satisfaction let's explore the posterior distribution. The marginal posterior distributions for the baseline and logit intercept parameters haven't changed much.

text
par(mfrow=c(1, 2))

hist(samples$baseline, breaks=seq(-7, 1, 0.2),  main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(-7, 1), xlab="Baseline Logit Slope", yaxt='n', ylab="")

hist(samples$alpha, breaks=seq(1.75, 2.25, 0.01),  main="",
     col=c_dark, border=c_dark_highlight,
     xlim=c(1.75, 2.25), xlab="Logit Intercept", yaxt='n', ylab="")

The heterogeneity across the location and method factors remains large but note that the inferred heterogeneity across the source factor levels is now consistent with no heterogeneity at all!

text
plot_factor_posteriors("main", "Location Factor", 1)

text
plot_factor_posteriors("main", "Method Factor", 2)

text
plot_factor_posteriors("main", "Source Factor", 3)

On the other hand the heterogeneity across the method/source interaction factors is substantial, specially between Maintenance Method 5 and Input Material Source 3! Although technically just a measure of heterogeneity, this large interaction could indicate something important about the functionality of the manufacturing process. For example the lack of a common contaminant in Input Material Source 3 might be compensating for Maintenance Method 5 being unable to properly remove that contaminant.

text
plot_factor_posteriors("inter1", "Location/Method Interaction Factor", 1)

text
plot_factor_posteriors("inter1", "Location/Source Interaction Factor", 2)

text
plot_factor_posteriors("inter1", "Method/Source Interaction Factor", 3)

The significant change in behavior within main factor levels after the introduction of interaction factors is common when the heterogeneity across those interaction factor levels is large. In particular when the interaction factors are not included the main factor level parameters have to contort to try to accommodate for the excess heterogeneity. That particular contortion, however, will depend on particular factor configurations observed and hence will tend to generalize poorly to other factor configurations. By explicitly modeling the significant interactions we avoid this fragile contortion and achieve much better generalizability, at least provided that whatever causes the heterogeneity is static.

With the first-order interactions providing a reasonable fit to the total heterogeneity we see the full variation of success probability evolutions.

text
par(mfrow=c(1, 2))
par(mar=c(5, 5, 3, 1))

N_plot <- 100
line_colors <- colormap(colormap=nom_colors, nshades=N_plot)
config_plot_idx <- rep(20*(1:10), each=10)
sample_plot_idx <- rep(400*(1:10), 10)

plot(1, type="n", main="Spaghetti",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
for (n in 1:N_plot)
  lines(data$fine_t, samples$p[sample_plot_idx[n], config_plot_idx[n],],
        col=line_colors[n], lwd=2)

probs = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
cred <- sapply(1:data$N_fine_t, function(n) quantile(samples$p[,,n], probs=probs))

plot(1, type="n", main="Quantile Ribbons",
     xlab="time (days)", ylab="Success Probability",
     xlim=c(0, 365), ylim=c(0, 1))
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[1,], rev(cred[9,])),
        col = c_light, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[2,], rev(cred[8,])),
        col = c_light_highlight, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[3,], rev(cred[7,])),
        col = c_mid, border = NA)
polygon(c(data$fine_t, rev(data$fine_t)), c(cred[4,], rev(cred[6,])),
        col = c_mid_highlight, border = NA)
lines(data$fine_t, cred[5,], col=c_dark, lwd=2)

One of the powerful features of overlapping factor models is that we can reconstruct the behavior of factor configurations that we didn't actually observe. With only 250 observed factor configurations there are many possible combinations of the main factor levels that we did not yet observe.

text
all_inter2_idx <- 1:data$N_all_inter2_factor_levels
obs_inter2_idx <- strtoi(names(table(data$inter2_factor_level_idx)))
setdiff(all_inter2_idx, obs_inter2_idx)
text
  [1]   2   3   8  15  17  19  23  26  29  33  34  35  36  40  44  45  46  47
 [19]  49  54  58  60  61  62  66  68  69  71  75  76  77  78  80  83  85  87
 [37]  89  90  91  92  93  94  95  96  97  99 100 103 104 105 106 107 108 112
 [55] 113 114 115 118 119 122 126 130 132 135 139 140 144 146 147 148 149 151
 [73] 153 154 159 160 168 169 174 179 181 182 183 185 186 187 191 192 197 198
 [91] 201 202 203 207 208 213 215 216 217 220 221 222 225 229 234 235 236 238
[109] 239 241 242 243 252 253 256 257 258 260 261 263 264 267 268 269 273 278
[127] 279 283 287 290 292 295 296 298 299 300 303 306 310 311

For example we didn't observe the second-order interaction level 311 which corresponds to Factor Location 9, Maintenance Method 5, and Input Material Source 3.

text
decode_inter2_idx <- function(idx, data) {
  N1 <- data$N_main_factor_levels[1]
  N2 <- data$N_main_factor_levels[2]
  N3 <- data$N_main_factor_levels[3]

  location_idx <- (idx - 1) %/% (N2 * N3) + 1
  method_idx <- ( (idx - 1) %% (N2 * N3)) %/% N3 + 1
  source_idx <- ( (idx - 1) %% (N2 * N3)) %% N3 + 1

  c(location_idx, method_idx, source_idx)
}

main_factor_idx <- decode_inter2_idx(311, data)

main_factor_idx
text
[1] 9 5 3

Given that we didn't observe this particular configuration what might we predict for its behavior after 300 days? We could take a counterfactual approach that ignores the heterogeneity entirely, basing our predictions on the baseline behavior only.

text
base_inf <- 1 / (1 + exp(-(samples$alpha + samples$baseline * 300 / 365.0)))

par(mfrow=c(1, 1))

hist(base_inf, breaks=seq(0, 1, 0.01),  main="Baseline Inference",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 1), xlab="Inferred Success Probability", yaxt='n', ylab="")

Alternatively we can reconstruct the behavior from the behavior common to lower-order factor configurations that we did observe. Although we didn't observe Factor Location 9, Maintenance Method 5, and Input Material Source 3 together, we did observe many configurations where each main factor level appeared separately; we also observed plenty of configurations where the levels of two of the main factors matched. Because the overlapping multifactor model separated these contributions we are able to add them back together in different ways.

text
encode_inter1 <- function(f1, l1, f2, l2, data) {
  (l1 - 1) * data$N_main_factor_levels[f2] + l2
}

inter1_12_idx <- encode_inter1(1, main_factor_idx[1], 2, main_factor_idx[2], data)
inter1_13_idx <- encode_inter1(1, main_factor_idx[1], 3, main_factor_idx[3], data)
inter1_23_idx <- encode_inter1(2, main_factor_idx[2], 3, main_factor_idx[3], data)

slope <- samples$baseline +
         samples$packed_delta_main[data$main_factor_start_idx[1] + main_factor_idx[1] - 1] +
         samples$packed_delta_main[data$main_factor_start_idx[2] + main_factor_idx[2] - 1] +
         samples$packed_delta_main[data$main_factor_start_idx[3] + main_factor_idx[3] - 1] +
         samples$packed_delta_inter1[data$inter1_factor_start_idx[1] + inter1_12_idx - 1] +
         samples$packed_delta_inter1[data$inter1_factor_start_idx[2] + inter1_13_idx - 1] +
         samples$packed_delta_inter1[data$inter1_factor_start_idx[3] + inter1_23_idx - 1]

recon_inf <- 1 / (1 + exp(-(samples$alpha + slope * 300 / 365.0)))

par(mfrow=c(1, 2))

hist(base_inf, breaks=seq(0, 1, 0.01),  main="Baseline Inference",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 1), xlab="Inferred Success Probability", yaxt='n', ylab="")

hist(recon_inf, breaks=seq(0, 1, 0.01),  main="Reconstructed Heterogeneity Inference",
     col=c_dark, border=c_dark_highlight,
     xlim=c(0, 1), xlab="Inferred Success Probability", yaxt='n', ylab="")

Ignoring the factor heterogeneity entirely yields a very different prediction for the success probability of this unobserved factor configuration after 300 days. The reconstruction based on a first-order interaction model might not be perfect but it should provide much better predictions whenever the latent process that generates the factor heterogeneities remains the same.

6 What's In A Name?

One of the practical complications of using factor models is the -- perhaps appropriate -- heterogeneity in terminology across, and even sometimes within, different fields. Indeed while the term "factor model" is directly motivated by the basic assumption of heterogeneity across factor levels it is not all that common in the contemporary applied statistics literature. In this section I will attempt to review some of the more common terminologies, and why I try to avoid them.

In this case study I use "factor model" to refer to models with known level assignments, but in some fields the term is also used to refer to models with unknown level assignments, such as independent component analysis [3]. Any confusion here can be avoided by explicitly denoting whether the factors, and the factor level assignments, are given or are meant to be inferred from data.

The term "multilevel" is often associated with factor models, sometimes to the point of being treated as synonyms. Historically, however, "multilevel" referred not to factor models in particular but rather to hierarchical models in general with the "levels" denoting to the layers of the hierarchy, such as the individual parameters verses the population parameters. From this perspective the term "multilevel" might indicate that hierarchical models are used, but because it doesn't tell us how they are used it is not sufficient for denoting factor models in particular. Moreover the overloading of "level" to refer to both the hierarchical structure and the categorical values within each factor is, in my opinion, far too confusing to be worth the risk.

Another term in the orbit of factor models is "random effect" and "fixed effect". Although there is some variation in applied literatures, in classical statistics "random effect" denotes factor level parameters that are modeled hierarchically while "fixed effect" denotes factor level parameter modeled independently. In other words a "random effect" implies a single factor hierarchical model as defined in Section 1.3. Similarly the term "random effects model" denotes models with multiple random effects and "mixed effects models" denotes models with some random effects and some fixed effects, although neither term indicates how the effects are integrated together. Better is the term "additive model" or more precisely "additive mixed effects model" which indicates that multiple random effects corresponding to different factors, including main factors and their derived interactions, are added together as in the residual expansions of nested multifactor model and overlapping multifactor models. Moreover the term "additive mixed effects model" almost always implies that the residual expansion is used to model the location parameter of some family of probability density functions; when the observational model is not specified by a family of normal density functions the term "general additive model" is also common.

Many contemporary tools such as lme4 and brms use a formula notation for specifying these models of heterogeneity in a location parameter. The notation was initially introduced in [4] but it has since enjoyed its own storied evolution.

My main issue with the "effect" terminology is the hidden, restrictive assumptions that are often taken for granted. For one the term "effect" itself is loaded, implying a causal influence of each factor level that is not actually implied by the mathematical model of heterogeneity. Moreover the commonly applied restriction to location parameters drastically limits the utility of multifactor models which can be used to model the heterogeneity that manifests in any part of a probabilistic model. Even within the implied assumptions this terminology obfuscates the implementation of the model, in particular the parameterization of the hierarchical models which is critical to accurate but efficient computation.

To avoid terminological baggage and communicate the assumptions as clearly as possible I prefer the terms "hierarchcial nested multifactor model" and "hierarchical overlapping multifactor model" depending on the relationship between the factors. That said the best way to communicate the assumptions is to document the full model. One of the advantages of probabilistic programming in Stan is that we have the flexibility to incorporate multifactor modeling where ever it is motivated by the application, and the program itself unambiguously communicates all of the assumptions being made; well-documented programs even ensure that those assumptions are actually decipherable by collaborators and colleagues. The expressiveness of the language also allows the parameterization of the many hierarchical models to be properly tuned to avoid computational problems, as we have done in the above exercises.

Even if the full modeling flexibility isn't needed, the exercise of building these models in Stan can be extremely useful for helping one to identify assumptions that they may have been accidentally taking for granted.

7 Conclusion

Factor models provide a principled approach to modeling heterogeneity compatible not just with one categorizing factor but multiple nested or even overlapping factors. With this approach we can model complex experimental side effects and isolate latent phenomena of interest in our inferences, and we can even heuristically model the phenomena itself by how it manifests in variation within the included factors. When sufficient care is taken to ensure that the the limitations of this modeling technique are understood and investigated, factor models become a powerful addition to our modeling technique toolbox.

By building multifactor models ourselves in Stan we not only facilitate those investigations but also free the technique from the restrictive assumptions built into higher-level tools, allowing us to witness the full potential of this fully armed and operational modeling technique.

Acknowledgements

I thank Jessica Graves and Charles Margossian for valuable comments.

A very special thanks to everyone supporting me on Patreon: Aapeli Nevala, Abhinav Katoch, Abhishek Vasu, Adam Bartonicek, Adam Fleischhacker, Adam Golinski, Adan, Alan O'Donnell, Alex ANDORRA, Alexander Bartik, Alexander Noll, Alfredo Garbuno Iñigo, Allison M. Campbell, Anders Valind, Andrea Serafino, Andrew Rouillard, Annie Chen, Anthony Wuersch, Antoine Soubret, Arya, asif zubair, Austin Carter, Austin Rochford, Austin Rochford, Avraham Adler, Bao Tin Hoang, Ben Matthews, Ben Swallow, Benjamin Phillabaum, enoit Essiambre, Bo Schwartz Madsen, Brian Hartley, Bryan Yu, Brynjolfur Gauti Jónsson, Cameron Smith, Canaan Breiss, Cat Shark, Chad Scherrer, Charles Naylor, Chase Dwelle, Chris Jones, Chris Zawora, Christopher Mehrvarzi, Chuck Carlson, Cole Monnahan, Colin Carroll, Colin McAuliffe, D, Damien Mannion, dan mackinlay, dan muck, Dan W Joyce, Daniel Hocking, Daniel Rowe, Darshan Pandit, David Burdelski, David Christle, David Humeau, David Pascall, Derek G Miller, Diogo Melo, Donna Perry, Doug Rivers, Dylan Murphy, Ed Berry, Ed Cashin, Elizaveta Semenova, Eric Novik, Erik Banek, Ero Carrera, Ethan Goan, Evan Cater, Fabio Zottele, Federico Carrone, Felipe González, Fergus Chadwick, Filipe Dias, Finn Lindgren, Florian Wellmann, Francesco Corona, Geoff Rollins, George Ho, Georgia S, Gerardo Salazar, Granville Matheson, Guido Biele, Guilherme Marthe, Hamed Bastan-Hagh, Hany Abdulsamad, Haonan Zhu, Hugo Botha, Hyunji Moon, Ian, Ignacio Vera, Ilaria Prosdocimi, Isaac S, J, J Michael Burgess, Jair Andrade Ortiz, James McInerney, James Wade, JamesU, Janek Berger, Jason Martin, Jeff Dotson, Jeff Helzner, Jeffrey Arnold, Jeffrey Burnett, Jessica Graves, Joel Kronander, John Flournoy, John Zito, Jon , Jonathan Sedar, Jonathan St-onge, Jonathon Vallejo, Jose Pereira, Josh Weinstock, Joshua Duncan, Joshua Griffith, Joshua Mayer, Joss Wright, Josué Mendoza, Justin Bois, Karim Naguib, Karim Osman, Kazuki Yoshida, Kejia Shi, Kádár András, Leo Grinsztajn, lizzie , Luiz Carvalho, Lukas Neugebauer, Marc Dotson, Marc Trunjer Kusk Nielsen, Marek Kwiatkowski, Mark Donoghoe, Markus P., Martin Modrák, Matt Wescott, Matthew Kay, Matthew Quick, Matthew T Stern, Maurits van der Meer, Maxim Kesin, Merlin Noel Heidemanns, Michael Colaresi, Michael DeWitt, Michael Dillon, Michael Lerner, Michael Redman, Michael Tracy, Mick Cooney, Miguel de la Varga, Mike Lawrence, Mikhail Popov, MisterMentat, Mohammed Charrout, Márton Vaitkus, Name, Nathan Rutenbeck, Nerf-Shepherd, Nicholas Cowie, Nicholas Ursa, Nick S, Nicolas Frisby, Noah Guzman, Octavio Medina, Ole Rogeberg, Oliver Crook, Olivier Ma, Omri Har Shemesh, Pablo León Villagrá, Patrick Boehnke, Pau Pereira Batlle, Paul Oreto, Peter Smits, Pieter van den Berg , Pintaius Pedilici, Ravin Kumar, Reed Harder, Riccardo Fusaroli, Richard Price, Robert Frost, Robert Goldman, Robert J Neal, Robert kohn, Robert Mitchell V, Robin Taylor, Rong Lu, Roofwalker, Ryan Grossman, Rémi , Scott Block, Sean Talts, Seth Axen, Shira , sid phani, Simon Dirmeier, Simon Duane, Simon Lilburn, Srivatsa Srinath, Stephanie Fitzgerald, Stephen Lienhard, Stephen Oates, Steve Bertolani, Stijn, Stone Chen, Sus, Susan Holmes, Suyog Chandramouli, Sören Berg, tardisinc, Teddy Groves, Teresa Ortiz, Thomas Littrell, Thomas Vladeck, Théo Galy-Fajou, Tiago Cabaço, Tim Howes, Tim Radtke, Tobychev , Tom Knowles, Tom McEwen, Tommy Naugle, Tuan Nguyen Anh, Tyrel Stokes, Utku Turk, Virginia Webber, vittorio trotta, Vladimir Markov, Will Dearden, Will Farr, yolhaj, yureq, Z, Zach A, and ZAKH.

References

[1] Box, G. E. P., Hunter, J. S. and Hunter, W. G. (2005). Statistics for experimenters. Wiley-Interscience [John Wiley & Sons], Hoboken, NJ.

[2] Crenshaw, K. (1989). Demarginalizing the intersection of race and sex: A black feminist critique of antidiscrimination doctrine, feminist theory and antiracist politics. University of Chicago Legal Forum 1989 139.

[3] Bishop, C. M. (2006). Pattern recognition and machine learning. Springer, New York.

[4] Wilkinson, G. N. and Rogers, C. E. (1973). Symbolic description of factorial models for analysis of variance. Journal of the Royal Statistical Society. Series C (Applied Statistics) 22 392–9.

License

A repository containing the material used in this case study is available on GitHub.

The code in this case study is copyrighted by Michael Betancourt and licensed under the new BSD (3-clause) license:

https://opensource.org/licenses/BSD-3-Clause

The text and figures in this case study are copyrighted by Michael Betancourt and licensed under the CC BY-NC 4.0 license:

https://creativecommons.org/licenses/by-nc/4.0/

Original Computing Environment

text
writeLines(readLines(file.path(Sys.getenv("HOME"), ".R/Makevars")))
text
CC=clang

CXXFLAGS=-O3 -mtune=native -march=native -Wno-unused-variable -Wno-unused-function -Wno-macro-redefined -Wno-unneeded-internal-declaration
CXX=clang++ -arch x86_64 -ftemplate-depth-256

CXX14FLAGS=-O3 -mtune=native -march=native -Wno-unused-variable -Wno-unused-function -Wno-macro-redefined -Wno-unneeded-internal-declaration -Wno-unknown-pragmas
CXX14=clang++ -arch x86_64 -ftemplate-depth-256
text
sessionInfo()
text
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.5

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] colormap_0.1.4       rstan_2.19.3         ggplot2_3.3.1       
[4] StanHeaders_2.21.0-3

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.4.6       pillar_1.4.4       compiler_4.0.2     prettyunits_1.1.1 
 [5] tools_4.0.2        digest_0.6.25      pkgbuild_1.0.8     jsonlite_1.6.1    
 [9] evaluate_0.14      lifecycle_0.2.0    tibble_3.0.1       gtable_0.3.0      
[13] pkgconfig_2.0.3    rlang_0.4.6        cli_2.0.2          curl_4.3          
[17] parallel_4.0.2     yaml_2.2.1         xfun_0.16          loo_2.2.0         
[21] gridExtra_2.3      withr_2.2.0        stringr_1.4.0      dplyr_1.0.0       
[25] knitr_1.29         generics_0.0.2     vctrs_0.3.0        stats4_4.0.2      
[29] grid_4.0.2         tidyselect_1.1.0   glue_1.4.1         inline_0.3.15     
[33] R6_2.4.1           processx_3.4.2     fansi_0.4.1        rmarkdown_2.2     
[37] purrr_0.3.4        callr_3.4.3        magrittr_1.5       codetools_0.2-16  
[41] matrixStats_0.56.0 ps_1.3.3           scales_1.1.1       ellipsis_0.3.1    
[45] htmltools_0.4.0    assertthat_0.2.1   colorspace_1.4-1   V8_3.2.0          
[49] stringi_1.4.6      munsell_0.5.0      crayon_1.3.4