Bayesian regression with checked summaries, Glist genotypes, posterior quantities and scoring.
The authoritative R interface contract defines the bayes, sbayes, blr, mbayes, msbayes and mblr interfaces. The initial bayes/mbayes packed and sbayes/msbayes marginal-summary BayesC/BayesR routes are implemented, along with blr/mblr exact common-design cross-products. All six C/R fitters support exact same-build continuation and optional posterior quantities within their route-specific contracts. All 24 initial method/interface combinations are implemented within documented native limits. The common result boundary validates schema and scientific axes, preserves logical chains, records software versions and supplies availability reasons for unsupported quantities. Separate method formats retain their scientific meanings. Optional native extensions and broad qualification remain separate work.
Choose a fitter and method
This overview describes the frozen gbayes 0.1.16 developer build. Choose the fitter from your input, then use the case-sensitive method and algorithm values below. Method matrix and qualification limits
Input
Fitter
Individual genotypes and one quantitative trait
bayes()
Individual genotypes and multiple jointly fitted traits
mbayes()
GWAS summaries and prepared LD for one trait
sbayes()
Summaries and LD for multiple traits, studies or populations
msbayes()
Prepared cross-products XX and Xy
blr() for one response, mblr() for multiple responses
method
bayes
sbayes
mbayes
msbayes
bayesC
mcmc, vbayes
mcmc, vbayes
mcmc
mcmc
bayesR
mcmc
mcmc
mcmc
mcmc
bayesRC
mcmc
mcmc
mcmc
mcmc
bayesCM (mr.mash covariance mixture)
vbayes
—
vbayes
—
bayesFR (MegaBayesC marker factors)
—
—
mcmc
—
bayesFA (MegaLMM relationship factors)
—
—
mcmc
—
marker_gaussian
pcg, gaussian with co-data
pcg
—
—
elastic_net
coordinate_descent
coordinate_descent
coordinate_descent
coordinate_descent
laplace_gaussian
vbayes
—
vbayes
—
normal_mixture (prepared or streamed X)
vbayes
—
—
—
point_normal
—
mcmc
—
—
continuous_shrinkage
—
mcmc
—
mcmc
variational (point-normal)
—
vbayes
—
—
mixture_variational (Gaussian mixture)
—
vbayes
—
—
multi_effect (scalar IBSS)
—
ibss
—
—
mvsusie (shared LD)
—
—
—
ibss
multisusie (separate study LD)
—
—
—
ibss
coef(fit) returns marker-by-trait effects where the model identifies them. Use gbayes::fit_contract(fit)$units to check their scale and gbayes::diagnostics(fit) to inspect the fit. bayesFA returns genetic fitted values and covariance. bayesFR reconstructs direct and factor-mediated marker effects. The cross-product companions cover BayesC, BayesR and covariance mixtures under their prepared-input contracts. Fitter contracts
Both require prepared packed Glist genotypes and complete finite outcomes. The joint matrices must be labelled in trait order; pi is aligned to the declared activity-pattern set. Initial joint learning is off; enable updateB, updateE or updatePi with the corresponding proper priors. Scalar defaults use h2=.5, BayesC pi=.001 or BayesR weights (.95,.02,.02,.01), df=4 learning priors and learned variances/weights. Trait centering preserves original response units; the likelihood dimension defaults to n-1. Existing HWE genotype coding is retained. Dense X and annotation requests are explicitly unavailable in this slice.
Retained indices are multiples of nthin; all nit post-burn transitions run, including a remainder. This is implemented by an exact native retention-phase translation for these ordinary models. Final seeded states are unchanged by the translation. Diagnostics identify their actual native checkpoint schedule; they do not claim unthinned all-marker capture. Full effect draws are unavailable. Scalar total-memory estimation and actual worker counts are unavailable; joint native reports are retained. Prediction uses saved training frequencies/scales and pooled effect means by default; chain selects one chain. Phenotype prediction adds the fitting-sample intercept and uses no target outcomes.
Individual C/R also supports native posterior-quantity capture:
Use mbayes with the same posterior keys and trait-named phenotype variances. Reference must be aligned sparse LD; genetic covariance is B’ R B on that declared standardized reference, separate from latent vb or training covariance. Partition labels are mutually exclusive and named in fitted marker order. Full group/trait covariance includes cross-group LD. Genetic correlations retain their positive-variance conditioning counts; h2 ratios need compatible explicit phenotypeVariance. Neither summing marginal effect variances nor applying the quadratic to posterior mean effects substitutes for these draw-wise quantities.
Selected score moments use saved fitting HWE coding, including when target frequencies differ. Partial marker targets report coverage and selected marker domain. Their uncertainty omits phenotype residual noise, cross-person covariance and reference uncertainty. Ordinary predict() remains mean-effect projection; availability\(prediction refers to stored capture moments. Capture requests apply
to each call separately, including continuation. Genetic/partition traces follow
retainDiagnostics; score traces use prediction\)retainDraws independently. No full effect draws are enabled. Resources are fingerprinted before/after capture, and managed memory guards include reference loading, targets and output copies. See the capture contract.
Individual C/R fits support exact continuation from native checkpoints:
Use mbayes for a saved joint fit. Nit adds transitions; omitted method, traits, priors, learning settings, thinning and chain seeds inherit the saved model. Nburn must be omitted or zero. The original global thinning phase is preserved, and diagnostics record absolute retained transitions. A segment with no scheduled draw fails. Workers and diagnostic capture may change. The resumed fit reports only the added segment’s summaries, and can itself be resumed; earlier intervals are not automatically pooled. Checkpoints require unchanged outcomes, ordered selections, genotype resource bytes and the same qualified bundled build, R and platform. Full active BED/BIM/FAM hashing adds streaming I/O on fit/resume. Current qualification is Windows; other runtime layouts report restartState unavailable. Other methods/interfaces do not acquire continuation from this change. See the exact continuation contract.
For marginal-summary BayesC/BayesR, use the corresponding summary interfaces:
Each table has rsids, chr, pos, ea, nea, b, seb and n, covering its reference exactly. The adapter aligns markers/coordinates/alleles and uses standardized marginal effects b/sqrt(nseb2+b2). Scalar defaults initialize vb=h2/(pmass) and ve=1-h2, with h2=.5. Sparse residual learning uses the existing reference-LD approximation and adjustment .9; this is recorded in input$nativeControl. For fixed residuals set updateE=FALSE. Explicit exact in-sample normalization retains the native same-sample, complete-LD checks.
Sbayes also accepts representation=“block_eigen” with verified Glist blocks; its residual learning uses the retained likelihood. Algorithm stays “mcmc”. Msbayes currently accepts sparse LD only. Independent providers can use a named Glist list and different marker sets, with trait mapping named in study order. Their residual variances are named by study. Shared-LD correlated summaries require sampling=list(dependence=“shared_ld”, covariance=Ve), or supply ve=Ve with that dependence and omit covariance. Shared-LD N must match across traits and markers. Joint learning defaults off; covariance learning requires exact response_crossproduct, likelihood_dimension, nue and prior$veScale. Genetic covariance, sampling covariance and sample overlap are distinct quantities.
Both summary interfaces return the common bayesfit, preserve all chains and record the same retention schedule as the individual adapters. Scalar global memory estimates/actual workers and full effect draws remain unavailable. Summary prediction fails explicitly because training coding and intercepts are not identified. Annotation remains unavailable in these C/R adapters.
Use msbayes with the same posterior keys. Reference is an explicit sparse-LD Glist aligned to every fitted marker, including the ordered union for different study references. It is not chosen from the fitting providers automatically. The reported draw-wise B’ R B uses this declared standardized reference, separately from latent vb, sampling covariance, fitting LD approximations or eigen truncation. A denominator of one applies only to compatible standardized phenotypes; provide compatible trait-named phenotypeVariance explicitly for h2. No reference uncertainty or automatic raw-unit conversion is included.
Partition-only requests report activity without inventing a genetic reference. With reference, partition covariance includes cross-group LD and is not a set of additive heritability contributions. Genetic correlations retain their positive-variance conditioning counts. Genetic/partition/h2 traces follow control$retainDiagnostics; moments remain available with traces disabled. Quantity summaries preserve native interval/diagnostic availability separately from parameter summaries. Singleton axes and per-chain moments are preserved; full effect draws and per-chain quantity intervals remain unavailable.
Capture is per call, including continuation, and summarizes only that call’s retained segment. Requests can change while states/RNG and parameter traces remain unchanged. Reference fingerprints and managed allocation guards apply; disk LD still requires one worker. Summary prediction requests remain rejected. See the summary capture contract.
Summary C/R fits can be continued from full native checkpoints:
saveRDS(fit, "summary-fit.rds")more <- gbayes::sbayes(stat, Glist=g, nit=500,continuation=readRDS("summary-fit.rds"))# Use msbayes for a saved joint summary fit; omitted sampling is inherited.gbayes::diagnostics(more)$execution$continuation
Nit adds transitions, with no repeated burn-in. Omitted model settings, representation, provider mapping, scientific controls, thinning and chain seeds inherit the original fit. Retained indices preserve the global thinning phase. Resumed summaries and intervals cover only the added segment; the new fit can itself be resumed. Storage mode, residual/normalization/eigen policies, sampling dependence/covariance/scatter and study sample sizes remain fixed. Worker count, diagnostic capture, interval probability and memory/entry budgets may change within existing backend limits; disk LD still requires one worker. Checkpoints bind harmonized summaries, full prepared LD bytes, reference descriptors and eigen block definitions, with the same bundled-Windows runtime qualification as individual C/R. Hashing adds streaming I/O. Specialized engines and other methods remain outside this contract. See the summary continuation contract.
Both reuse existing native mean-field optimizers on common-N sparse-LD inputs. Variational fixes pi/h2 (defaults .01/.5), slab variance h2/(p*pi), and unit likelihood residual variance. Mixture_variational requires absolute component variances through vb; pi supplies strictly positive normalized weights or defaults to uniform. At most one zero spike is allowed, in any component position. Pure Gaussian mixtures and an all-zero point mass retain their native meanings. Without a spike, PIPs equal one by definition. No h2/gamma calibration is applied to explicit mixture variances. All learning flags default FALSE; TRUE fails. Prior is empty, with no duplicate nested variance/weight spellings.
Nit defaults 1000 and limits sweeps per window. Control tolerance defaults 1e-8; windows defaults to one whole-panel range. Supply an ordered two-column matrix of one-based inclusive ranges, covering all markers without gaps or duplicates; overlaps are permitted. Each window is optimized once with the global residual and cross-window LD retained. Nonconvergent windows raise an error. A completed multi-window fit is labelled windowed_approximation, not whole-panel convergence. The native whole-panel flag identifies a coordinate fixed point, not a global optimum or exact joint posterior.
Means, variational marginal variances and PIPs use the common bayesfit accessors. Under correlated LD, mean-field variances differ from exact joint posterior marginal variances. Native objective endpoints omit the fixed log p(Y|b=0) baseline; they are relative bounds, not absolute ELBOs or full histories. Responsibilities, parameter posterior estimates, sampled draws and chains are unavailable. Final effects are the optimizer mean matrix. Explicit MCMC-only arguments fail, and ncores=1 is required. No prediction from unknown training coding, annotations, generic posterior capture or continuation is added.
Memory or disk storage uses controls memoryLimit (256 MiB) and maxLdEntries (1e7). Managed preflight counts LD/cache payloads, replicated native mixture priors/states and R/native copies. Native disk page/window limits still apply; these estimates do not measure process RSS or qualify routine genome-wide use. See ?gbayes::variational for the exact argument and window contracts.
Both require common-N summaries and sparse LD. Consecutive seeded logical chains share one prepared reference and run serially; ncores>1 fails. Defaults are 1000 postburn transitions, 500 burnin, thinning one, two chains and seed one. No native RNG checkpoints, prediction from unknown coding, generic posterior capture or annotation composition are exposed by these adapters.
Point-normal defaults to pi=.01, h2=.5, slab variance h2/(p*pi) and unit residual variance. Its means/PIPs average conditional expectations at every postburn sweep, so nthin must equal one. UpdateB and updatePi both default FALSE; both TRUE select the existing coupled pi sampling/h2 quadratic-form update. This is the 2020-style auto policy, not the expanded later LDpred2-auto algorithm, independent variance learning or posterior heritability inference. Control sparseEffects enables the existing threshold approximation and cannot accompany auto updates. Memory or disk LD is supported. Vb/ve/gamma/nub/nue/updateE and nested prior settings are unsupported. Native p/h2 paths support scoped diagnostics; effect variances are unavailable.
Continuous shrinkage requires memory LD and verified Glist LD blocks; no duplicate offsets are accepted. Prior globalScale defaults one. UpdateB controls global-scale learning (default FALSE); local scales and residual scale always update, so updateE=FALSE fails. Other scalar scale/probability arguments are unsupported. Native a=1,b=.5, the local-scale cap and update order remain unchanged. Completed-multiple thinning preserves all transitions and final effects. Local/global/residual means are available; PIPs, effect second moments, parameter/effect traces and trace convergence diagnostics remain unavailable. Common effect summaries mark unavailable moments with NA.
Control retainDiagnostics, memoryLimit, storage and maxLdEntries apply, with maximumBlockDimension and denseWorkspaceLimit for shrinkage. Managed memory preflight includes shared resources, chain outputs, PN’s mandatory full paths and native dense workspace reservations. These estimates are not process-RSS measurements or large-data qualification. See the installed method help ?gbayes::point_normal for the full crosswalk.
For annotation-dependent scalar mixtures, use bayesRC:
A is a finite numeric matrix with exact fitted marker row names and unique non-intercept columns. The native sampler centers columns without rescaling; annotations may overlap. Only the component role is enabled. Pi defaults to BayesR weights (.95,.02,.02,.01), is normalized and initializes zero-slope continuation-probit coefficients. It does not define their priors. Gaussian intercept prior means default to zero and intercept/slope SDs default to one. Supply native component keys initial, intercept_means, intercept_prior_sd, coefficient_prior_sd or update_every for explicit choices. Initial is a labelled coefficient-by-stick matrix; explicit initial and explicit pi conflict. With explicit starts and omitted pi, mean initial marker class probabilities supply nominal slab-scale calibration.
UpdatePi defaults TRUE and learns annotation intercepts/slopes, with no global Dirichlet update. Use the direct flag rather than component\(learn. Individual
vb/ve, updateB/updateE and nub/nue retain the scalar C/R rules. Summary global
updateE defaults FALSE and TRUE fails. Its separate control\)blockResidual has native mode all_mix by default; sample, mix and fixed are explicit alternatives. Ve initializes every block; nue (default four) and prior$veScale (default (nue-2)/nue*ve) set learned block priors, and are rejected with fixed blocks. Block scatters/dimensions use retained eigen coordinates. The native all_mix/mix threshold and selection policies remain unchanged; sample updates every block. Sbayes requires one common N and verified Glist LD blocks.
Defaults are nit=1000, nburn=500, nthin=1, nchains=2, ncores=1 and seed=1. The native total-sweep annotation cadence is unchanged by completed-multiple retention, including remainder schedules. Coefficient arrays preserve retained draw/chain/coefficient/stick axes, and final states remain chain-specific. Prior probabilities, allocations and PIPs are different quantities. Native coefficient diagnostics have their original scope. Optional posterior capture, continuation, cross-product RC, annotation hypervariance learning and complete sblr algorithm/output parity remain unavailable. No new sampler or general mixing/calibration qualification is introduced.
For joint individual BayesRC, keep residual covariance fixed and supply activity-pattern probabilities separately from positive magnitude weights:
Vb and Ve must be SPD matrices labelled in selected trait order. pi follows the declared activity-pattern order, with null first; the default two-trait order is 00, 10, 01, 11. Each annotation design has exact fitted-marker rows and at least one uniquely named non-intercept column. Pattern/component roles can be used separately; unannotated probability roles remain fixed. updatePi learns only the supplied probit roles, without global Dirichlet updates. Optional annotation$variance scales every positive magnitude and has its own learn flag. Probit intercept priors default to zero independently of initial pi/component weights. Coefficients and draws are role-labelled lists; variance coefficients have no stick axis. Ordinary prediction uses saved training HWE coding. Residual learning, posterior capture, continuation and saved-fit mapping remain unavailable for joint RC. See the full joint contract and the runnable RDS-input example at tools/examples/gbayes/joint-bayesrc.R.
For joint summary BayesRC, use the same annotation roles with an explicit sampling model and fixed sampling/residual covariance:
Omega is a labelled SPD sampling-error covariance on the standardized summary scale, distinct from genetic covariance or raw sample-overlap counts. Shared LD requires common N and complete common markers. Alternatively declare sampling=list(dependence="independent", residual_variance=c(height=1,yield=1)) and omit ve; independent studies can use separate named references, sample sizes and local marker sets with the existing explicit study-to-trait mapping. Annotation rows follow the ordered global marker union. Missing local markers provide no likelihood information; do not assert independence for overlapping studies. Summary effects retain standardized units, with unidentified training coding/intercepts. Ordinary predict() is unavailable, and scoring uses the existing explicit summary conversion inputs. Residual learning, continuation, posterior capture and saved-fit mapping stay gated. See the summary annotation contract and tools/examples/gbayes/summary-joint-bayesrc.R for the runnable RDS-input example.
For fixed Gaussian marker priors, both scalar interfaces accept named means and variances:
Omitted means default to zero. Vectors are named for every fitted marker and aligned independently by name. Zero variance fixes an effect at its supplied mean, with its LD/cross-product offset retained. At least one variance is positive. Individual means use original phenotype units per training-HWE-scaled genotype; summary means use standardized reference-allele coordinates, not raw GWAS beta units. Prior means already refer to the reference allele even when GWAS input rows require harmonization. The fitter does not estimate priors or convert source-study units automatically. Derive data-dependent priors using training-only data or a declared independent source.
The individual native provider saves selected-training coding and the phenotype mean, supporting ordinary prediction. Summary coding/intercepts stay unidentified. nit caps PCG iterations; control$tolerance sets the existing relative gate. Outputs contain posterior means and solve diagnostics, with no posterior variance, spike PIPs or sampled chains. See the Gaussian contract and the runnable RDS-input example at tools/examples/gbayes/marker-gaussian.R.
For covariance-mixture regression, use the common fitters:
fit <- gbayes::mbayes(data=phenotypes, Glist=genotypes,trait=c("height", "yield"), method="bayesCM")# algorithm="vbayes" is the default for bayesCM.scores <-predict(fit, list(Glist=target_genotypes))
The phenotype table contains unique character id and numeric trait columns. Missing outcomes select the existing published mr.mash missing-data route. Defaults use training variances v and p fitted markers: with h2=.5, the dictionary contains zero, independent diag(h2v/p), and a shared rank-one pattern, with uniformly initialized learned weights. The default fixed residual covariance is diag((1-h2)v). These are working scale assumptions, not estimated heritability or learned covariance matrices; supply explicit prior$covariance and ve when appropriate. nit caps VI sweeps (default 1000), updatePi controls weight learning and updateE=TRUE enables diagonal residual EB with diagonal initial ve; use control=list(residualLearning=“full”) for full EB with correlated residuals. Prior contains covariance only; pi supplies weights. Explicit updateB/gamma/vb/nub/nue and MCMC-only arguments nburn/nthin/nchains/seed fail. Only one worker is supported.
Use bayes for one trait, mbayes for at least two, or blr/mblr for explicit XX/Xy/yy. Cross-products require dictionary and residual covariance on declared units. Exact EB requires yy; likelihood=“reference_ld” keeps residuals fixed. Without yy, fixed-residual inference exposes a relative objective rather than an absolute ELBO. Saved coding enables cross-product prediction; missing coding is not inferred. No marginal-GWAS conversion is added.
Individual CM uses native sample-count normalization n. Exact cross-product CM defaults to n and accepts an explicit effective likelihoodDimension >2 and <=n for a common projected design. This is separate from C/R’s n-1 default. Complete scalar packed CM prepares a bounded dense Gram from the HWE operator; joint CM keeps the native observation-space route. Scalar packed missing outcomes and dense X remain unqualified. All traits need observed outcomes, and dictionary/ residual defaults need at least two varying observed outcomes per trait.
Variational bayesfit reports optimization/EB diagnostics and dictionary responsibilities, without chains, sampled draws or R-hat/ESS. Global nonzero probability is anyPip; multivariate trait PIPs remain unavailable and summary shows NA. Missing-outcome augmented bounds and observed likelihood at fitted means have separate labels. Hitting nit is not convergence. The existing gbayes dispatcher and historical native helpers retain their separate scope.
For factor models, use mbayes with genotype-backed Glist:
BayesFA uses the existing one-kernel MegaLMM sampler. The adapter constructs an additive relationship internally using selected training genotypes, excludes and reports estimated monomorphic markers, mean-imputes missing calls in centered coordinates, and normalizes the mean diagonal to one. All-missing markers fail. No ridge, supplied K, Glist$K or second decoded genotype panel is introduced. Frequency/sample/marker selections and construction accounting are recorded; control=list(retainKernel=TRUE) optionally saves the bounded kernel for inspection. The kernel is constructed once and shared across chains.
BayesFR uses the native MegaBayesC marker-factor and direct-effect sampler with selected-training sample-SD coding. Total effects are reconstructed per native draw before averaging; marker-factor, direct and loading activity remain separate. Trait-total PIPs are unavailable. Both methods allow missing outcomes and require all selected Glist samples exactly once, at least two traits and some observed outcomes in every trait. Arbitrary fixed-effect estimation is not added.
Defaults are two factors, nit=1000 post-burn transitions, nburn=1000, nthin=1, nchains=2, ncores=1 and seed=1. Chains use consecutive uint32 seeds and remain separate. The existing factor runner is serial; ncores>1 fails. Nit must be divisible by nthin; retained indices are completed post-burn multiples without a retention-phase shift. No execution aliases in control are accepted.
BayesFR updateB/updatePi map to slab/inclusion learning in marker-factor, direct and loading groups; updateE maps to trait and factor noise. Defaults retain native learning. Loading-order shrinkage still updates with updateB=FALSE. BayesFA rejects those generic switches in favor of explicit factor/grid priors. H2/pi/gamma/vb/ve/nub/nue, dense X, annotation, optional posterior capture and continuation remain unsupported here.
Common bayesfit results preserve invariant posterior means, retained arrays, per-chain access and native final states. G/R traces use the existing native R-hat/ESS/MCSE engine; they are not an all-marker mixing certificate. Final factor states lack RNG state and are not continuation checkpoints. Set control=list(retainDraws=FALSE) to omit invariant capture without changing the seeded trajectories or posterior means. Memory guards include transient draw copies and native estimates, not measured process-RSS ceilings.
BayesFA has no marker coefficients. Predict accepts NULL or stored training IDs for native genetic/phenotype fitted summaries; new-kernel prediction is unavailable. BayesFR uses pooled or selected-chain total effects and saved coding for genotype prediction, adding the corresponding intercept means for phenotype scores. Training phenotypeFitted includes latent residual-factor contributions and is separate from genotype-only prediction. No target outcomes are consumed.
Bounds remain n<=256, traits<=128, factors<=16 and bayesFR markers<=4096. Dense relationship storage is quadratic. Multiple kernels, general covariates and genome-wide factor performance remain unqualified. Full-model MegaBayesC mixing failures remain unresolved and paused. Existing native/dispatcher routes keep their separate documented contracts.
The existing dispatcher remains available for unmigrated routes:
Release status (22 October 2026): the public source repository supplies gbayes 0.1.1. This guide also describes the current development source, version 0.1.6. In particular, gbayes::blr() is a development interface and is absent from the public 0.1.1 archive. Check packageVersion("gbayes") and installed help before using an example. See the source-package release status.
Development adaptive multivariate and factor models
gbayes_multitrait(data, method, prior, control) exposes mr_mash, mr_mash_missing, mr_mash_rss, mega_lmm and mega_bayesc through the standalone gbayes R package. These method names also work with gbayes(data=..., method=..., prior=..., control=...) without Glist. They are development interfaces absent from the public 0.1.1 archive. Method names refer to our native implementations; upstream software is a pinned test reference and is not called during fitting.
Individual marker routes use numeric counted-dosage X and outcome Y matrices, unique sample row names, marker/trait column names, counted alleles in marker order and nonempty provenance. mr.mash also requires trait residual covariance V and a named PSD covariance dictionary with mixture weights:
# X and Y have matching sample row labels; alleles follow X column order.fit <- gbayes::gbayes_multitrait(data=list(X=X, Y=Y, V=diag(ncol(Y)), alleles=alleles,provenance="training panel"), method="mr_mash",prior=list(covariance=list(zero=0*diag(ncol(Y)),independent=diag(ncol(Y))), weights=c(.5,.5)),control=list(maximum_sweeps=1000, residual_learning="fixed"))scores <-predict(fit, X_target, alleles)
The missing-outcome route accepts NA/NaN in Y and returns observed masks and conditional imputation summaries. Complete mr.mash rejects missing outcomes. Optional full/diagonal residual EB is explicit. The RSS adapter takes C=X’X, S=X’Y, V, training centers/scales, common sample size and an explicit exact or reference_ld likelihood; absolute ELBO and residual learning need exact H=Y’Y. It does not reinterpret marginal GWAS coefficients as S. Predictions reuse training coding and validate marker/allele order.
For individual mr.mash and MegaBayesC, replace X with Glist=panel inside data, or pass Glist=panel to gbayes(). Y row labels select and order the training samples; data$markers optionally selects/orders markers across files. Alleles default to Glist A1 and supplied alleles must match. Direct PLINK inputs use bed=list(bedfiles=..., bimfiles=..., famfiles=...), with ordinary sidecar defaults. These adapters call installed gbase preparation and reuse native packed operations, without constructing decoded genotype or Gram matrices. Missing genotypes are imputed from selected-training frequencies. mr.mash BED retains HWE standardization; MegaBayesC retains its sample-SD or centered-raw coding. These scales define different effect priors.
predict(fit, list(Glist=target_panel, ids=target_ids)) uses saved training frequencies/scales, including imputation, rather than estimating target coding. Packed fits additionally check both alleles and coordinates. Singleton targets and zero-variance target columns are supported. Optional control$packed_memory_limit_bytes tightens packed storage preflight; the total native estimate also includes effects, factors and retained traces.
MegaLMM takes Y and one labelled sample relationship K. MegaBayesC takes X/Y and learns marker-to-factor effects, direct effects and sparse loadings. Factor controls include burnin, retained draws, thin, distinct uint32 seeds and memory limits. Results retain separate chains, invariant traces, final states and explicit update/solve accounting. Direct, marker-factor and loading PIPs remain distinct activity summaries. Raw loading means have sign and ordering ambiguity. MegaBayesC G is realized training-design genetic covariance. Genotype-only predictions differ from training phenotype fits conditioned on observed outcomes. New-kernel MegaLMM prediction is unavailable.
gbayes::gbayes_yaml("model.yml", output="new-fit.rds") uses the same dispatcher. Its gbayes.model/v1 schema has method, data, prior and control mappings. Matrix declarations such as X: {file: dosage.csv} refer to labelled numeric CSVs relative to the YAML file; the first column contains row IDs. Dictionary matrices use the same declarations. Inline matrices need numeric values rows and explicit rows/columns labels. Unknown fields, duplicate keys, tags, anchors and aliases are rejected; expressions are never evaluated. The optional yaml package is required. Existing output files are preserved, and fits include input hashes. The standalone mixed-model gsuite.model/v1-draft schema remains a separate solve/REML interface. Packed YAML data uses bed: {bedfiles: [chr1.bed, chr2.bed]} or Glist: {file: panel.rds}, plus labelled Y and the same prior/control fields. PLINK paths resolve relative to the YAML document; a saved Glist retains its physical paths. The runner records input hashes for the referenced resources.
See installed ?gbayes_multitrait, ?gbayes_yaml and the development package README for all controls. These adapters retain the bounded native scope, memory limits and scientific qualification of each inference route. They do not establish packed streaming, arbitrary fixed covariates, multiple kernels, genome-wide performance or broad calibration. Existing published methods and source archives are unchanged.
stat + Glist selects a summary-statistics likelihood. data + Glist selects an individual-level BED likelihood. A named list of checked summary frames or several named phenotype columns selects the multivariate route. Unsupported method/data combinations fail explicitly.
Fixed-variance single-effect summaries
gbayes::gbayes_single_effect(stat) fits a deterministic single-effect model from an ordinary data frame with unique rsids and either b/seb or score/information. It accepts fixed positive residual_variance and effect_variance, optional nonnegative marker_weights, and output labels trait and response_units. No Glist or prepared LD resource is required by this focused interface.
The per-marker result contains posterior assignment probabilities and moments. The model assumes exactly one active marker; assignment probabilities sum to one even when the evidence is weak. They are not unconditional association probabilities. This interface does not expose native single-effect variance learning or the wider BayesC/BayesR control set. For regional multi-effect fitting and posterior interpretation, use the mapping guide.
Prepare genotypes and summaries
Single-trait summary BayesC/BayesR also accepts familiar iteration and prior arguments:
fit <- gbayes::gbayes(Glist=Glist, stat=stat, method="bayesC",algorithm="mcmc", nit=100, nburn=0, seed=10)head(fit$stat) # bm: native posterior mean; dm: PIPhead(fit$post) # ve, vg, vb, pi, pip on the fitted likelihood scalehead(fit$conv) # native R-hat, ESS, MCSE and diagnostic statuses
Familiar calls default to one chain, 100 sweeps, zero burn-in, h2=.5, BayesC active probability .001, and learned slab/residual variances and mixture weights. nit/nburn/nthin/nrun/seed, pi/gamma/vb/ve, and updateB/updateE/updatePi adapt to native settings. Explicit conflicting aliases and nested settings are rejected; existing advanced calls retain their defaults. Familiar adaptation is limited to single-trait summaries.
Summary bm remains in standardized native genotype/phenotype units. The standalone reference-LD residual policy defaults to adjustment .9; it differs from qgg’s marker-specific adjustment. No independent genetic-variance draw is recreated. post$vg instead averages the joint-effect quadratic b' C b / n from retained draws, reusing the fitted residual. It is unavailable with variable sample sizes or a distinct explicit posterior reference. pi is total non-null mixture probability and pip is summed marker PIP (expected active count); pi0, pi1, … retain component weights. conv exposes rhat_*, ess_*, mcse_* and status_* columns, rather than qgg Geweke z scores. Original native posterior and diagnostic fields remain available. Single-chain output does not establish convergence or posterior equivalence. Use gmap::getCredibleSets(Glist, fit, sets) to interpret saved marginal PIPs with full BED LD without refitting.
Scalar summary BayesC/BayesR support optional LD swaps on sparse-LD and block-eigen routes, with the same controls as regional gmap():
Native Metropolis-Hastings proposals relocate an active effect to an inactive LD neighbour. probability selects sweeps for up to moves proposals; minimum_r2 and maximum_friends bound candidate neighbours. Neighbours use the fitted cross-products, including retained eigen truncation. fit$ld_swap reports pooled attempted/accepted counts and the acceptance rate; fit$chains retains per-chain counts. Counts include burn-in and no attempts gives an NA rate. They measure proposal activity, not convergence. Individual BED fits do not support these swaps. For sparse LD, neighbour preparation scans the existing stored correlations once and shares the list across chains. It does not recompute LD from genotypes or rebuild the list at every sweep.
Probability defaults to zero; zero moves also disables swaps and neighbour preparation. Finding neighbours adds preparation cost, especially with eigen operators. Existing manuscript timings used swaps disabled and remain unchanged; improved mixing or elapsed time has not been established by those timings.
BayesC and BayesR also accept algorithm="mcmc-eigen". Declare exhaustive contiguous LD blocks using gbase::define_ld_blocks(Glist, blocks); block edges must have no retained cross-block LD. The verified decomposition is prepared once per block and reused by every chain. This route uses the retained block-diagonal summary likelihood, defaults to positive eigenvalue mass .995, and learns a global residual variance in the retained response/rank space:
Use updateE=FALSE for fixed residual variance. Reference-LD adjustment and caller-supplied full-space normalization cannot be combined with this route. SBayesRC remains a separate annotated model with block-specific residual scales. The eigen option is not a promise of lower elapsed time: preparation and retained rank affect the cost. The existing manuscript timings describe the earlier dense/sparse MCMC version and have not been replaced by these interface changes.
gbase::gprep() owns the qgg-style Glist contract. Sparse LD is added to the same object rather than creating another public descriptor.
checkStat() returns an ordinary data frame with qgg-style names. It performs marker, coordinate and allele alignment but does not introduce a summary class, infer sample sizes or manufacture study frequencies. For the Gaussian summary likelihood, gbayes() requires finite b, seb and positive n; the package performs the documented standardized-effect conversion internally.
Both routes support fixed or learned effect variance and mixture weights, explicit residual policies, compact posterior summaries, annotations and exact serialized continuation. Individual fits use native BED coding and return portable allele-labelled fit$weights.
Scheduled scalar BED fits and variance decomposition
With gbayes 0.1.2 or later, scalar individual BayesC and BayesR accept control$marker_schedule=list(enabled=TRUE). Defaults are full_sweep_every=10, base_interval=50, maximum_interval=200, candidate_threshold=.001, candidate_lifetime=20, and burnin_only=FALSE. A zero full-sweep interval requests full sweeps. Active and recent candidate markers are revisited; low-probability null markers can be skipped between full sweeps. Scheduling is an explicit approximation to ordinary full-sweep sampling. It is opt-in, scalar-BED-only in R, and its queue/counters are serialized for continuation.
For a posterior-analysis example, prefer scheduling only during burn-in:
These counts are starting settings, not a convergence guarantee. With burnin_only=TRUE, every sampling sweep is full, including continuation batches with zero burn-in. With scheduling during sampling, learned global mixture weights update on periodic full sweeps and, in corrected scalar native builds, whenever the scheduled visit includes every marker. Visits that skip markers hold weights between full sweeps; an interval of ten can therefore give ten times fewer weight updates. Earlier native builds also held weights on nonperiodic visits that included every marker, needlessly slowing learning in the all-hot case. A low candidate threshold can keep all markers hot, providing no marker-visit saving. The all-hot correction changes scheduled draw sequences; continue a study with a consistent native build.
Check posterior quantities separately: similar held-out accuracy and highly correlated posterior-mean predictions can coexist with poor variance or mixture-weight mixing. Inspect parameter-level R-hat, ESS, Monte Carlo error and chain traces; a single worst-parameter statistic does not describe every output. Starting weights or inclusion_probability are distinct from the Dirichlet/Beta weight_prior used when learning is enabled. Continuing a saved fit keeps its model and transition settings; changing a prior or scheduler requires a fresh fit. An extra continuation batch can be discarded as further warm-up before summarizing a subsequent batch. Full sweeps establish the baseline before studying approximate scheduling during sampling.
fit$individual_bed$variance exposes native final and post-burnin means:
The LD term can be negative. Empirical diagonal variances need not be one under the native allele-frequency/HWE coding. These quantities differ from the slab variance parameter Vb; BayesR component variances are its multiplier-scaled values. Residual variance Ve is a separate model parameter. Compute h2 = Vg/(Vg+Ve) at each posterior draw when reporting model-scale heritability. The variance of posterior mean predictions differs from mean posterior Vg.
Each fit$chains[[k]]$individual_bed contains vb_trace, ve_trace, vg_trace, vle_trace, vld_trace, weight_trace, and log-CPO. BED traces include burn-in and every sweep; variance means average all post-burnin sweeps independently of effect thinning. Top-level traces average chains at corresponding sweeps; use per-chain traces for posterior uncertainty and diagnostics. Top-level final_* values average endpoints, not posterior draws. Per-chain scheduling counters are scheduled_marker_updates and scheduled_full_sweeps. Log-CPO uses retained training draws and is distinct from held-out prediction accuracy.
The gact individual-level example shows sparse-trait BayesC/BayesR with training-only preparation and held-out scoring. Its advanced study preserves the original short-run sparse/polygenic comparison and records quantity-specific prediction, variance and mixture diagnostics.
Annotation-informed block-eigen regression
Use sbayes(method = "bayesRC", algorithm = "mcmc", representation = "block_eigen") for a single checked summary trait. Prepare sparse LD and verify the block partition first. This example takes a prepared Glist, its aligned stat table, and a block_table with the first and last marker of each block.
For an annotated fit, use a numeric design with marker IDs as row names and annotation names as column names. Pass it in exact fitted-marker order. The following call shows the legacy gbayes() spelling and controls.
The block residual update is defined on retained response coordinates: each block uses the squared retained response norm and retained rank. This is an explicit reduced-space likelihood and is not an assertion of identical normalization to GCTB or another SBayesRC implementation. Set retained_positive_mass = 1 to retain every positive eigenvalue. On a full-rank block-diagonal reference with fixed block residuals, this route reduces to the ordinary bayesr sufficient-statistic fit.
fit$diagnostics$block_eigen records block loads, eigensystem decompositions, retained ranks, discarded positive mass and peak dense-block memory. The factors remain native working state; the returned fit is serializable and continuation restores sampler state without serializing dense eigenvectors.
Additional summary engines
The same dispatcher provides focused single-trait summary methods:
For summaries, stat may be a named trait list with one shared Glist sparse-LD reference, or a named study list paired with a named list of study-specific Glist references. Study identity remains distinct from trait identity. Local LD operators are preserved; no synthetic union LD matrix is created. Independent and shared-LD sampling assumptions are declared through sampling.
Annotations and continuation
BayesC supports inclusion and variance annotations. BayesR supports component and variance annotations. BayesS scaling uses the same checked variance-model boundary. Multivariate fits additionally support pattern annotations.
Pass a previous fit, or its $continuation member, back through continuation. The model-defining inputs, marker order, prior, annotations and transition controls must remain identical. Continuation restores native chain states and performs zero additional burn-in.
Posterior genetic quantities
An explicitly aligned sparse-LD Glist can define the reference population for posterior genetic covariance and correlation. Heritability additionally requires an explicit phenotype variance; no denominator is inferred.
fit$quantities separates genetic covariance/correlation, heritability, reporting partitions, predictions and per-chain quantities. Partition groups are reporting objects and are independent of covariance-group priors.
Predict selected individuals with uncertainty
Posterior score uncertainty uses an existing target Glist. Its active markers may be a strict subset of fitted markers and may span any number of BED components. Components and markers retain Glist order; requested individuals retain the supplied ID order.
The package validates exact fitted-marker availability, coordinates and counted alleles. Component projections use the public gscore::summary interface and are summed into one score. Coverage records fitted, used and omitted markers and the number of active BED components. Reported score covariance is posterior effect uncertainty, not phenotype predictive variance.
Scalar individual-level BED fits also include genetic_variance (VG), vle, vld and h2 directly in fit$posterior. These rows use the original per-chain draws from every post-burn-in sweep, independently of effect thinning. They report posterior mean, SD, credible intervals, R-hat, ESS and Monte Carlo error using the native summary routines. h2 is summarized from each draw’s VG / (VG + VE). Existing effect_variance (VB) and residual_variance (VE) rows retain their effect-thinned parameter draws. Continuation summaries cover the new batch.
Apply portable posterior weights
When genotype coding is identified, fit$weights is directly consumable by gscore(). This includes block-eigen SBayesRC fits; scoring uses the portable posterior mean weights and does not need the fitted eigensystems:
prediction <- gscore::gscore(fit$weights, target)
For pathway or other marker-set scores, pass a uniquely named list of marker IDs. The target Glist resolves their BED locations and the native scorer handles overlapping or cross-file sets in one pass:
Weight learning remains with gbayes; score application remains with gscore. Raw association effects are not automatically Bayesian weights, and conventional clumping and thresholding remains gscore::clump_threshold().
Regional interpretation
gmap::gmap_bed() can consume a saved individual-BED gbayes_fit together with sparse LD prepared from the same Glist samples and physical marker selection:
mapped <- gmap::gmap_bed(fit, Glist, regions)
This interprets global marginal PIPs by region without refitting. Marginal-PIP groups are not component credible sets.
gmap_bed() is specific to individual-BED fits because it verifies the fitted sample selection, BED files and in-sample LD identity. A summary SBayesRC fit remains a whole-reference gbayes_fit; regional BayesC/BayesR or multi-effect models are fitted through gmap() with their own explicit regional likelihood.
Qualification status
The package passed its complete source check with no errors or warnings, focused deterministic tests, an exact Windows DLL-closure and SHA-256 audit, and clean binary loading. The two source-check NOTEs concern installed DLL size and the conservative compiled-code scan of the bundled native DLL closure.
Simple individual-level defaults
Scalar individual BED fits can omit prior: gbayes initializes half the observed phenotype variance as residual variance and half as nominal genetic variance. BayesC starts with inclusion probability .001; BayesR starts with weights (.95,.02,.02,.01) and multipliers (0,.01,.1,1). The marker-scale variance is VG/(m times mixture variance mass), using standardized genotype coding. This is a starting heuristic, not an empirical estimate of heritability or causal count. Variance learning uses df=4 and scale=initial variance/2; mixture learning uses unit Beta/Dirichlet concentrations. These learning priors are separate from initial mixture probabilities. Automatic runs use 1000 burn-in and 2000 sampling sweeps, thinning 5, seeds 1 and 2, one thread, retained diagnostics and full sweeps. Control overrides remain available. Explicit nonempty priors retain the existing opt-in learning controls and require proper learning priors when enabled. Scalar BED responses are centred internally without rescaling; the default likelihood dimension is n-1. The phenotype mean is recorded in provenance. An omitted prior during continuation reuses the saved prior and transition controls. Inspect $prior, $control and $posterior; default sweep counts and the R-hat/ESS screening message do not guarantee convergence.
Exact cross-product BayesC and BayesR
Development only — gbayes 0.1.6. This entry point is not included in the public gbayes 0.1.1 download; it requires a compatible development installation.
For general feature regression, use the existing native sampler without a Glist:
X <-scale(cbind(feature1 =sin(1:30), feature2 =cos(1:30)))y <-as.vector(scale(sin((1:30)/3)))fit <- gbayes::blr(crossprod(X), drop(crossprod(X, y)),yy =sum(y^2), n =length(y),method ="bayesR", nit =5000, nburn =1000, seed =10)coef(fit)# Multiple responses, with labelled residual and latent marker covariances:joint <- gbayes::mblr(XX, Xy_matrix, yy=YY, n=n,vb=Vb, ve=Ve, pi=pattern_weights)gbayes::extract(joint, "effects", chain=1)
The caller prepares consistently centered and scaled XX, Xy and yy, as in the example above; blr() does not transform supplied statistics. The caller supplies matching unique feature labels for XX and Xy; joint Xy also has ordered trait labels, and yy is labelled in that trait order. Scaled eigensystem and Schur-complement checks validate the full PSD/rank contract, including singular XX and consistent Xy. Coefficients and variances retain supplied feature units.
The direct controls and defaults match the other new fitters: nit=1000, nburn=500, nthin=1, nchains=2, ncores=1, seed=1. Retain completed post-burn multiples of nthin and finish all transitions. Scalar pi is the BayesC active probability or complete BayesR mixture vector. With d the declared likelihood dimension, defaults use vb=h2yy/(trace(XX)mixture mass) and ve=(1-h2)*yy/d. This respects arbitrary feature scaling. Joint vb/ve and activity-pattern pi are explicit, with learning off by default. Proper priors enable optional covariance/weight learning; exact same-scale yy is required for residual learning. There is no reference-LD adjustment. C/R reference-LD input uses sbayes/msbayes.
The default declares already centered inputs with likelihood dimension n-1. Other projections require control$likelihoodDimension and coding=list(preprocessing=“residualized”). Coding can additionally store feature-named centers/scales and trait-named intercepts used to prepare the statistics. Dense feature prediction reuses those transformations; phenotype prediction requires intercepts and centered preprocessing. Without saved coding, prediction is unavailable. Neither training means nor nuisance coefficients are inferred from cross-products. Common fits retain labelled axes, per-chain access and actual checkpoint diagnostics. Full coefficient draws and annotation are unavailable here. This replaces the previous scalar blr signature without compatibility aliases.
Exact C/R cross-product fits support native checkpoint continuation:
saveRDS(fit, "cross-product-fit.rds")more <- gbayes::blr(crossprod(X), drop(crossprod(X, y)), n=length(y),nit=500, continuation=readRDS("cross-product-fit.rds"))# Use mblr for a saved joint checkpoint. Omitted yy/coding reuse saved values.gbayes::diagnostics(more)$execution$continuation
Supply XX, Xy and n again; ordered labels, values, scatter, supplied units, coding and likelihood dimension must remain identical. Omitted method, priors, learning flags, thinning, chains and seeds inherit the original model. Omitted yy/coding inherit the checked saved values; explicit NULL is a new value and must match. Final learned parameters remain private checkpoint state.
Nit adds transitions without repeated burn-in. Global thinning survives remainder and repeated splits, including a short segment containing the next retained draw. At most one discarded advance precedes the retained native call. Resumed fits summarize only newly retained draws and remain resumable. Worker count, diagnostic capture, probability and memory budgets may change; model and chain identities stay fixed. Native states/RNG and parameter traces replay uninterrupted runs.
Checked statistics/coding and the bundled gbayes/gbase runtime are fingerprinted before/after fitting; the declared gbase dependency is initialized even for pure cross-products. SaveRDS/readRDS needs no live handles. Current qualification is bundled Windows builds; other layouts report restartState unavailable. Existing feature prediction still requires saved transforms, and phenotype prediction requires centered preprocessing/intercepts. Full effect draws and CM continuation remain unavailable. See the cross-product continuation contract.
Cross-product C/R can also capture posterior quantities:
Use mblr with trait-named denominators for joint models. Reference=“training” selects XX/d with the declared likelihood dimension d; the reported draw-wise component covariance is B’ XX B / d. Centered inputs default to d=n-1. Residualized inputs give a projection-normalized model quantity, not raw population covariance. Feature units remain supplied units; no LD conversion, alleles, new centering or intercept terms are inferred. The fitting operator is shared, with a reporting identity tied to its ordered features, values and divisor.
The common genetic quantity names denote this linear-predictor component. Generic features alone do not justify genetic interpretation. The common heritability output is an explicit-denominator variance ratio, requiring compatible phenotypeVariance; yy is not used to infer that denominator. Genetic interpretation requires an appropriate genetic feature model and units.
Partition labels are disjoint and named in fitted feature order. Partition-only requests report activity; with reference=“training”, full group/trait covariance retains cross-group terms and is not an additive heritability allocation. Correlation moments retain positive-variance conditioning counts. Per-chain moments and pooled native quantity intervals/diagnostics remain separate from parameter summaries. Traces follow retainDiagnostics; moments remain when traces are disabled. Capture is per call, including continuation, and covers only newly retained draws. States/RNG and parameter traces are unchanged. Managed capture budgets and identity checks apply. Full effect draws, per-chain quantity intervals and posterior score capture remain unavailable. Ordinary predict() retains its saved-coding contract. See the cross-product capture contract.
Joint summary IBSS
Development gbayes 0.1.9 exposes native mvSuSiE and MultiSuSiE through msbayes() with algorithm="ibss". These engines do not need the gmap R package. Select one bounded region in Glist or control$markers; full LD is reused or prepared through gbase. A call fits one supplied marker domain; genome-wide region orchestration and set interpretation remain separate.
mvSuSiE uses one shared Glist, complete common markers and N, and one study per trait. The optional study-named trait mapping is one-to-one. ve is fixed SPD sampling covariance; vb is a nonnegative component scale. The labelled PSD dictionary in prior$covariance may contain singular/private/shared templates. pi supplies template weights. updateB and updatePi default TRUE. Effects use the standardized b/sqrt(n*seb2+b2) convention. Trait PIPs, any-trait assignments and same-marker pair activity retain distinct meanings.
MultiSuSiE treats every study as its own effect axis and requires independent samples, including when studies reuse an LD reference. Named reference catalogs can be reordered; sampling$reference maps study names to them. Observed marker subsets, ordering and N may differ. Effect covariance vb is PSD and its correlation shapes remain fixed. Effect and residual learning default off.
Its checked OLS inputs retain supplied score/information or reconstruct information=(n-1)vy/((n-2)seb2+b2), score=b*information. Reconstruction assumes intercept-only OLS/conventional SE for continuous outcomes. Supply outcome variance via sampling$phenotype_variance or prepared metadata; inferred beta/SE/N initialization is recorded separately and is not sufficient for residual learning. Set sampling$in_sample_ld=TRUE and provide genuine variance for that option. prior$markerWeights is fixed for both engines.
Use nit as the maximum sweeps (when omitted: 500 for mvSuSiE, 200 for MultiSuSiE). Explicit MCMC controls, continuation and posterior capture are rejected. IBSS results retain no sampled chains. MultiSuSiE exposes union anyPip and leaves trait pips unavailable. Objective decreases and iteration exhaustion remain visible; returned residual proposals may differ from the scale actually used for posterior moments. Neither a converged coordinate fit nor a union PIP establishes sharing calibration. See help("summaryIBSS", package="gbayes") for all controls and limits.
Fixed BayesC active-slab means
Keep method="bayesC" and supply marker-named prior$slabMean. The spike is zero; only the active normal slab moves. Supply explicit scalar pi, vb and ve, all fixed. Individual means use original phenotype per saved HWE dosage scale; summary means use standardized phenotype/genotype and must already match the reference counted allele.
VB uses a whole-panel product approximation with no MCMC controls. Its fixed point does not establish calibration under LD. Neither route enables joint fitting, marker-prior learning, capture, continuation or gmap conversion. Development gbayes 0.1.16 supports optional exact MCMC residual learning below. Ordinary BayesC MCMC without slabMean or marker probability/variance fields retains its defaults. See the full contract and tools/examples/gbayes/informed-bayesc.R for a runnable saved-input example.
Marker-specific BayesC probabilities and slab variances
Use named prior$markerInclusionProbability instead of scalar pi and/or named prior$markerSlabVariance instead of scalar vb. Each vector covers every fitted marker exactly once. Slab variances are positive absolute variances on the fitted effect scale; probabilities are active probabilities strictly inside (0,1). Scalar and marker forms of the same parameter are mutually exclusive. Keep ve explicit and fixed; optional slabMean defaults to zero.
Code
fit <-sbayes(stat, LD, method="bayesC", algorithm="vbayes", ve=1,prior=list(markerInclusionProbability=marker_pi,markerSlabVariance=marker_variance,slabMean=summary_scale_means))# The same prior fields work in individual bayes and with algorithm="mcmc".
The existing units, whole-panel VB approximation, fixed-prior restrictions and save/reload/scoring handoff apply. Fixed marker priors remain in input$prior; no artificial global mixture-weight or variance-scale estimate is reported.
Scalar BayesC and BayesR annotations
Use gbayes 0.1.16 for these calls. Designs and supplied frequencies use exact fitted-marker order.
Baseline pi learning and BayesC inclusion-slope learning are distinct. BayesR component learning replaces its global weight update. The MAF coefficient is an exponent on fitted-scale variance; no raw-dosage BayesS conversion is inferred. Marker prior probabilities and posterior PIPs remain separate quantities. Capture, continuation, joint C/R annotations and saved mapping remain gated. See the source contract.
Exact residual learning
Set updateE = TRUE in informed scalar BayesC MCMC or independent-provider joint BayesC/BayesR MCMC to learn exact residual variances.
For informed bayes, centered outcomes supply y’y and dimension n-1. For informed sbayes, declare control=list(normalization=list(response_ss=yy, likelihood_dimension=d,in_sample_ld=TRUE)). Keep marker means, probabilities and slab variances fixed. ve is the initial residual variance. VB remains fixed.
For msbayes C/R, declare sampling=list(dependence=“independent”, residual_variance=initial, response_sum_squares=yy, likelihood_dimension=d, in_sample_ld=TRUE), with all three vectors named in provider order. Use existing vb and pattern pi, updateE=TRUE, optional nue and prior$veScale. nue defaults to 4; veScale is a scaled-inverse-chi-square scale, defaulting to a prior mean at the initial variance. Provider residual means are in extract(fit,“parameters”) under provider_residual_variance; retained parameters and terminal scales retain separate provider labels even when several studies map to one trait.
Exact summary learning requires compatible in-sample y’y, scores, full LD and common N within each provider, equal to its LD sample count. External/reference LD, overlap, variable marker N and truncated LD are not admitted. Data provenance and independence remain caller assertions. These extensions do not expose capture, annotations, continuation or saved gmap conversion. See the design contract, installed ?exact_residual_learning, and tools/examples/gbayes/exact-residual.R.
Population shrinkage
Use msbayes with continuous_shrinkage and mcmc for PRS-CSx, JointPRS reference and Panther reference fits. Keep population names in stat and use one common phenotype label in trait:
Code
fit <-msbayes(list(EUR=eur, EAS=eas), list(EUR=ld_eur, EAS=ld_eas),trait="height", sampling=list(dependence="independent"),method="continuous_shrinkage", algorithm="mcmc",prior=list(hierarchy="prs_csx",globalScale=.01),nit=1000,nburn=500,nthin=5,nchains=2,seed=42)
All references must already contain the same ordered marker intersection and verified LD blocks. Independent discovery samples, population-specific common N and explicit catalog mappings are required. For JointPRS use hierarchy= “jointprs_reference” and named correlationCaps. For Panther use hierarchy= “panther_reference” plus labelled sharingGroups, pantherRoute and outputPopulation. The supplied categories are not learned sharing probabilities; target mode ignores them. All native estimated population effects are retained.
updateB learns the global scale only; local and normalized residual scales always update. These reference residual transitions are separate from exact in-sample residual learning. Extract effects/empirical effectVariance, parameters, localScales, JointPRS populationCorrelation or Panther groupScales. No spike PIPs are available. Serial chains retain selected diagnostics and final effects, without continuation or gmap interpretation. JointPRS remains experimental; selected mean agreement does not establish mixing. See the full contract, ?population_shrinkage and the saved-input example in tools/examples/gbayes/population-shrinkage.R.
Scalar summary IBSS
Use sbayes with multi_effect and ibss for one bounded region. Prepare OLS summaries with the public gmap helper, retaining original phenotype/design effect units:
Code
prepared <- gmap::gmap_stat(stat, LD, phenotype_variance=vy)fit <-sbayes(prepared, LD, trait="height", method="multi_effect", algorithm="ibss",vb=.02,ve=1,updateB=TRUE,nit=500,control=list(effects=5))# Alternatively pass ordinary stat plus control$phenotypeVariance=vy.
The full regional marker/allele/coordinate order must match complete LD; the initial route requires positive full-rank LD and caps the domain at 2048 markers by default. It does not perform automatic filtering, score projection or LD repair. Component-variance learning is on by default; residual learning is off. Exact residual learning requires explicit in-sample response scatter/dimension, matching sample count and normalization. It is variational EB, not MCMC.
Extract effects, effectVariance, pips, componentAssignments and componentScales; inspect diagnostics(fit)$ibss for objective/residual traces and inactive/inner convergence flags. Inactive components are not signals, and conditional components do not establish independent causal markers. There are no chains or full effect draws. Save/reload works through RDS; prediction, capture, continuation and saved scalar gmap conversion are not exposed. Direct gmap is the reference workflow. See the contract, ?scalar_summary_ibss and tools/examples/gbayes/scalar-summary-ibss.R.
Weighted elastic net
All four genomic fitters accept named marker penalty multipliers with method = "elastic_net" and algorithm = "coordinate_descent".
Code
fit <-bayes(training,Glist,trait="height",method="elastic_net",algorithm="coordinate_descent",nit=10000,control=list(lambda=.1,alpha=.6,l1Weights=marker_l1,l2Weights=marker_l2))joint <-mbayes(training,Glist,trait=c("height","weight"),method="elastic_net",algorithm="coordinate_descent",nit=10000,control=list(lambda=.1,alpha=.6,covariance=K,l1Weights=marker_l1,l2Weights=marker_l2))# K is a fixed SPD penalty covariance labelled c("height","weight").
Each supplied vector must be finite, nonnegative and named for the entire fitted marker panel. Omitted weights default to ones and are never normalized. Weights apply to saved training empirical-SD coefficients; scalar covariance scales the L1/L2 terms as before. Zero removes a penalty, not a marker. Alpha=0 remains gated; alpha=1 ignores L2 weights. Use diagnostics(fit)$numerical for native and normalized KKT, objective and qualified lambdaMax. An L1-unpenalized marker with nonzero score prevents a finite all-zero threshold. Prediction reuses training coding; weights and exact normalized coefficients survive RDS save/reload. Joint weights are marker vectors shared across traits. L1 uses marginal SDs of K; each L2 weight multiplies the full marker precision block, so zero removes that marker’s cross-trait penalty. K does not weight residuals. Automatic selection/weight estimation remains separate. The new joint native symbol requires rebuilding native gbayes before the R package at the batch checkpoint. See the contract, ?weighted_elastic_net and tools/examples/gbayes/weighted-elastic-net.R.
The scalar summary route uses standardized marginal effects and reference LD:
Supply the usual b/SE/n table covering every prepared sparse-LD marker and one common GWAS N. This fits a normalized reference-LD quadratic with standardized summary effects, not empirical-SD individual effects. The supplied LD must be PSD for convexity; no PSD certification, repair or projection is performed. Inspect the saved LD/convexity limitations and normalized summary KKT/objective. No training coding/intercept or direct prediction is inferred. Bayesian scale, learning, MCMC, capture and continuation arguments are rejected. The runnable example accepts interface=“sbayes” with stat instead of data in inputs.rds.
Joint summary fitting adds a distinct sampling declaration to the penalty K:
K is the fixed penalty covariance; Omega is the justified sampling-error covariance. Both are SPD and labelled in trait order. For independent providers, declare dependence=“independent” and residual_variance named in provider order. Study-named Glists also use the normal named trait map. This source route admits one full ordered panel per trait (2–32 traits), with common N within each provider; independent providers can have different LD/N. Losses are normalized per provider before adding the same shared-marker penalty. PSD LD is assumed, not certified/repaired. Inspect maximumKktSummary and the normalized objective; there is no further N division, training coding or posterior uncertainty. The example accepts interface=“msbayes” with stat, sampling and penalty K.
Runnable Gaussian and weighted elastic-net examples
Run both fits with a small centered feature matrix. The row names match the phenotype IDs. The named L1 multipliers apply a larger penalty to v.
Code
ids <-paste0("i", 1:4)X <-cbind(u =c(-1, -1, 1, 1), v =c(-1, 1, -1, 1))rownames(X) <- idstraining <-data.frame(id = ids, height =c(-1, 1, -2, 2))fit <- gbayes::bayes( training, X = X, trait ="height",method ="marker_gaussian", algorithm ="pcg", ve =1,prior =list(markerVariance =c(u =0.2, v =0.2)))weighted <- gbayes::bayes( training, X = X, trait ="height",method ="elastic_net", algorithm ="coordinate_descent",control =list(lambda =0.1, alpha =0.6, l1Weights =c(u =1, v =2)))coef(fit) # u = 0, v = 0.666667coef(weighted) # u = 0, v = 1.326923predict(fit, X)
X is a bounded finite matrix with sample row IDs and feature column IDs, already centered in the desired fitting units. The response is centered without rescaling. Keep the training feature-preparation recipe and apply it to target features before predict; no feature standardization or raw-feature transform is inferred. The exact-statistics companion is blr(XX,Xy,yy,n,method=…), using the same two methods and native fitters. Its existing coding can enable generic prediction. Set prior$markerMean to supply Gaussian prior means or elastic-net penalty centers. Elastic-net weights default to one when omitted. For genomic inputs, see the four weighted elastic-net fitters. The prepared-design examples passed on the frozen 0.1.16 build. See the contract, ?prepared_design and tools/examples/gbayes/prepared-design.R.
A labelled finite matrix can replace the reader descriptor. Each reader result must retain declared sample order and requested feature order, with both axes labelled. Keep the source immutable. The adapter adds an intercept and native QR fits the supplied fixed covariates; target phenotype prediction needs matching covariates. Features retain their supplied units. Priors remain fixed and each candidate is a separate scalar bayesfit; candidates are not traits or selections.
Inspect each fit’s negative-ELBO history and convergence status. Maximum sweeps remains provisional; variational variances are approximate, and no PIPs are exposed. Shared batch work diagnostics must not be summed across their copies. The saved fit omits its reader. Prediction uses new feature matrices. See the contract, ?streamed_prediction and tools/examples/gbayes/streamed-prediction.R.
Scalar Gaussian co-data
This runnable example learns a diagonal Gaussian prior from two overlapping groups in one co-data set. It uses the supplied feature coding and a fixed residual variance and group penalty.
X can also be a labelled dgCMatrix; sparse input is not converted to a dense feature matrix. Coding defaults to zero centers and unit scales. Supply the intended transforms explicitly: this route fits no intercept, leaves outcomes unchanged and does not infer preprocessing. Effects use transformed feature units. Overlapping groups are averaged per feature. globalMode="known_noise_ml" and explicit varianceBounds optionally learn the initial global variance; ve and hyperLambda stay fixed. Both moment RHS and hyper-ridge profiles are explicit options. Use only training outcomes and training-derived coding.
The reportable means are Gaussian conditional means at a learned plug-in prior. Sampling variance in diagnostics is not posterior effect uncertainty; PIPs and posterior variances are unavailable. Prediction uses all fitted features in fitted order, with saved coding and no refitting. No implicit phenotype offset is added. This bounded scalar route has no joint/summary adapter. Automatic tuning and multiple annotation sets are supported below. General selection stays in gscore. See the design contract, ?gbayes::co_data_gaussian and the runnable source example tools/examples/gbayes/co-data-gaussian.R.
Combining multiple co-data sets
Use named sets instead of groups/id. Every set covers all fitted features; groups can overlap within a set. For the same three-feature example:
An unnamed scalar hyperLambda shares one fixed penalty; a named vector aligns penalties to sets. The native engine learns group profiles and weights across sets, then fits their combined diagonal Gaussian prior. Normalizing groups and normalizing set weights are independent choices; both enabled give mean prior variance equal to the global variance. Set normalization is post-fit scaling. The same frozen coding and optional shared known-noise ML apply. A one-group set uses a fixed unit profile. Sets are annotations on one outcome, not new traits or model-averaged candidate fits.
Set weights are not posterior activity or sharing probabilities. Inspect the actual route/rank/KKT diagnostics: similar profiles may not identify individual weights. The undefined zero-source profile and solver failures are explicit errors, with no accepted partial fit. Posterior effect variances and PIPs remain unavailable. See ?gbayes::co_data_gaussian, the design and runnable source example tools/examples/gbayes/co-data-gaussian-multi.R.
Tuning from saved feature-group splits
Use hyperLambda=0 with saved partitions of each group’s feature IDs:
For multiple sets, use hyperLambda=c(A=0, B=3) and splits=list(A=splits) with the earlier named sets. A tunes; B stays fixed. Each split half names every group, with disjoint members covering the full group; character(0) is allowed for an empty half. One-group sets retain their native unit profile and skip tuning. No random splits are inferred. control$tuning adjusts native path and hyper-search controls; maxSplits bounds the total saved pairs.
Zero requests native path-bound construction and raw-gamma held-out equation tuning, followed by the declared full-group fit. It is not a zero-penalty solve. Inspect saved paths, split equations, objective, evaluations and boundary status. Prediction and save/reload do not repeat selection. Search exhaustion and undefined numerical equations return no accepted partial fit.
These partition feature-group equations, not patients: they do not create a validation cohort. Use training outcomes/coding only. Patient CV/refit remains separate in gscore; fixed noise and absent posterior variances/PIPs are unchanged. See the contract, package help and tools/examples/gbayes/co-data-tuning.R.
Learning residual variance
The same scalar co-data family can learn the initial residual and global effect variances jointly, then hold them fixed during annotation fitting:
Omit ve, globalVariance and varianceBounds. The bounds constrain the residual/ global ratio, using supplied feature coding. For multiple sets, replace groups with the existing named sets contract; every set receives the same learned pair. Positive penalties and saved-split automatic penalties both compose with this mode. Native fitting learns noise once before groups; it does not re-estimate noise after group tuning or set weighting. No intercept or centering is inferred.
Inspect objective, boundary and identification limits. Proportional-to-identity design Gram matrices and zero outcomes are rejected, and near-flat profiles are not identification certificates. Prediction/save/reload do not retune. No PIPs or posterior parameter/effect uncertainty is added. See the contract, help and tools/examples/gbayes/co-data-noise.R.
Supplied-fold initialization selected in gscore
Use gscore for the workflow and gbayes for numerical fitting:
Multiple sets use the same coData$sets contract; saved feature-group split tuning can also be supplied separately. For noise profiling conditional on the selected ratio, set estimateNoise=TRUE and omit ve. Do not supply coData initializer modes/variances/bounds; gscore selects that pair. Final fitControl reuses CV coding.
This workflow tunes the ordinary ridge initializer. Full-model co-data CV remains planned. gscore independently selects minimum row-weighted MSE with a largest-penalty exact-tie rule and verifies the native provisional profile before refitting. Freeze preprocessing externally and keep patient clusters within folds. No outer test outcomes, learned fold coding or automatic folds enter. CV and refit work/ownership remain saved, including in fit provenance. The final fit is conditional on the selected pair and keeps normal prediction/uncertainty contracts. See the design, package help and tools/examples/gscore/co-data-cv.R.