Skip to content

VIPRSMix

VIPRSMix

Bases: VIPRS

A class for the Variational Inference for Polygenic Risk Scores (VIPRS) model parametrized with the sparse mixture prior on the effect sizes. The class inherits many of the methods and attributes from the VIPRS class unchanged. However, there are many important updates and changes to the model, including the dimensionality of the arrays representing the variational parameters.

Details for the algorithm can be found in the Supplementary Material of the following paper:

Zabad S, Gravel S, Li Y. Fast and accurate Bayesian polygenic risk modeling with variational inference. Am J Hum Genet. 2023 May 4;110(5):741-761. doi: 10.1016/j.ajhg.2023.03.009. Epub 2023 Apr 7. PMID: 37030289; PMCID: PMC10183379.

Attributes:

Name Type Description
K

The number of causal (i.e. non-null) components in the mixture prior (minimum 1). When K=1, this effectively reduces VIPRSMix to the VIPRS model.

d

Multiplier for the prior precision of each non-null component (vector of size K). Smaller values correspond to wider components.

Source code in viprs/model/VIPRSMix.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
class VIPRSMix(VIPRS):
    """
    A class for the Variational Inference for Polygenic Risk Scores (VIPRS) model
    parametrized with the sparse mixture prior on the effect sizes. The class inherits
    many of the methods and attributes from the `VIPRS` class unchanged. However,
    there are many important updates and changes to the model, including the dimensionality
    of the arrays representing the variational parameters.

    Details for the algorithm can be found in the Supplementary Material of the following paper:

    > Zabad S, Gravel S, Li Y. Fast and accurate Bayesian polygenic risk modeling with variational inference.
    Am J Hum Genet. 2023 May 4;110(5):741-761. doi: 10.1016/j.ajhg.2023.03.009.
    Epub 2023 Apr 7. PMID: 37030289; PMCID: PMC10183379.

    :ivar K: The number of causal (i.e. non-null) components in the mixture prior (minimum 1). When `K=1`, this
    effectively reduces `VIPRSMix` to the `VIPRS` model.
    :ivar d: Multiplier for the prior precision of each non-null component
        (vector of size K). Smaller values correspond to wider components.

    """

    def __init__(self, gdl, K=1, prior_multipliers=None, **kwargs):
        """
        :param gdl: An instance of `GWADataLoader`
        :param K: The number of causal (i.e. non-null) components in the mixture prior (minimum 1). When `K=1`, this
            effectively reduces `VIPRSMix` to the `VIPRS` model.
        :param prior_multipliers: Multipliers for the prior precisions of the
            non-null mixture components (vector of size K). Smaller values
            correspond to wider components.
        :param kwargs: Additional keyword arguments to pass to the VIPRS model.
        """

        # Make sure that the matrices follow the C-contiguous order:
        kwargs["order"] = "C"

        super().__init__(gdl, **kwargs)

        # Sanity checks:
        assert K > 0  # Check that there is at least 1 causal component
        self.K = K

        if prior_multipliers is not None:
            assert len(prior_multipliers) == K
            self.d = np.array(prior_multipliers).astype(self.float_precision)
        else:
            self.d = 2 ** np.linspace(-min(K - 1, 7), 0, K).astype(self.float_precision)

        if np.any(self.d <= 0.0):
            raise ValueError("Prior precision multipliers must be strictly positive.")

        # Populate/update relevant fields:
        self.shapes = {c: (shp, self.K) for c, shp in self.shapes.items()}
        self.n_per_snp = {
            c: n[:, None].astype(self.float_precision, order=self.order)
            for c, n in self.n_per_snp.items()
        }
        self._e_step_statistics = None

    def initialize_variational_parameters(self, param_0=None):
        """Initialize variational parameters and invalidate cached statistics."""

        super().initialize_variational_parameters(param_0)
        self._e_step_statistics = None

    def _set_optimization_scale(self, target_scale):
        """Rescale model parameters and invalidate scale-dependent statistics."""

        super()._set_optimization_scale(target_scale)
        self._e_step_statistics = None

    def initialize_theta(self, theta_0=None):
        """
        Initialize the global hyperparameters of the model
        :param theta_0: A dictionary of initial values for the hyperparameters theta
        """

        theta_0 = {} if theta_0 is None else theta_0.copy()
        theta_0.update(self.fix_params)
        if "tau_beta" in self.fix_params and "tau_betas" not in self.fix_params:
            theta_0.pop("tau_betas", None)

        # ----------------------------------------------
        # (1) Initialize pi from a uniform
        if "pis" in theta_0:
            self.pi = self._cast_parameter(theta_0["pis"])

            # If only the total causal proportion is fixed, preserve the
            # supplied component ratios and rescale them to that total.
            if "pi" in self.fix_params and "pis" not in self.fix_params:
                overall_pi = self.fix_params["pi"]
                if isinstance(self.pi, dict):
                    self.pi = {
                        c: overall_pi * pi / pi.sum(axis=1, keepdims=True)
                        for c, pi in self.pi.items()
                    }
                else:
                    self.pi *= overall_pi / self.pi.sum()
        else:
            overall_pi = theta_0["pi"] if "pi" in theta_0 else np.random.uniform(
                low=max(0.005, 1.0 / self.n_snps), high=0.1
            )

            self.pi = overall_pi * np.random.dirichlet(np.ones(self.K))

        # ----------------------------------------------
        # (2) Initialize sigma_epsilon and component precisions. Under the
        # standardized model, h2 = sum_jk(pi_jk / tau_jk) = 1 - sigma_epsilon.
        if "tau_betas" in theta_0:
            self.tau_beta = self._cast_parameter(theta_0["tau_betas"])
        elif "tau_beta" in theta_0:
            self.tau_beta = theta_0["tau_beta"] * self.d
        else:
            if "sigma_epsilon" in theta_0:
                h2g_estimate = 1.0 - theta_0["sigma_epsilon"]
            else:
                try:
                    h2g_estimate = np.clip(simple_ldsc(self.gdl), 1e-3, 1.0 - 1e-3)
                except Exception:
                    h2g_estimate = np.random.uniform(low=0.001, high=0.999)

            self.tau_beta = self.d * (
                self._prior_variance_sum(self.d) / h2g_estimate
            )

        if "sigma_epsilon" in theta_0:
            self.sigma_epsilon = theta_0["sigma_epsilon"]
        else:
            self.sigma_epsilon = np.clip(
                1.0 - self._prior_variance_sum(self.tau_beta),
                a_min=1e-4,
                a_max=1.0 - 1e-4,
            )

        # Cast all the hyperparameters to conform to the precision set by the user:
        self.sigma_epsilon = np.dtype(self.float_precision).type(self.sigma_epsilon)
        self.pi = self._cast_parameter(self.pi)
        self.tau_beta = self._cast_parameter(self.tau_beta)
        self.lambda_min = self._cast_parameter(self.lambda_min)
        self._sigma_g = np.dtype(self.float_precision).type(0.0)

    def _cast_parameter(self, value):
        """Cast scalar, array, or chromosome-indexed parameters."""

        if isinstance(value, dict):
            return {
                c: np.asarray(v, dtype=self.float_precision, order=self.order)
                for c, v in value.items()
            }
        if np.isscalar(value):
            return np.dtype(self.float_precision).type(value)
        return np.asarray(value, dtype=self.float_precision, order=self.order)

    def _prior_variance_sum(self, tau_beta):
        """Return the total prior variance contributed by all variants."""

        total = 0.0
        for c, shape in self.shapes.items():
            c_pi = self.pi[c] if isinstance(self.pi, dict) else self.pi
            c_tau = tau_beta[c] if isinstance(tau_beta, dict) else tau_beta
            if np.ndim(c_pi) == 1 and np.ndim(c_tau) == 1:
                total += shape[0] * np.sum(c_pi / c_tau, dtype=np.float64)
            else:
                total += np.sum(np.asarray(c_pi) / np.asarray(c_tau), dtype=np.float64)
        return total

    def e_step(self):
        """
        Run the E-Step of the Variational EM algorithm.
        Here, we update the variational parameters for each variant using coordinate
        ascent optimization techniques. The update equations are outlined in
        the Supplementary Material of the following paper:

        > Zabad S, Gravel S, Li Y. Fast and accurate Bayesian polygenic risk modeling with variational inference.
        Am J Hum Genet. 2023 May 4;110(5):741-761. doi: 10.1016/j.ajhg.2023.03.009.
        Epub 2023 Apr 7. PMID: 37030289; PMCID: PMC10183379.
        """

        # Step 1: Initialize genome-wide sufficient statistics. The native
        # kernel adds each chromosome's contribution to these arrays.
        statistics = {
            "gamma_sum": np.zeros(self.K, dtype=np.float64),
            "component_zeta": np.zeros(self.K, dtype=np.float64),
            # gamma*log(gamma), null*log(null), gamma*log(var_tau), null
            "elbo": np.zeros(4, dtype=np.float64),
        }
        self._e_step_statistics = None
        if not hasattr(self, "zeta"):
            self.zeta = {}

        for c, shapes in self.shapes.items():
            if c not in self.zeta or self.zeta[c].shape != (shapes[0],):
                self.zeta[c] = np.empty(shapes[0], dtype=np.float64)

            # Get the priors:
            tau_beta = self.get_tau_beta(c)
            pi = self.get_pi(c)
            parameter_scale = getattr(self, "_parameter_scale", 1.0)
            scaled_n = self.n_per_snp[c] / parameter_scale

            lambda_min = self.lambda_min[c] if isinstance(self.lambda_min, dict) else self.lambda_min
            if not np.isscalar(lambda_min):
                lambda_min = np.asarray(lambda_min)[:, None]

            # Updates for tau variational parameters:
            self.var_tau[c] = (
                scaled_n * (1.0 + lambda_min) / self.sigma_epsilon
            ) + tau_beta
            np.log(self.var_tau[c], out=self._log_var_tau[c])

            if isinstance(self.pi, dict):
                log_null_pi = np.log(1.0 - self.pi[c].sum(axis=1))
            else:
                log_null_pi = np.ones_like(self.eta[c]) * np.log(1.0 - self.pi.sum())

            # Compute some quantities that are needed for the per-SNP updates:
            mu_mult = (
                scaled_n / (self.var_tau[c] * self.sigma_epsilon)
            ).astype(self.float_precision)
            u_logs = (
                np.log(pi)
                + 0.5 * (np.log(tau_beta) - self._log_var_tau[c])
            ).astype(self.float_precision)

            cpp_e_step_mixture(
                self.ld_left_bound[c],
                self.ld_indptr[c],
                self.ld_data[c],
                self.std_beta[c],
                self.var_gamma[c],
                self.var_mu[c],
                self.eta[c],
                self.q[c],
                self.eta_diff[c],
                log_null_pi,
                u_logs,
                self.var_tau[c],
                self._log_var_tau[c],
                np.sqrt(0.5 * self.var_tau[c]).astype(self.float_precision),
                mu_mult,
                self.zeta[c],
                statistics["gamma_sum"],
                statistics["component_zeta"],
                statistics["elbo"],
                self.dequantize_scale,
                self.threads,
                self.low_memory,
            )

        # Step 2: Publish the statistics only after every chromosome has
        # completed, so downstream updates cannot observe partial values.
        self._e_step_statistics = statistics

    def elbo(self, sum_axis=None):
        """Compute the scalar ELBO from E-step sufficient statistics."""

        statistics = getattr(self, "_e_step_statistics", None)
        if (
            statistics is None
            or sum_axis is not None
            or isinstance(self.pi, dict)
            or isinstance(self.tau_beta, dict)
        ):
            return super().elbo(sum_axis=sum_axis)

        # Step 1: Compute the likelihood contribution, which is independent
        # of the component-wise reductions cached by the E-step.
        parameter_scale = getattr(self, "_parameter_scale", 1.0)
        elbo = -np.log(2.0 * np.pi * self.sigma_epsilon)
        if "sigma_epsilon" not in self.fix_params:
            elbo -= 1.0
        else:
            beta_eta = sum(
                self.std_beta[c].astype(np.float64).dot(
                    self.eta[c].astype(np.float64)
                )
                for c in self.shapes
            )
            elbo -= (1.0 / self.sigma_epsilon) * (
                1.0
                - 2.0 * beta_eta / parameter_scale
                + self._sigma_g / parameter_scale
            )
        elbo *= 0.5 * self.n

        # Step 2: Reconstruct all mixture terms from the cached scalar and
        # component statistics, reducing the remaining work to O(K).
        gamma_sum = statistics["gamma_sum"]
        component_zeta = statistics["component_zeta"]
        gamma_log_gamma, null_log_null, gamma_log_var_tau, null_sum = (
            statistics["elbo"]
        )
        pi = np.asarray(self.pi, dtype=np.float64)
        tau_beta = np.asarray(self.tau_beta, dtype=np.float64)
        null_pi = 1.0 - pi.sum()

        elbo -= gamma_log_gamma - np.dot(gamma_sum, np.log(pi))
        elbo -= null_log_null - null_sum * np.log(null_pi)
        elbo += 0.5 * (
            gamma_sum.sum()
            - gamma_log_var_tau
            + np.dot(gamma_sum, np.log(tau_beta))
        )
        elbo -= 0.5 * np.dot(tau_beta, component_zeta)
        return elbo

    def set_fixed_params(self, fix_params):
        """Set fixed mixture hyperparameters, including their plural aliases."""

        assert isinstance(fix_params, dict), "The fixed parameters must be provided as a dictionary."

        # The plural forms fix component-specific values; the singular forms
        # fix only the total probability or shared precision scale.
        if "pis" in fix_params:
            self.fix_params.pop("pi", None)
        elif "pi" in fix_params:
            self.fix_params.pop("pis", None)
        if "tau_betas" in fix_params:
            self.fix_params.pop("tau_beta", None)
        elif "tau_beta" in fix_params:
            self.fix_params.pop("tau_betas", None)

        self.fix_params.update(fix_params)

        if "sigma_epsilon" in fix_params:
            self.sigma_epsilon = np.dtype(self.float_precision).type(
                fix_params["sigma_epsilon"]
            )
        if "lambda_min" in fix_params:
            self.lambda_min = self._cast_parameter(fix_params["lambda_min"])
        if "tau_betas" in fix_params:
            tau_beta = self._cast_parameter(fix_params["tau_betas"])
            if isinstance(tau_beta, dict):
                self.tau_beta = {
                    c: tau / getattr(self, "_parameter_scale", 1.0)
                    for c, tau in tau_beta.items()
                }
            else:
                self.tau_beta = tau_beta / getattr(self, "_parameter_scale", 1.0)
        elif "tau_beta" in fix_params:
            self.tau_beta = (
                fix_params["tau_beta"] * self.d
                / getattr(self, "_parameter_scale", 1.0)
            )
        if "pis" in fix_params:
            self.pi = self._cast_parameter(fix_params["pis"])
        elif "pi" in fix_params and self.pi is not None:
            overall_pi = fix_params["pi"]
            if isinstance(self.pi, dict):
                self.pi = {
                    c: overall_pi * pi / pi.sum(axis=1, keepdims=True)
                    for c, pi in self.pi.items()
                }
            else:
                self.pi *= overall_pi / self.pi.sum()

    def update_pi(self):
        """
        Update the prior mixing proportions `pi`
        """

        if "pis" not in self.fix_params:
            statistics = getattr(self, "_e_step_statistics", None)
            if statistics is None:
                pi_estimate = dict_sum(self.var_gamma, axis=0)
            else:
                pi_estimate = statistics["gamma_sum"].copy()

            if "pi" in self.fix_params:
                # If the user provides an estimate for the total proportion of causal variants,
                # update the pis such that the proportion of SNPs in the null component becomes 1. - pi.
                pi_estimate = self.fix_params["pi"] * pi_estimate / pi_estimate.sum()
            else:
                pi_estimate /= self.n_snps

            # Set pi to the new estimate:
            self.pi = self._cast_parameter(pi_estimate)

    def update_tau_beta(self):
        """
        Update the prior precision (inverse variance) for the effect sizes, `tau_beta`
        """

        if "tau_betas" not in self.fix_params and "tau_beta" not in self.fix_params:
            # Estimate a shared precision scale and apply the component-specific
            # precision multipliers. This is the constrained mixture M-step.

            statistics = getattr(self, "_e_step_statistics", None)
            if statistics is None:
                zetas = sum(self.compute_zeta(sum_axis=0).values())
                total_responsibility = dict_sum(self.var_gamma)
            else:
                zetas = statistics["component_zeta"]
                total_responsibility = statistics["gamma_sum"].sum()

            global_tau = total_responsibility / np.dot(self.d, zetas)
            # Preserve the exact component ratios while enforcing tau_k >= 1
            # on the original (unscaled) precision scale.
            global_tau = np.maximum(
                global_tau,
                1.0 / (np.min(self.d) * getattr(self, "_parameter_scale", 1.0)),
            )

            self.tau_beta = self._cast_parameter(self.d * global_tau)

    def update_sigma_epsilon(self):
        """Update residual variance without promoting float32 models."""

        super().update_sigma_epsilon()
        self.sigma_epsilon = np.dtype(self.float_precision).type(
            self.sigma_epsilon
        )

    def get_null_pi(self, chrom=None):
        """
        Get the proportion of SNPs in the null component
        :param chrom: If provided, get the mixing proportion for the null component on a given chromosome.
        :return: The value of the mixing proportion for the null component
        """

        pi = self.get_pi(chrom=chrom)

        if isinstance(pi, dict):
            return {c: 1.0 - c_pi.sum(axis=-1) for c, c_pi in pi.items()}
        return 1.0 - np.sum(pi, axis=-1)

    def get_proportion_causal(self):
        """
        :return: The proportion of variants in the non-null components.
        """
        if isinstance(self.pi, dict):
            return np.dtype(self.float_precision).type(
                sum(np.sum(pis, dtype=np.float64) for pis in self.pi.values())
                / self.n_snps
            )
        return np.sum(self.pi)

    def get_average_effect_size_variance(self):
        """
        :return: The average per-SNP variance for the prior mixture components
        """

        total = self._prior_variance_sum(self.tau_beta)
        return total / (
            self.n_snps * getattr(self, "_parameter_scale", 1.0)
        )

    def compute_pip(self):
        """
        :return: The posterior inclusion probability
        """
        return {c: gamma.sum(axis=1) for c, gamma in self.var_gamma.items()}

    def compute_eta(self):
        """
        :return: The mean for the effect size under the variational posterior.
        """
        return {c: (v * self.var_mu[c]).sum(axis=1) for c, v in self.var_gamma.items()}

    def compute_zeta(self, sum_axis=1):
        """
        :return: The expectation of the squared effect size under the variational posterior.
        """
        return {
            c: np.sum(
                v.astype(np.float64)
                * (
                    self.var_mu[c].astype(np.float64) ** 2
                    + (1.0 / self.var_tau[c].astype(np.float64))
                ),
                axis=sum_axis,
            )
            for c, v in self.var_gamma.items()
        }

    def to_theta_table(self):
        """
        :return: A `pandas` DataFrame containing information about the estimated hyperparameters of the model.
        """

        table = super().to_theta_table()

        extra_theta = []

        if isinstance(self.tau_beta, dict):
            average_taus = dict_sum(self.tau_beta, axis=0) / self.n_snps
            for i, tau in enumerate(np.atleast_1d(average_taus), 1):
                table.loc[table["Parameter"] == f"tau_beta_{i}", "Value"] = tau

        if isinstance(self.pi, dict):
            pis = dict_sum(self.pi, axis=0) / self.n_snps
        else:
            pis = self.pi

        for i in range(self.K):
            extra_theta.append({"Parameter": f"pi_{i + 1}", "Value": pis[i]})

        return pd.concat([table, pd.DataFrame(extra_theta)])

