21 KiB
Changelog
All notable changes to Tensor are documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[development]
Fixed
Linear algebra.
Cholesky,Eigen,EigenComplexand the Cholesky rank-one update refuse a matrix or vector holding a NaN or infinity instead of returning an all-NaN factor or spectrum with a nil error, the refusal the sparse solvers already make.EigenComplexconverges on a Hermitian matrix whose off-diagonal entries all sit just under the per-entry skip level: the sweep no longer exhausts its passes on a matrix it should have declared converged.
Statistics.
FitHiddenMarkovModelfits a single-observation sequence instead of crashing the process: a transition row with no evidence keeps its previous estimate rather than dividing by zero.Viterbirefuses a sequence of probability zero under the model, the same refusalForwardmakes, instead of returning a meaningless path beside a log probability of -Inf.- The Student-t tails stay accurate past the point t squared
overflows float64:
StudentTCDF, the regression coefficient p-values andNoncentralTCDFat extreme t answer the tail the format still holds instead of a silent zero or an error naming a NaN. LinearRegressionandWeightedLinearRegressionkeep their inference alive when the squared deviations underflow to zero: the standard errors, t and F statistics read factored sums of squares instead of reporting infinity beside zero evidence.
Integration and optimisation.
TriangleMesh2D.BoundaryEdgesreturns the mesh's own edges: the boundary pairs sort as pairs, never as one flat index list that interleaves the endpoints of unrelated edges.IntegrateFunctionnames itself in its errors; the adaptive quadrature no longer reports under a name absent from the surface.MinimiseDifferentialEvolutionrefuses a non-finite bound instead of drawing a NaN population and returning a NaN point with no error.
Signal and plots.
WriteSVGkeeps extreme but finite data and axis ranges drawable: the padding, projection and tick arithmetic fall back to forms whose terms stay in range, so the file never carries a NaN coordinate.- Filter design refuses an order whose coefficient arithmetic overflows the float64 range instead of shipping a numerator of zeros or NaN.
[1.0.0] - 2026-09-03
The initial release of Tensor, a scientific computing library in pure Go: immutable n-dimensional arrays over a wide element-type set, dense and sparse linear algebra, differential equations, quadrature, signal transforms, statistics up to mixed models and hidden Markov models, optimisation from simplex to stochastic global search, a reverse-mode differentiable core, deterministic SVG plotting and an experimental SPMD package, with no third-party dependencies and a deterministic, parallel execution model.
The module is one core package plus one package per domain:
sourcedock.dev/petrbalvin/tensor carries the Array core with
element-wise math, special functions and the reproducible generator,
re-exporting the whole surface of every domain package; linalg the
dense and sparse solvers; signal the transforms, filters and
stencils; integrate the differential equations and quadrature;
stats the distributions and inference; optim the fitting and root
finding; io the CSV, FITS, HDF5, NetCDF and memory-mapped readers
and writers; grad the differentiable core; plot the deterministic
figures. Import what you use: the domain packages depend on the core,
never on each other except through five one-directional edges, and
nothing below the root imports the root. The experimental spmd
package stands beside them, imported explicitly: a distributed
program names it, the facade does not.
Added
Core arrays.
- Immutable, shape-checked n-dimensional arrays over int64, float32,
float64, complex128, IEEE 754 float16 and the narrow integer types
Int8, Uint8, Int16, Uint16, Int32 and Uint32, with Bool beside
them, under a strict promotion ladder, row-major layout and
multi-rank text formatting. Constructors cover literals
(
FromInts,FromFloat32s,FromFloats,FromComplexes,FromFloat16s,FromInt8sand the family around them), filled and ranged builders (Zeros,Ones,FullI/FullF/FullC,Range,RangeBy,Linspace,Grid), byte loading and dtype conversions (WithInt/WithFloat/WithComplex, andAstype, which range-checks every conversion into a narrow target with an error naming the value and its index). - Element-wise arithmetic with scalar variants, transcendentals,
comparisons that answer a bool mask of one byte per element
composing through
And,Or,XorandNot(WhereandSelectkeep the int mask), and reductions fromSum,Mean,Min/Max,ProdandDotthrough axis variants,ArgMax,TopK,CumSumandCumProdtoSumKahancompensated summation. Every float fold cuts its line through a canonical partition fixed by the length alone and combines the partials through a balanced tree, so a reduction's answer is a function of the data alone, never of the machine, andCumSumcarries a Neumaier compensation term so a long prefix sheds no small addend. - Shape operations (
Reshape,Flatten,Squeeze,Transpose,TransposeAxes,MoveAxis,Pad,Tile,Repeat,Flip,Roll,Diag, triangular extractions), indexing (contiguousSliceselections as read-only payload views,Gather,Scatter,Take,Nonzero,Argwhere,SearchSorted), and the toolkit piecesEinsum,Unique,OneHot,CrossProduct,Sort,ArgSort, and the numericJacobianof a vector function by central differences. MatMul2D, the parallel cache-friendly kernel; sparse matrices asSparseCOO; interpolation (Interpolate, the Fritsch-CarlsonInterpolateMonotone,Interpolate2D,InterpolateGrid, natural cubic splines); and special functions: the gamma and beta families, error functions, Bessel of integer order and, throughBesselJRealOrder, of any real order, Airy and Fresnel families, exponential integrals, orthogonal polynomials, spherical harmonics, elliptic integrals and Jacobi functions, andCosm1forcos(x) − 1at the arguments where the direct subtraction has no correct significant bit.- Quasirandom sequences for Monte Carlo integration:
HaltonPointsand the base-2 digitalSobolPoints(Joe and Kuo initialisation, 40 dimensions). - Parallel execution across every core with a fixed reduction order,
SetNumCPUto pin the worker count, and pooled scratch buffers whose borrow path zeroes the window. - The reproducible
Generator: xoshiro256++ seeded through splitmix64, stable across Go releases, with uniform, normal and truncated-normal draws, shuffles and permutations;Splitmix64andSubstreamare exported for callers who seed their own streams. The distribution draws of thestatspackage take the same generator, so a seeded program replays exactly.
Linear algebra.
- Dense factorisations and solves: LU (
Solve,Inv,Det), QR besideRRQR, the rank-revealing column-pivoted factorisation withRRQRRankandSolveRRQR, whose rank-deficient path answers the minimum-norm solution, Cholesky with rank-one update and downdate,LeastSquares, the tridiagonal and cyclic-tridiagonal solvers,Pinverse,MatrixRank,Cond. - Eigenproblems in the symmetric, Hermitian-complex, general and
generalised forms;
SVDandSVDComplexin real and complex arithmetic;SchurComplex; the matrix functionsMatrixExp,MatrixSqrtandMatrixLog. - Regularised and truncated solves for ill-posed systems:
SolveTruncated(rank truncation of the singular spectrum) andSolveTikhonov(Tikhonov damping through the SVD). - Sparse direct factorisations:
CSCFromCOOand theSparseCSCview withToCSR/ToCSCconversions,NewSparseCholesky, the sparse Cholesky with the elimination tree, the natural, reverse Cuthill-McKee and minimum-degree orderings and the rank-oneUpdateandDowndate, andNewSparseLU, the Gilbert-Peierls left-looking elimination with partial pivoting. One factorisation solves any number of right-hand sides. - Sparse iterative methods on the CSR view:
SpSolve(conjugate gradient),SpSolveBiCGSTAB,SpLSQRandSpLSMRfor overdetermined systems, the ILU(0) preconditioner, the Lanczos eigensolverSpEigenwith its general Arnoldi form, andSpExpApply, the Krylov action of a matrix exponential. The complex side mirrors it for Hermitian positive-definite and general non-Hermitian operators, the shape Helmholtz and electromagnetics problems need. - Polynomial fitting, roots through the companion matrix, and the
fluent
Pipelinechain over the element-wise surface.
Signal and transforms.
- Fourier transforms of any length:
FFT/IFFT,FFT2,FFT3,FFTN/IFFTN, the real-inputRFFT/IRFFTpair andFFTFreq. - Cosine and sine transforms (orthonormal types I to IV), the type-1 non-uniform FFT by Gaussian gridding, and the short-time Fourier transform with window choice.
- Spectral estimation:
WelchPSD,Spectrogram,LombScarglefor unevenly sampled data, and the spectral Poisson solves in periodic, Dirichlet and Neumann boundaries. - Sample-rate conversion:
Decimatebehind a Kaiser anti-alias filter, rationalResampleand exact band-limitedResampleFourier; the HilbertAnalyticSignalandEnvelope; andChirp, the linear frequency sweep synthesised from the closed-form phase at each sample. - Filter design: Butterworth, Chebyshev, inverse Chebyshev and
elliptic (Cauer) responses in low-pass, high-pass, band-pass and
band-stop forms with explicit ripple and attenuation budgets,
applied through
FilterApplyand, zero phase, throughFiltfilt. - Correlation and wavelets: FFT-based
AutocorrelateandCrossCorrelate,PartialAutocorrelate, the HaarDWT/IDWTand the Daubechies families db2 to db8, and the analyticCWT(Morlet and Mexican hat). - Convolutions, pooling and windows:
Conv1D/Conv2D/Conv3Dwith groups and dilation,ConvTranspose2D, the max, average, adaptive and global pooling families, theMedianFilterandRankFilterfamilies in one and two dimensions, theSavitzkyGolaysmoother, theGradient1D/Laplacianstencils, and the public window catalogueWindowHannthroughWindowBox, each in the symmetric and the periodic convention. - Time-series estimation:
KalmanFilter,ExtendedKalmanFilterandUnscentedKalmanFilterwith the filtered states, covariance history, innovations and the summed log likelihood;EstimateARthrough Yule-Walker over the Levinson recursion,EstimateARMAthrough Hannan-Rissanen innovations,SelectARMAover a lag grid by information criterion, andARMASpectrumfor the theoretical one-sided spectrum.
Differential equations and quadrature.
- Initial value problems:
IntegrateODE(adaptive Dormand-Prince 4(5)) with path and step recording,IntegrateBDF2andIntegrateBDFVar(variable order 1 to 5, VODE-style step and order adaptation) for stiff systems,IntegrateROS4, the L-stable Rosenbrock-Wanner solver,IntegrateBackwardEuler,IntegrateRK4, event detection with direction filters,IntegrateDAEfor semi-explicit index-1 differential-algebraic systems in mass-matrix form, and the symplecticIntegrateVerletbesideIntegrateYoshida4andIntegrateMidpointfor separable and general Hamiltonians. - Boundary values:
IntegrateBoundaryby damped shooting with the root finder ofoptim, andSolveBoundaryCollocationby three-point Lobatto IIIA collocation on an adaptively refined mesh. - Quadrature: adaptive Gauss-Legendre
IntegrateFunction, fixed-nodeGaussLegendreNodes,IntegrateND, globally adaptive cubature over hyperrectangles, andIntegrateFilonfor the oscillatory integrals of a smooth amplitude against a cosine or sine carrier. - Turnkey PDE evolution: the heat equation by Crank-Nicolson in one dimension and Peaceman-Rachford ADI in two, the wave equation by velocity Verlet in one dimension and an explicit central stencil in two, advection by the monotone upwind and Koren-limited fluxes and their advection-diffusion combination, CFL enforced everywhere.
- Finite elements: structured and arbitrary triangular meshes in two
dimensions and tetrahedral meshes in three, with
SolvePoissonFEM2DandSolvePoissonFEM3D, the piecewise-linear Poisson assemblies through the sparse direct factorisation, with Dirichlet lifting and natural Neumann boundaries.
Statistics.
- Distributions: CDFs, quantiles and matched random draws for the normal, exponential, gamma, chi-square, Student t, F and their noncentral forms, Poisson, binomial, negative binomial, Weibull, lognormal, Pareto and Dirichlet laws, built on the incomplete gamma and beta functions.
- Descriptives: mean-free moments,
Median,Quantile, histograms in one and two dimensions, the robustMedianAbsoluteDeviationandTrimmedMean, and the rolling windows. - Inference:
WelchTTest,KolmogorovSmirnovTest,MannWhitneyU, one-wayANOVAOneWay,ChiSquareGoodnessOfFit,BootstrapCI, the rank correlationsSpearmanRhoandKendallTau, the multiple-testing correctionsBonferroni,HolmandBenjaminiHochberg, and the contingency table analysesFisherExactTest,ChiSquareIndependence,McNemarTestandCramersV. - Models:
LinearRegressionwith standard errors, t-tests, p-values, R² and the model F-test,WeightedLinearRegression,LogisticRegressionandPoissonRegressionon the exact likelihood with Wald inference,HuberRegression,TheilSenRegressionandQuantileRegressionfor the robust and distribution-free fits, lasso and elastic net over a documented regularisation path,PCA,KMeanswith k-means++ seeding,GaussianMixtureselected over a component grid byGaussianMixtureBIC, Gaussian-process regression over squared-exponential, Matern 3/2 and 5/2 and periodic kernels, multivariate normal densities and draws, GaussianKernelDensity,LinearMixedModel, the Gaussian linear mixed model with grouped random effects estimated by residual maximum likelihood, the discrete hidden Markov model with itsForward,SmoothandViterbirecursions and its Baum-Welch fit, andHierarchicalClustering, the agglomerative dendrogram with the single, complete, average, centroid and Ward linkages and theDendrogramcuts into flat clusters.
Optimisation.
- Local:
Minimise(Nelder-Mead simplex),MinimiseLBFGSwith box bounds and a projected-gradient convergence measure, andLevenbergMarquardtwith an optional analytic Jacobian. TheLevenbergMarquardtFitform reports χ², a namedFitStatusand, on request, the parameter covariance and per-residual weights throughSigma, and the least squares and system solvers takeParallelJacobian, an explicit opt-in that spreads the finite-difference columns across workers with bit-identical answers. - Constrained:
MinimiseConstrained, the augmented Lagrangian over the box, so equality and inequality rows ofLinearConstraintscompose with the walls, andMinimiseNonlinearConstrainedfor rows that are arbitrary functions. - Global:
MinimiseDifferentialEvolutionfor multimodal, derivative-free landscapes,MinimiseCMAES(the rank-one and rank-mu update set, seeded through the generator) andMinimiseSimulatedAnnealing(geometric cooling), all deterministic under a seed and all honest about an exhausted budget. - Programming:
MinimiseLinearandMinimiseLinearRows, the revised simplex with a two-phase start over standard-form and two-sided row programs, andMinimiseQP, the active-set method for the strictly convex program with the multipliers returned. - Root finding:
FindRoot(Brent),FindRootBrentfor a scalar bracketed root,FindRootNewtonandFindRootSystem(damped Newton with Armijo backtracking and an optional Broyden rank-one update in place of repeated Jacobian builds). A solver that exhausts its budget is refused with an error unless the best-effort exit is requested by name.
Automatic differentiation.
- A reverse-mode graph over the arithmetic surface, the matrix
products (single and batched), the reductions, slicing,
concatenation, axis permutation and the Fourier transforms; every
float leaf accumulates through
Backward. - Complex tensors differentiate under the Wirtinger convention, the loss stays real, and mixed real-complex graphs compose exactly through the 2·Re narrowing.
- Second order:
Hessian(forward-over-reverse) andHessianVectorProductin two gradient evaluations. - On top of the graph:
MinimiseNewtonCG(truncated-CG Newton with an Armijo line search),SampleHMC(Hamiltonian Monte Carlo on any differentiable unnormalised density) andAdjointODE(adjoint sensitivities at the cost of one extra solve).
Plotting.
- The
plotpackage: deterministic SVG line charts of computed series. Linear axes with five ticks, one legend line per series, aLineconstructor straight from two rank-1 arrays through the promotion ladder, and a byte-identical file on every run, so a figure in a paper is compared exactly like any other computed number.
Distributed execution.
- The experimental
spmdpackage: explicit SPMD worlds, one program on many ranks, over TCP between machines or in one process over channels, launched, listened for and joined throughLaunch,ListenandJoin. The movement collectivesBroadcast,Scatter,GatherandAllGathermove arrays between ranks; the sharded reductions cut a global array on the canonical fold partition's block boundaries and combine the partials through the same balanced tree the single-array fold uses, soSum,Min,Max,Any,All,Prod, the norm and the dot families answer the single-array reduction's exact bits at any world size, whatever the order the frames arrive in;ReduceandAllReducefold the ranks' same-shaped arrays elementwise in rank index order.ExchangeHalosandExchangeHalosOnGridhand each rank's boundary slabs to the neighbours of a decomposition laid out on a row-major process grid. Every failure or deadline fails the whole world loudly, and no collective ever returns a partial numeric result.
Data I/O.
- CSV reading and writing, with or without a header row, every stored numeric dtype written and read.
- FITS images with header cards in both directions, and binary and ASCII table extensions.
- HDF5 in both directions:
LoadHDF5reads the default and the "latest" file formats (contiguous, compact and chunked storage, the deflate, shuffle and fletcher32 filters, superblocks of versions 2 and 3 with the lookup3 checksum of each verified, group attributes merged into each dataset), andSaveHDF5withSaveHDF5Textwrites every stored dtype at its native width, booleans through the HDF5 enumeration convention, nested groups, attributes and optional filters, byte-deterministic on every run. Unsupported format features are refused by name, and cyclic or over-deep group walks are refused. LoadNetCDF/SaveNetCDFfor the NetCDF classic model (CDF-1 and CDF-2), with named dimensions, text attributes and record dimensions in both directions, and fixed-point variables landing at their own width and sign.- Memory mapping:
MapFloats,MapFloat32sandMapIntsopen native-endian files as read-only arrays without reading them, andSaveNativeFloatswrites the format they read.
Examples.
- Thirteen runnable workflows in
examples/: ODE parameter fitting by adjoint sensitivities, PSF deconvolution, HMC sampling, spectral analysis, wavelet denoising, the exact pendulum period throughEllipticK, a Helmholtz system on the complex sparse solvers, quasi-Monte Carlo integration, heat and wave evolution, regression inference, a FITS star field, a NetCDF climate round trip and an FFT tour.
Project.
- A determinism oracle pinning fixed workloads through the facade by SHA-256 digest of the output bits, and a resource-leak harness holding the goroutine count and live heap to baseline under repeated heavy runs.
- Gitea Actions pipelines for test, race and release, with the release notes extracted from this file's matching section.
- The document set: this changelog, the README, the API reference, the architecture, the development guide, the benchmarking method, the contribution rules and the security policy, under the MIT licence.