https://github.com/jonasson2/varmapack
Varmapack is a C library for simulation and analysis of Gaussian VAR, VMA, VARMA, VARMAX, and continuous-time OU models. Its primary purpose is to generate simulated series from supplied model parameters, but it also provides model testcases, theoretical and sample autocovariances, covariance-to-correlation conversion, innovation-covariance recovery, spectral radii, and impulse response functions. In contrast to some other packages, the simulated series have the correct distribution from the start; they are burn-in (or spin-up) free. The package uses Randompack (https://github.com/jonasson2/randompack), [Jónasson (2026)] (https://arxiv.org/abs/2605.05099), to generate random numbers for the simulation. C, Python, R, and MATLAB interfaces are described in the respective README files in the GitHub repository.
Varmapack is based on a part of Algorithm 878 published in ACM TOMS in 2008 Jónasson (2008). That algorithm is a collection of MATLAB functions to evaluate the likelihood of a VARMA model, which also includes functions to simulate such models and provide testcase data.
The public header file varmapack.h serves as a compact reference for the C
API: all user-facing functions are declared there, with comments describing the
role of each parameter.
A fixed seed gives reproducible simulation paths for a fixed compiler, BLAS library, and Randompack build. Bitwise agreement across platforms is not guaranteed when a conditional startup covariance is rank deficient: floating point factorization can select a different numerical rank and therefore consume a different number of normal variates. The resulting paths remain draws from the same conditional distribution.
Varmapack is described in Kristján Jónasson (2026), "Burn-in-free simulation of VARMA time series", SoftwareX, 36.
For more details of the mathematics, see Kristján Jónasson (2026), "Burn-in-free simulation of VARMA time series", SoftwareX, 36.
The mathematics of new features for the Varmapack 0.2 series (0.2.xxx) is described separately in Varmapack 0.2: Mathematics of New Features (Draft). That note contains LLM-generated material and has not yet been proof-read.
The models considered are either VARMA
or VARMAX
where in both cases
A model with
There are two possibilities to start VARMA simulation with Varmapack: (a) by
drawing both shocks
For a stationary model, both (a) and (b) are possible, and the simulated series will have the correct distribution from the first generated term, so that no burn-in segment needs to be discarded.
For a nonstationary model, starting values must be supplied. For a pure VAR
model (
With VARMAX simulation, startup states must be provided:
Varmapack can compute the theoretical autocovariance function of model (1),
up to a user-specified maximum lag.
The inverse problem, recovering
Varmapack can also compute sample autocovariance matrices from observed data. The default maximum-likelihood normalization is
and the corrected normalization replaces the denominator
The spectral radius
where
An important concept in time-series theory is that of impulse response
functions. The impulse response matrix
which has the impulse response matrices as coefficients. With
for
where
The supported installation method is to build Varmapack from source. Building
the library requires Meson, Ninja, pkg-config, C and Fortran compilers, and
an optimized BLAS library. macOS provides BLAS through the Accelerate framework.
On Linux and Windows, OpenBLAS or MKL must be installed separately. Varmapack
also requires the Randompack C library; see below.
Install or load these prerequisites using the normal method for your system.
For example, an HPC cluster may supply them through environment-module systems,
using module load commands.
Install Randompack 0.1.10 or later system-wide or under ~/.local as described
in its README. Before
configuring Varmapack, verify that pkg-config can find a suitable version:
pkg-config --atleast-version=0.1.10 randompackFor source installations, specifying --libdir=lib for both Randompack and
Varmapack is recommended to ensure consistent library paths across platforms.
The Randompack README and the Varmapack commands below use this setting. With
--prefix=/usr/local, the libraries are installed under /usr/local/lib;
without an explicit libdir, Meson may choose a platform-specific multiarch
directory.
For a user-local installation, this requires the setting described in the Randompack README:
export PKG_CONFIG_PATH="$HOME/.local/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"This export sets PKG_CONFIG_PATH if it is undefined, or prepends the new
directory to it if it exists. Add the export to the appropriate shell startup
file if the user-local installation should be available in future shells. No
such setting is normally needed for a system-wide installation.
Clone Varmapack and choose either a system-wide or user-local installation before configuring the build:
git clone https://github.com/jonasson2/varmapack.git
cd varmapackFor a system-wide installation, configure, build, test, and install with:
meson setup build --buildtype=release --prefix=/usr/local --libdir=lib
ninja -C build
meson test -C build
sudo meson install -C buildFor a user-local installation that does not require sudo, use ~/.local:
meson setup build --buildtype=release --prefix="$HOME/.local" --libdir=lib
ninja -C build
meson test -C build
meson install -C buildThe PKG_CONFIG_PATH setting above also makes the user-local Varmapack
installation visible. In either case, verify the installed version and inspect
the compiler and linker flags with:
pkg-config --modversion varmapack
pkg-config --cflags --libs varmapackPrograms using Varmapack can then be compiled with:
cc -o myprog myprog.c $(pkg-config --cflags --libs varmapack)Varmapack's pkg-config file declares Randompack as a dependency, so this
command supplies the flags for both libraries; Randompack need not be added
separately.
Varmapack stores matrices in column-major order. Coefficient matrices belonging
to successive lags are contiguous blocks, and simulated series are stored as an
r by n by M array.
The code blocks through the VARMAX simulation section are successive parts of one
main function in QuickStart.c in the examples folder. For
readability, error checking is omitted; the final section of the chapter shows
how to check errors.
The program begins by simulating 10 replicates of length 200 from a
two-dimensional VAR(1) model. Passing B=0 and q=0 selects a pure VAR model;
similarly, A=0 and p=0 would select a VMA model. Once Varmapack is
installed, compile the complete QuickStart.c example using the cc
command given above.
#include <stdio.h>
#include <stdlib.h>
#include <varmapack.h>
int main(void) {
int p = 1, q = 0, r = 2, n = 200, M = 10;
double Avar[] = {0.6, 0, 0.1, 0.4}; // r by r by p
double Sigvar[] = {2, 0, 0, 1}; // r by r
double X[2*200*10]; // r by n by M
randompack_rng *rng = randompack_create(0); // select default Randompack engine
randompack_seed(123, 0, 0, rng); // optional, but gives reproducible results
varmapack_sim(Avar, 0, Sigvar, 0, 0, p, q, r, n, M, 0, 0, 1, X, 0, rng);
for (int t=0; t<5; t++) printf("%8.4f %8.4f\n", X[r*t], X[1 + r*t]);The next part selects the fixed smallARMA1 testcase. First inquire about its
dimensions, then allocate and fill its coefficient arrays. This testcase has
p=q=1 and r=2.
char name[VARMAPACK_TESTCASE_NAME_LEN] = "smallARMA1";
int index = 0;
varmapack_testcase(name, &index, 0, &p, &q, &r, 0, 0, 0, 0);
double *A = malloc((p ? p : 1)*r*r*sizeof(*A));
double *B = malloc((q ? q : 1)*r*r*sizeof(*B));
double *Sig = malloc(r*r*sizeof(*Sig));
varmapack_testcase(name, &index, 0, &p, &q, &r, A, B, Sig, 0);The testcase is simulated with a time-dependent mean and a supplied startup
path. The last mu column repeats to the end, so the mean at t=0 is (0,0) and
at every subsequent time step is (1,1). Here nX0=2, while MX0=1 broadcasts
the single startup path. Set MX0=M and supply an r by nX0 by M array to
give each replicate its own path.
double mu[] = {0, 0, 1, 1}; // r by nmu (time dependent means)
double X0[] = {0, 0, 0.1, -0.1}; // r by nX0 (common start for all replicates)
double E[2*200*10]; // r by n by M (returns shocks)
varmapack_sim(A, B, Sig, mu, 2, p, q, r, n, M, X0, 2, 1, X, E, rng);Next, QuickStart.c simulates a zero-mean realization of smallARMA1 and
computes theoretical and sample autocovariances, theoretical correlations,
ordinary and orthogonalized impulse responses, and AR and MA spectral radii.
varmapack_sim(A, B, Sig, 0, 0, p, q, r, n, M, 0, 0, 1, X, 0, rng);
enum { maxlag = 3 };
double Gamma[2*2*(maxlag+1)], Corr[2*2*(maxlag+1)];
double Psi[2*2*(maxlag+1)], Theta[2*2*(maxlag+1)], GammaHat[2*2*(maxlag+1)];
double rho = varmapack_specrad(A, r, p);
double rhoMA = varmapack_ma_specrad(B, r, q);
varmapack_acvf(A, B, Sig, p, q, r, Gamma, maxlag);
varmapack_cov2corr(Gamma, r, maxlag, Corr);
varmapack_autocov("N", "ML", r, n, X, maxlag, GammaHat);
varmapack_psi(A, B, p, q, r, maxlag, Psi);
varmapack_irf(A, B, Sig, p, q, r, maxlag, Theta);
printf("AR spectral radius: %.4f\n", rho);
printf("MA spectral radius: %.4f\n", rhoMA);
for (int k=0; k<=maxlag; k++) printf("Gamma[%d]: %.4f %.4f %.4f %.4f\n",
k, Gamma[4*k], Gamma[4*k+1], Gamma[4*k+2], Gamma[4*k+3]);
for (int k=0; k<=maxlag; k++) printf("Corr[%d]: %.4f %.4f %.4f %.4f\n",
k, Corr[4*k], Corr[4*k+1], Corr[4*k+2], Corr[4*k+3]);
for (int k=0; k<=maxlag; k++) printf("GammaHat[%d]: %.4f %.4f %.4f %.4f\n",
k, GammaHat[4*k], GammaHat[4*k+1], GammaHat[4*k+2], GammaHat[4*k+3]);
for (int k=0; k<=maxlag; k++) printf("Psi[%d]: %.4f %.4f %.4f %.4f\n",
k, Psi[4*k], Psi[4*k+1], Psi[4*k+2], Psi[4*k+3]);
for (int k=0; k<=maxlag; k++) printf("Theta[%d]: %.4f %.4f %.4f %.4f\n",
k, Theta[4*k], Theta[4*k+1], Theta[4*k+2], Theta[4*k+3]);Gamma, Corr, Psi, Theta, and GammaHat each contain maxlag + 1
contiguous r by r matrices. The sample call above analyzes the first
replicate in X; use normalization "C" instead of "ML" for division by
n - k.
varmapack_cov2corr(cov, r, maxlag, corr) converts a sequence of covariance
matrices such as Gamma or GammaHat to correlations. Both arrays have shape
r by r by maxlag + 1 in column-major order. Each entry at lag k is
divided by the product of the corresponding standard deviations obtained from
the diagonal of the lag-zero covariance matrix.
The call above preserves the covariances in Gamma and writes the correlations
to Corr. Pass the same array for both arguments to convert it in place.
Distinct arrays must not overlap. The diagonal lag-zero correlations are set
exactly to one.
The function deliberately does not clip other values to [-1,1]. In
particular, the corrected sample autocovariances produced by
varmapack_autocov with normalization "C" use lag-dependent divisors and can
therefore yield values outside that interval after conversion.
Like the other Boolean-valued analysis functions, varmapack_cov2corr returns
false and sets varmapack_last_error() when an argument is invalid, an input
entry is not finite, or a lag-zero variance is not positive.
varmapack_cov2sig(A, B, cov, p, q, r, Sig) recovers the innovation covariance
from a specified lag-zero model covariance, with the AR and MA coefficients
held fixed. cov and Sig are single column-major r by r matrices.
Only the lower triangle of cov is read; the full symmetric Sig is returned.
Pass 0 for A when p=0, or for B when q=0.
The AR model must be stationary. Both covariances must be positive semidefinite
within floating-point tolerance; singular covariances are allowed, but not
every target is compatible with the supplied coefficients. Pass the same array
for cov and Sig to convert in place; otherwise the output must not overlap
any input.
The function returns false and sets varmapack_last_error() for invalid
input, an incompatible target, or a singular or numerically unreliable inverse
problem. On failure, Sig is unchanged. The inverse Yule--Walker derivation is
in Recovering innovation covariance.
varmapack_ou_create(tau, cov, mu, r) constructs a stationary Gaussian
Ornstein--Uhlenbeck model with diagonal drift. tau contains positive
persistence times and cov is the stationary process covariance, not the
innovation covariance. Both cov and the continuous-time driving covariance
D[i,j] = cov[i,j]*(1/tau[i] + 1/tau[j]) must be positive semidefinite.
Only the lower triangle of cov is read; singular covariances are allowed.
varmapack_ou_create_drift(K, cov, mu, r) instead takes a full column-major
drift parameter matrix K, with drift -K*(X-mu). K must have eigenvalues with
strictly positive real parts, and K*cov + cov*K' must be positive semidefinite.
The autoregressive coefficient matrix over a gap of length d is the matrix
exponential exp(-K*d). With constant gaps, the sampled process is a VAR(1).
double tau[] = {1, 2}, cov[] = {1, .5, .5, 1}, t[100], X[200];
varmapack_ou_model *model = varmapack_ou_create(tau, cov, 0, 2);
if (!model) { /* report varmapack_last_error() */ }
else {
bool ok = varmapack_gamma_times(100, 16, 1, t, rng);
if (ok) ok = varmapack_ou_sim(model, t, 100, 1, X, rng);
if (!ok) { /* report varmapack_last_error() */ }
varmapack_ou_free(model);
}varmapack_ou_sim draws the first observation from N(mu,cov) and uses exact
gap-dependent transitions, without burn-in. Times must be finite and strictly
increasing; output has column-major shape r*n*M.
Models copy their inputs, are reusable, and must be freed with
varmapack_ou_free. Workspaces are local to each call; sharing an immutable
model across threads is safe with separate RNGs and output arrays.
varmapack_ou_specrad(model, gap) gives the sampled VAR(1) spectral radius
at a fixed positive gap.
varmapack_gamma_times(n, shape, mean_gap, t, rng) generates times starting at
zero with independent Gamma gaps, scale mean_gap/shape and CV
1/sqrt(shape). It does not normalize the realized mean spacing. Positive
infinite shape gives constant spacing. Unrepresentable positive gaps or times
produce an error. Time generation is independent of the OU simulator, which
also accepts actual observation times. Outputs and the RNG may be partly
advanced if simulation or time generation fails.
varmapack_slepian_create(theta, cov, mu, r) takes the unit-step MA(1)
coefficient matrix theta and the stationary covariance cov. The optional
mean mu defaults to zero. Both matrices are column-major; only the lower
triangle of cov is used. The constructor solves
cov = Sig + theta*Sig*theta^T for the driving covariance Sig.
varmapack_slepian_sim(model, t, n, M, X, rng) uses unit-width Brownian
noise windows and starts in stationarity without burn-in. At unit spacing
it reduces to a vector MA(1). Supply finite, strictly increasing times;
the output has column-major shape r*n*M. Free the model with
varmapack_slepian_free.
varmapack_ou_acvf and varmapack_slepian_acvf return
Cov(X(t+h), X(t)) for finite real lags h as consecutive column-major
matrices. Negative lags transpose the corresponding positive-lag matrix.
Finally, the example creates deterministic two-dimensional exogenous testcase
data. Its d by n input sequence is broadcast to every replicate. To use a
different sequence for each replicate, set Mz=M and store z as d by n
by M.
int s = 2, d = 2;
double C[2*2*2];
double z[2*200];
varmapack_testcasex(s, d, r, n, C, z);
varmapack_simx(A, B, C, Sig, z, 1, p, q, s, d, r, n, M, X0, 2, 1, X, E, rng);
randompack_free(rng);
free(Sig);
free(B);
free(A);
return 0;
}Most Varmapack functions return false on failure and make a diagnostic
available through varmapack_last_error(). The exceptions are
varmapack_specrad() and varmapack_ma_specrad(), which return NAN on
failure. The diagnostic is thread-local, so a failure in one thread does not
replace the error reported in another. Randompack reports errors through its
RNG object. The standalone ErrorCheck.c in the examples folder checks
both libraries:
#include <stdio.h>
#include <varmapack.h>
int main(void) {
int status = 0;
int r = 2, n = 200, M = 10;
double A[] = {0.6, 0, 0.1, 0.4};
double Sig[] = {2, 0, 0, 1};
double X[2*200*10];
randompack_rng *rng = randompack_create(0);
if (!rng) {
fprintf(stderr, "could not create RNG\n");
return 1;
}
if (!randompack_seed(123, 0, 0, rng)) {
fprintf(stderr, "Randompack: %s\n", randompack_last_error(rng));
status = 1;
}
else if (!varmapack_sim(A, 0, Sig, 0, 0, 1, 0, r, n, M, 0, 0, 1, X, 0,
rng)) {
fprintf(stderr, "Varmapack: %s\n", varmapack_last_error());
status = 1;
}
randompack_free(rng);
return status;
}The European stock-index example applies a VAR(1)
model fitted to the EuStockMarkets log returns. Matching C, R, Python, and
Matlab programs generate exact stationary simulations from the fitted model.
Varmapack includes three Meson test programs:
RunTestsprovides direct C unit and edge-case tests of the public functions.AgainstMatlabcompares C results with MATLAB reference outputs.TestLyapunovtests the state-space covariance solver used for simulation startup.
Run the C test suite with:
meson test -C build --print-errorlogsSee tests/README.md for the test groups, statistical validation, and
numerical-robustness cases.
AgainstMatlab compares the public numerical functions and simulated series,
using identical Randompack streams where applicable. The standard suite uses
the checked-in tests/matlabcompare.txt fixture, so MATLAB is not needed to
run it.
Most of the MATLAB reference functions are based on the thoroughly tested MATLAB code from the 2008 ACM TOMS Algorithm 878 package. New reference functions were developed mostly independently of the C implementations. MATLAB functions are generally easier to write from mathematical algorithm descriptions than C functions, making implementation errors less likely. This makes the reference implementation a valuable independent cross-check.
When MATLAB is available, see DEVELOPMENT.md for regenerating the reference
fixture and running the full comparison.
The benchmark directory contains four C timing programs. Build them with:
ninja -C build benchmark/TimeSimulate benchmark/TimeScalability \
benchmark/TimeSetup benchmark/TimeBreakEvenTimeSimulate measures direct C-library simulation for all named testcases. It
uses length 100, 1000 replicates, and a 0.1-second timing target per testcase by
default. Its output is directly comparable with
matlab/examples/TimeSimulate.sh, python/examples/TimeSimulate.py, and
r-package/inst/examples/TimeSimulate.R:
build/benchmark/TimeSimulateUse -h to list its timing and workload options.
TimeScalability varies one of the model order, dimension, series length,
replicate count, or spectral radius at a time around a configurable reference
model. It separates the amortized setup estimate from the remaining generation
time:
build/benchmark/TimeScalabilityTimeSetup and TimeBreakEven are development benchmarks for analyzing the
two startup solvers. See DEVELOPMENT.md for their use.
The AnalyseSpeedup scripts separate the main contributions to the timing
comparisons with R's MTS, Python's Statsmodels VARMAX, and Matlab's varm:
Rscript benchmark/AnalyseSpeedup.R
python benchmark/AnalyseSpeedup.py
benchmark/AnalyseSpeedup.shEach script accepts -h for its timing and workload options.