__init__(gdl, K=1, prior_multipliers=None, **kwargs)

Parameters:

Name Type Description Default
gdl

An instance of GWADataLoader

required
K

The number of causal (i.e. non-null) components in the mixture prior (minimum 1). When K=1, this effectively reduces VIPRSMix to the VIPRS model.

1
prior_multipliers

Multipliers for the prior precisions of the non-null mixture components (vector of size K). Smaller values correspond to wider components.

None
kwargs

Additional keyword arguments to pass to the VIPRS model.

{}
Source code in viprs/model/VIPRSMix.py
def __init__(self, gdl, K=1, prior_multipliers=None, **kwargs):
    """
    :param gdl: An instance of `GWADataLoader`
    :param K: The number of causal (i.e. non-null) components in the mixture prior (minimum 1). When `K=1`, this
        effectively reduces `VIPRSMix` to the `VIPRS` model.
    :param prior_multipliers: Multipliers for the prior precisions of the
        non-null mixture components (vector of size K). Smaller values
        correspond to wider components.
    :param kwargs: Additional keyword arguments to pass to the VIPRS model.
    """

    # Make sure that the matrices follow the C-contiguous order:
    kwargs["order"] = "C"

    super().__init__(gdl, **kwargs)

    # Sanity checks:
    assert K > 0  # Check that there is at least 1 causal component
    self.K = K

    if prior_multipliers is not None:
        assert len(prior_multipliers) == K
        self.d = np.array(prior_multipliers).astype(self.float_precision)
    else:
        self.d = 2 ** np.linspace(-min(K - 1, 7), 0, K).astype(self.float_precision)

    if np.any(self.d <= 0.0):
        raise ValueError("Prior precision multipliers must be strictly positive.")

    # Populate/update relevant fields:
    self.shapes = {c: (shp, self.K) for c, shp in self.shapes.items()}
    self.n_per_snp = {
        c: n[:, None].astype(self.float_precision, order=self.order)
        for c, n in self.n_per_snp.items()
    }
    self._e_step_statistics = None

