The Prelude
Hilbert's standard library — 46 modules written in Hilbert itself, from ring identities to reinforcement learning.
The Prelude ships with the compiler. Nothing in it is special: every module is a .hb file of
defs and laws built from the intrinsics — einsum, a few elementwise maps, two
reductions, triangle and the extents rows and columns. Bring a module into a document with
open:
open Prelude.Statistics
open Prelude.Regression
Opening a module also brings in the modules it opens. All names share one namespace, so a doorway you write must not reuse a Prelude name (see The language).
How to read a reference page
Every definition is stated the way a mathematician states it: first each symbol is introduced — let \(x \in \mathbb{R}^n\) be a column of \(n\) values — then the result is given as a formula, derived from what the definition actually computes (including guards, floors and the number of iterations). The notation is shared across all pages:
| Notation | Meaning |
|---|---|
| \(x \in \mathbb{R}^n\), \(x_i\) | a vector of length n and its components |
| \(A \in \mathbb{R}^{n \times p}\), \(A_{ij}\) | a matrix and its entries; a data matrix has one row per observation |
| \(A \odot B\) | the elementwise product |
| \([P]\) | the Iverson bracket: 1 if \(P\) is true, 0 otherwise — how Hilbert writes a comparison mask |
| \(\mathbf{1}_n\), \(I_p\), \(e_k\) | the vector of ones, the identity matrix, a basis vector |
| \(d + [d = 0]\) | a guarded divisor (safe): a zero is replaced by one |
| \(u \in [0, 1)^n\) | independent uniform draws supplied by the caller |
- Each customer-facing definition has its own entry: the signature with the meaning and shape of every parameter, its mathematical statement, what it is for, and its definition copied from the source.
- Beside each entry, a why note gives the intuition (how to picture the quantity and why it is
shaped that way) and use it when (the problems it solves, practical tips, and which sibling to use
instead). The tags at the foot of the note name the kinds of problems it helps with, such as
outlier-detectionorcredit-assignment. - Building blocks — helpers, loop bodies and intermediate terms — are listed at the end of each section, each with its own mathematical statement. They can be used, but they exist to serve the entries above them.
- Examples at the end of each page were compiled with the Hilbert compiler and run; the outputs shown are the real outputs.
- Shapes use n for observations (rows of a data matrix), p for features, k for classes or clusters, s and a for states and actions.
Randomness is an argument. No Prelude definition draws random numbers by itself. Samplers, bootstraps and simulations take their uniform or Gaussian draws as tensors, so every result is reproducible from its inputs. Models and processes generate seeded draws for you.
Chemistry
- Chemistry — .hcWrite chemistry as a rewriting system. Reactions are laws the build balances, syntheses are theorems it establishes, and every claim is checked by the proof kernel.
- ChemistryThe chemistry prelude — the periodic table, the isotopes and every datum the slices read, each with its source — and the runtime a generated chemistry class returns.open Chemistry.Elements, Chemistry.Isotopes, Chemistry.Atoms, Chemistry.Thermo, Chemistry.Inorganic, Chemistry.Organic, Chemistry.Phases, Chemistry.Nuclear, Chemistry.Spectra
Materials
Agents
- BDI agentsBelief, desire and intention as a modal theory — an agent written in .ha, its plans written in .hk and proved before they run.
- Reactive, deliberative and the LLMAn agent that acts at once, stops when it is in danger, thinks before it continues — and uses a language model for ideas and knowledge without ever letting it decide.
Reference
- The PreludeHilbert's standard library — 46 modules written in Hilbert itself, from ring identities to reinforcement learning.
- IntrinsicsThe few functions and constants the compiler knows without a library — everything else is defined in Hilbert.
Foundations
- ArithmeticThe ring identities over the reals, stated as laws that simplify formulas such as x · 1 to x and x + 0 to x.open Prelude.Arithmetic
- TrigonometryFive trigonometric identities, true for every real, stated as laws that simplify sines and cosines before code is generated.open Prelude.Trigonometry
- CalculusThe rules of differentiation as laws, so a derivative written with ∂ is reduced to an ordinary formula at compile time.open Prelude.Calculus
- Linear algebraMatrix products, the inverse, Cholesky, QR, the symmetric eigenproblem, the SVD and a positive-definite solver, all written over einsum.open Prelude.LinearAlgebra
- KernelsDistance and kernel matrices, row-wise argmin and argmax masks, kernel centring and a numerically stable softmax, for writing learners over.open Prelude.Kernels
Statistics
- StatisticsDescriptive statistics of a column or a data matrix: moments, covariance and correlation, ranks, order statistics, quantiles, sorting and weighted forms.open Prelude.Statistics
- DistributionsDensities, CDFs, quantiles and samplers for twenty probability distributions, with the special functions (ln Γ, incomplete gamma and beta, erf) beneath them.open Prelude.Distributions
- MultivariatePrincipal components, whitening, Mahalanobis distance, ordinary, weighted and ridge least squares, and linear discriminants over a data matrix.open Prelude.Multivariate
- CategoricalContingency tables, the χ² test of independence, Cramér's V and entropy-based association measures, all computed from one-hot columns.open Prelude.Categorical
- Inferencet-tests, one-way ANOVA, confidence intervals, the correlation test and multiple-comparison corrections, each returning a statistic or a p-value.open Prelude.Inference
- ResamplingThe bootstrap, permutation tests and the rank tests (Mann–Whitney, Kruskal–Wallis, Wilcoxon signed rank), computed without loops over replicates.open Prelude.Resampling
- SeriesAutocovariance and autocorrelation, rolling-window statistics, differencing, and the closed-form conjugate Bayesian updates.open Prelude.Series
- MetricsScores for judging models: classification counts and rates, ROC-AUC, log loss and Brier, regression errors and R², and the silhouette.open Prelude.Metrics
Machine learning
- RegressionLogistic and Poisson regression by Newton's method, the lasso and elastic net, a linear SVM, kernel ridge and Gaussian-process regression.open Prelude.Regression
- FittingA two-component normal mixture by expectation–maximisation, a reproducible Metropolis chain, AR(1) and AR(2) fits with forecasts, and exponential smoothing.open Prelude.Fitting
- LearningActivations, losses with their gradients, and the optimiser steps (momentum, RMSProp, Adam, soft thresholding) that training loops are built from.open Prelude.Learning
- SelectionCross-validation folds as masks, a cross-validated ridge regression with a penalty grid search, and simple column scores for feature selection.open Prelude.Selection
- BayesGaussian, multinomial and Bernoulli naive Bayes classifiers, fitted in closed form, plus per-class sizes, priors, means and variances.open Prelude.Bayes
- Neighboursk-nearest-neighbour classification and regression, the nearest centroid, the local outlier factor and kernel density estimation.open Prelude.Neighbours
- Clusteringk-means, DBSCAN, single-linkage and spectral clustering over a data matrix, written as masks and one closure with no loop over points.open Prelude.Clustering
- ManifoldDimension reduction and embedding: classical scaling, kernel PCA, Isomap, truncated SVD, non-negative factorisation, random projection and t-SNE.open Prelude.Manifold
- PatternsMarket-basket rules, Apriori pruning, PageRank and recommendation, computed as contractions over matrices of ones and zeros or ratings.open Prelude.Patterns
- TreesRegression and binary classification trees (CART), weighted trees, random forests from bootstrap counts, gradient boosting and penalised leaves.open Prelude.Trees
- NetworksDense layers and backpropagation, autoencoders, layer normalisation, attention, dropout, convolution, recurrent and gated cells, and an adversarial pair.open Prelude.Networks
- SequencesHidden Markov models (forward, backward, posteriors, Viterbi), the scalar Kalman filter, Kaplan–Meier survival and Cox proportional hazards.open Prelude.Sequences
Stochastic processes
- ChainsDiscrete-time Markov chains answered by linear algebra — stationary distributions, reversibility, absorption, branching, urns and fitting a chain to a path.open Prelude.Chains
- PathsRandom walks one step at a time — lazy walks, barriers, gambler's ruin in closed form, the Brownian bridge, betting systems, running extremes and path statistics.open Prelude.Paths
- PointsPoint processes — Poisson arrivals, thinning, renewal gaps, Hawkes self-excitation, Cox overdispersion, Ripley's K and simple fits.open Prelude.Points
- JumpsContinuous-time Markov chains by uniformisation, birth–death and telegraph processes, compound Poisson moments and Gillespie's stochastic simulation step.open Prelude.Jumps
- DiffusionsStochastic differential equations — Euler–Maruyama and Milstein steps, with the closed forms of Brownian motion, GBM, Ornstein–Uhlenbeck, CIR, Merton jumps and fractional Brownian motion.open Prelude.Diffusions
- QueuesClosed-form answers for waiting lines — M/M/1, Erlang B and C, bounded queues, Pollaczek–Khinchine and Jackson networks.open Prelude.Queues
- VolatilityModels whose variance is itself a process — GARCH, EGARCH, Heston, regime switching and AR(1) — with their stationarity tests.open Prelude.Volatility
- FieldsApplied stochastic models — Ising and Potts rings, SIR epidemics, Wright–Fisher and Moran genetics, percolation and insurance ruin.open Prelude.Fields
- SamplingOne-step Markov chain Monte Carlo moves, importance and rejection sampling, variance reduction, particle filtering and stick-breaking priors, driven by draws you supply.open Prelude.Sampling
Evolution
- GeneticsThe operators of an evolutionary algorithm — spawn, select, cross, mutate, survive and read — for bits, reals, integers and permutations, written as masks and one-hot contractions.open Prelude.Genetics
- EvolutionGenetic algorithms for four encodings, NSGA-II, evolution strategies, CMA-ES, differential evolution, particle swarms and ant colonies — each a category a process inherits by supplying its fitness.open Prelude.Evolution
Graphs
Reinforcement learning
- ReturnsDiscounted returns for every step of a trajectory at once, split at episode boundaries, with TD errors and GAE.open Prelude.Returns
- PoliciesTurning a table of action values into a policy — greedy, ε-greedy, Boltzmann and UCB — plus one-hot encoding, entropy and the softmax score.open Prelude.Policies
- TemporalModel-free tabular learning — one batched update fed by Q-learning, SARSA, expected SARSA or double-Q targets, plus eligibility traces and Dyna.open Prelude.Temporal
- DecisionsSolving a finite Markov decision process given as tensors — value iteration, exact policy evaluation, policy iteration and advantages.open Prelude.Decisions
- TrajectoriesRolling out episodes of a tensor MDP under a policy from caller-supplied uniform draws, plus inverse-CDF sampling and replay gathers.open Prelude.Trajectories
- ApproximationValue learning when the table will not fit — linear semi-gradient TD, exact LSTD and the DQN target matrix.open Prelude.Approximation
- ObjectivesPolicy-gradient methods over features — a softmax policy, REINFORCE with a baseline, entropy, and the clipped PPO gradient.open Prelude.Objectives
- DeliberationLearned plan selection that can never choose an unlicensed option — masked greedy, ε-greedy, softmax and UCB policies, and a leakage check.open Prelude.Deliberation