compute_eta()

Returns:

Type Description

The mean for the effect size under the variational posterior.

Source code in viprs/model/VIPRSMix.py
def compute_eta(self):
    """
    :return: The mean for the effect size under the variational posterior.
    """
    return {c: (v * self.var_mu[c]).sum(axis=1) for c, v in self.var_gamma.items()}

compute_pip()

Returns:

Type Description

The posterior inclusion probability

Source code in viprs/model/VIPRSMix.py
def compute_pip(self):
    """
    :return: The posterior inclusion probability
    """
    return {c: gamma.sum(axis=1) for c, gamma in self.var_gamma.items()}

compute_zeta(sum_axis=1)

Returns:

Type Description

The expectation of the squared effect size under the variational posterior.

Source code in viprs/model/VIPRSMix.py
def compute_zeta(self, sum_axis=1):
    """
    :return: The expectation of the squared effect size under the variational posterior.
    """
    return {
        c: np.sum(
            v.astype(np.float64)
            * (
                self.var_mu[c].astype(np.float64) ** 2
                + (1.0 / self.var_tau[c].astype(np.float64))
            ),
            axis=sum_axis,
        )
        for c, v in self.var_gamma.items()
    }

e_step()

Run the E-Step of the Variational EM algorithm. Here, we update the variational parameters for each variant using coordinate ascent optimization techniques. The update equations are outlined in the Supplementary Material of the following paper:

Zabad S, Gravel S, Li Y. Fast and accurate Bayesian polygenic risk modeling with variational inference. Am J Hum Genet. 2023 May 4;110(5):741-761. doi: 10.1016/j.ajhg.2023.03.009. Epub 2023 Apr 7. PMID: 37030289; PMCID: PMC10183379.

Source code in viprs/model/VIPRSMix.py
def e_step(self):
    """
    Run the E-Step of the Variational EM algorithm.
    Here, we update the variational parameters for each variant using coordinate
    ascent optimization techniques. The update equations are outlined in
    the Supplementary Material of the following paper:

    > Zabad S, Gravel S, Li Y. Fast and accurate Bayesian polygenic risk modeling with variational inference.
    Am J Hum Genet. 2023 May 4;110(5):741-761. doi: 10.1016/j.ajhg.2023.03.009.
    Epub 2023 Apr 7. PMID: 37030289; PMCID: PMC10183379.
    """

    # Step 1: Initialize genome-wide sufficient statistics. The native
    # kernel adds each chromosome's contribution to these arrays.
    statistics = {
        "gamma_sum": np.zeros(self.K, dtype=np.float64),
        "component_zeta": np.zeros(self.K, dtype=np.float64),
        # gamma*log(gamma), null*log(null), gamma*log(var_tau), null
        "elbo": np.zeros(4, dtype=np.float64),
    }
    self._e_step_statistics = None
    if not hasattr(self, "zeta"):
        self.zeta = {}

    for c, shapes in self.shapes.items():
        if c not in self.zeta or self.zeta[c].shape != (shapes[0],):
            self.zeta[c] = np.empty(shapes[0], dtype=np.float64)

        # Get the priors:
        tau_beta = self.get_tau_beta(c)
        pi = self.get_pi(c)
        parameter_scale = getattr(self, "_parameter_scale", 1.0)
        scaled_n = self.n_per_snp[c] / parameter_scale

        lambda_min = self.lambda_min[c] if isinstance(self.lambda_min, dict) else self.lambda_min
        if not np.isscalar(lambda_min):
            lambda_min = np.asarray(lambda_min)[:, None]

        # Updates for tau variational parameters:
        self.var_tau[c] = (
            scaled_n * (1.0 + lambda_min) / self.sigma_epsilon
        ) + tau_beta
        np.log(self.var_tau[c], out=self._log_var_tau[c])

        if isinstance(self.pi, dict):
            log_null_pi = np.log(1.0 - self.pi[c].sum(axis=1))
        else:
            log_null_pi = np.ones_like(self.eta[c]) * np.log(1.0 - self.pi.sum())

        # Compute some quantities that are needed for the per-SNP updates:
        mu_mult = (
            scaled_n / (self.var_tau[c] * self.sigma_epsilon)
        ).astype(self.float_precision)
        u_logs = (
            np.log(pi)
            + 0.5 * (np.log(tau_beta) - self._log_var_tau[c])
        ).astype(self.float_precision)

        cpp_e_step_mixture(
            self.ld_left_bound[c],
            self.ld_indptr[c],
            self.ld_data[c],
            self.std_beta[c],
            self.var_gamma[c],
            self.var_mu[c],
            self.eta[c],
            self.q[c],
            self.eta_diff[c],
            log_null_pi,
            u_logs,
            self.var_tau[c],
            self._log_var_tau[c],
            np.sqrt(0.5 * self.var_tau[c]).astype(self.float_precision),
            mu_mult,
            self.zeta[c],
            statistics["gamma_sum"],
            statistics["component_zeta"],
            statistics["elbo"],
            self.dequantize_scale,
            self.threads,
            self.low_memory,
        )

    # Step 2: Publish the statistics only after every chromosome has
    # completed, so downstream updates cannot observe partial values.
    self._e_step_statistics = statistics

elbo(sum_axis=None)

Compute the scalar ELBO from E-step sufficient statistics.

Source code in viprs/model/VIPRSMix.py
def elbo(self, sum_axis=None):
    """Compute the scalar ELBO from E-step sufficient statistics."""

    statistics = getattr(self, "_e_step_statistics", None)
    if (
        statistics is None
        or sum_axis is not None
        or isinstance(self.pi, dict)
        or isinstance(self.tau_beta, dict)
    ):
        return super().elbo(sum_axis=sum_axis)

    # Step 1: Compute the likelihood contribution, which is independent
    # of the component-wise reductions cached by the E-step.
    parameter_scale = getattr(self, "_parameter_scale", 1.0)
    elbo = -np.log(2.0 * np.pi * self.sigma_epsilon)
    if "sigma_epsilon" not in self.fix_params:
        elbo -= 1.0
    else:
        beta_eta = sum(
            self.std_beta[c].astype(np.float64).dot(
                self.eta[c].astype(np.float64)
            )
            for c in self.shapes
        )
        elbo -= (1.0 / self.sigma_epsilon) * (
            1.0
            - 2.0 * beta_eta / parameter_scale
            + self._sigma_g / parameter_scale
        )
    elbo *= 0.5 * self.n

    # Step 2: Reconstruct all mixture terms from the cached scalar and
    # component statistics, reducing the remaining work to O(K).
    gamma_sum = statistics["gamma_sum"]
    component_zeta = statistics["component_zeta"]
    gamma_log_gamma, null_log_null, gamma_log_var_tau, null_sum = (
        statistics["elbo"]
    )
    pi = np.asarray(self.pi, dtype=np.float64)
    tau_beta = np.asarray(self.tau_beta, dtype=np.float64)
    null_pi = 1.0 - pi.sum()

    elbo -= gamma_log_gamma - np.dot(gamma_sum, np.log(pi))
    elbo -= null_log_null - null_sum * np.log(null_pi)
    elbo += 0.5 * (
        gamma_sum.sum()
        - gamma_log_var_tau
        + np.dot(gamma_sum, np.log(tau_beta))
    )
    elbo -= 0.5 * np.dot(tau_beta, component_zeta)
    return elbo

get_average_effect_size_variance()

Returns:

Type Description

The average per-SNP variance for the prior mixture components

Source code in viprs/model/VIPRSMix.py
def get_average_effect_size_variance(self):
    """
    :return: The average per-SNP variance for the prior mixture components
    """

    total = self._prior_variance_sum(self.tau_beta)
    return total / (
        self.n_snps * getattr(self, "_parameter_scale", 1.0)
    )

get_null_pi(chrom=None)

Get the proportion of SNPs in the null component

Parameters:

Name Type Description Default
chrom

If provided, get the mixing proportion for the null component on a given chromosome.

None

Returns:

Type Description

The value of the mixing proportion for the null component

Source code in viprs/model/VIPRSMix.py
def get_null_pi(self, chrom=None):
    """
    Get the proportion of SNPs in the null component
    :param chrom: If provided, get the mixing proportion for the null component on a given chromosome.
    :return: The value of the mixing proportion for the null component
    """

    pi = self.get_pi(chrom=chrom)

    if isinstance(pi, dict):
        return {c: 1.0 - c_pi.sum(axis=-1) for c, c_pi in pi.items()}
    return 1.0 - np.sum(pi, axis=-1)

get_proportion_causal()

Returns:

Type Description

The proportion of variants in the non-null components.

Source code in viprs/model/VIPRSMix.py
def get_proportion_causal(self):
    """
    :return: The proportion of variants in the non-null components.
    """
    if isinstance(self.pi, dict):
        return np.dtype(self.float_precision).type(
            sum(np.sum(pis, dtype=np.float64) for pis in self.pi.values())
            / self.n_snps
        )
    return np.sum(self.pi)

initialize_theta(theta_0=None)

Initialize the global hyperparameters of the model

Parameters:

Name Type Description Default
theta_0

A dictionary of initial values for the hyperparameters theta

None
Source code in viprs/model/VIPRSMix.py
def initialize_theta(self, theta_0=None):
    """
    Initialize the global hyperparameters of the model
    :param theta_0: A dictionary of initial values for the hyperparameters theta
    """

    theta_0 = {} if theta_0 is None else theta_0.copy()
    theta_0.update(self.fix_params)
    if "tau_beta" in self.fix_params and "tau_betas" not in self.fix_params:
        theta_0.pop("tau_betas", None)

    # ----------------------------------------------
    # (1) Initialize pi from a uniform
    if "pis" in theta_0:
        self.pi = self._cast_parameter(theta_0["pis"])

        # If only the total causal proportion is fixed, preserve the
        # supplied component ratios and rescale them to that total.
        if "pi" in self.fix_params and "pis" not in self.fix_params:
            overall_pi = self.fix_params["pi"]
            if isinstance(self.pi, dict):
                self.pi = {
                    c: overall_pi * pi / pi.sum(axis=1, keepdims=True)
                    for c, pi in self.pi.items()
                }
            else:
                self.pi *= overall_pi / self.pi.sum()
    else:
        overall_pi = theta_0["pi"] if "pi" in theta_0 else np.random.uniform(
            low=max(0.005, 1.0 / self.n_snps), high=0.1
        )

        self.pi = overall_pi * np.random.dirichlet(np.ones(self.K))

    # ----------------------------------------------
    # (2) Initialize sigma_epsilon and component precisions. Under the
    # standardized model, h2 = sum_jk(pi_jk / tau_jk) = 1 - sigma_epsilon.
    if "tau_betas" in theta_0:
        self.tau_beta = self._cast_parameter(theta_0["tau_betas"])
    elif "tau_beta" in theta_0:
        self.tau_beta = theta_0["tau_beta"] * self.d
    else:
        if "sigma_epsilon" in theta_0:
            h2g_estimate = 1.0 - theta_0["sigma_epsilon"]
        else:
            try:
                h2g_estimate = np.clip(simple_ldsc(self.gdl), 1e-3, 1.0 - 1e-3)
            except Exception:
                h2g_estimate = np.random.uniform(low=0.001, high=0.999)

        self.tau_beta = self.d * (
            self._prior_variance_sum(self.d) / h2g_estimate
        )

    if "sigma_epsilon" in theta_0:
        self.sigma_epsilon = theta_0["sigma_epsilon"]
    else:
        self.sigma_epsilon = np.clip(
            1.0 - self._prior_variance_sum(self.tau_beta),
            a_min=1e-4,
            a_max=1.0 - 1e-4,
        )

    # Cast all the hyperparameters to conform to the precision set by the user:
    self.sigma_epsilon = np.dtype(self.float_precision).type(self.sigma_epsilon)
    self.pi = self._cast_parameter(self.pi)
    self.tau_beta = self._cast_parameter(self.tau_beta)
    self.lambda_min = self._cast_parameter(self.lambda_min)
    self._sigma_g = np.dtype(self.float_precision).type(0.0)

initialize_variational_parameters(param_0=None)

Initialize variational parameters and invalidate cached statistics.

Source code in viprs/model/VIPRSMix.py
def initialize_variational_parameters(self, param_0=None):
    """Initialize variational parameters and invalidate cached statistics."""

    super().initialize_variational_parameters(param_0)
    self._e_step_statistics = None

set_fixed_params(fix_params)

Set fixed mixture hyperparameters, including their plural aliases.

Source code in viprs/model/VIPRSMix.py
def set_fixed_params(self, fix_params):
    """Set fixed mixture hyperparameters, including their plural aliases."""

    assert isinstance(fix_params, dict), "The fixed parameters must be provided as a dictionary."

    # The plural forms fix component-specific values; the singular forms
    # fix only the total probability or shared precision scale.
    if "pis" in fix_params:
        self.fix_params.pop("pi", None)
    elif "pi" in fix_params:
        self.fix_params.pop("pis", None)
    if "tau_betas" in fix_params:
        self.fix_params.pop("tau_beta", None)
    elif "tau_beta" in fix_params:
        self.fix_params.pop("tau_betas", None)

    self.fix_params.update(fix_params)

    if "sigma_epsilon" in fix_params:
        self.sigma_epsilon = np.dtype(self.float_precision).type(
            fix_params["sigma_epsilon"]
        )
    if "lambda_min" in fix_params:
        self.lambda_min = self._cast_parameter(fix_params["lambda_min"])
    if "tau_betas" in fix_params:
        tau_beta = self._cast_parameter(fix_params["tau_betas"])
        if isinstance(tau_beta, dict):
            self.tau_beta = {
                c: tau / getattr(self, "_parameter_scale", 1.0)
                for c, tau in tau_beta.items()
            }
        else:
            self.tau_beta = tau_beta / getattr(self, "_parameter_scale", 1.0)
    elif "tau_beta" in fix_params:
        self.tau_beta = (
            fix_params["tau_beta"] * self.d
            / getattr(self, "_parameter_scale", 1.0)
        )
    if "pis" in fix_params:
        self.pi = self._cast_parameter(fix_params["pis"])
    elif "pi" in fix_params and self.pi is not None:
        overall_pi = fix_params["pi"]
        if isinstance(self.pi, dict):
            self.pi = {
                c: overall_pi * pi / pi.sum(axis=1, keepdims=True)
                for c, pi in self.pi.items()
            }
        else:
            self.pi *= overall_pi / self.pi.sum()

to_theta_table()

Returns:

Type Description

A pandas DataFrame containing information about the estimated hyperparameters of the model.

Source code in viprs/model/VIPRSMix.py
def to_theta_table(self):
    """
    :return: A `pandas` DataFrame containing information about the estimated hyperparameters of the model.
    """

    table = super().to_theta_table()

    extra_theta = []

    if isinstance(self.tau_beta, dict):
        average_taus = dict_sum(self.tau_beta, axis=0) / self.n_snps
        for i, tau in enumerate(np.atleast_1d(average_taus), 1):
            table.loc[table["Parameter"] == f"tau_beta_{i}", "Value"] = tau

    if isinstance(self.pi, dict):
        pis = dict_sum(self.pi, axis=0) / self.n_snps
    else:
        pis = self.pi

    for i in range(self.K):
        extra_theta.append({"Parameter": f"pi_{i + 1}", "Value": pis[i]})

    return pd.concat([table, pd.DataFrame(extra_theta)])

update_pi()

Update the prior mixing proportions pi

Source code in viprs/model/VIPRSMix.py
def update_pi(self):
    """
    Update the prior mixing proportions `pi`
    """

    if "pis" not in self.fix_params:
        statistics = getattr(self, "_e_step_statistics", None)
        if statistics is None:
            pi_estimate = dict_sum(self.var_gamma, axis=0)
        else:
            pi_estimate = statistics["gamma_sum"].copy()

        if "pi" in self.fix_params:
            # If the user provides an estimate for the total proportion of causal variants,
            # update the pis such that the proportion of SNPs in the null component becomes 1. - pi.
            pi_estimate = self.fix_params["pi"] * pi_estimate / pi_estimate.sum()
        else:
            pi_estimate /= self.n_snps

        # Set pi to the new estimate:
        self.pi = self._cast_parameter(pi_estimate)

update_sigma_epsilon()

Update residual variance without promoting float32 models.

Source code in viprs/model/VIPRSMix.py
def update_sigma_epsilon(self):
    """Update residual variance without promoting float32 models."""

    super().update_sigma_epsilon()
    self.sigma_epsilon = np.dtype(self.float_precision).type(
        self.sigma_epsilon
    )

update_tau_beta()

Update the prior precision (inverse variance) for the effect sizes, tau_beta

Source code in viprs/model/VIPRSMix.py
def update_tau_beta(self):
    """
    Update the prior precision (inverse variance) for the effect sizes, `tau_beta`
    """

    if "tau_betas" not in self.fix_params and "tau_beta" not in self.fix_params:
        # Estimate a shared precision scale and apply the component-specific
        # precision multipliers. This is the constrained mixture M-step.

        statistics = getattr(self, "_e_step_statistics", None)
        if statistics is None:
            zetas = sum(self.compute_zeta(sum_axis=0).values())
            total_responsibility = dict_sum(self.var_gamma)
        else:
            zetas = statistics["component_zeta"]
            total_responsibility = statistics["gamma_sum"].sum()

        global_tau = total_responsibility / np.dot(self.d, zetas)
        # Preserve the exact component ratios while enforcing tau_k >= 1
        # on the original (unscaled) precision scale.
        global_tau = np.maximum(
            global_tau,
            1.0 / (np.min(self.d) * getattr(self, "_parameter_scale", 1.0)),
        )

        self.tau_beta = self._cast_parameter(self.d * global_tau)