Skip to main content

API reference

Runnable examples shows these entry points composed into checked solver, correction/AD, reconstruction and MFM/MFV clients.

For meshless geometry, reconstruction and conservative flux rates, see the MFM/MFV API and numerical contracts.

Every public function, by module. Signatures are abbreviated to the arguments that matter; the detailed pages carry the equations, options, and JVP scopes. Flat imports work for everything listed (from warpSPHCore import … — see __init__.py's __all__ aggregation).

CUDA operators, prepared launches, geometry/value JVPs, Density HVPs and the autograd bridges follow Torch's current stream on the tensor's device. Warp adjoint-buffer initialization, reverse launches and gradient clearing use that same stream. Callers establish dependencies before moving data or reusing scratch across streams; the bridge adds no device-wide synchronization.

Type configuration — type_config.py​

Configure before import/compilation. warpSPHCore_PRECISION=float32|float64 selects floating-point precision; warpSPHCore_INDEX_DTYPE=int32|int64 selects stored particle IDs, and warpSPHCore_OFFSET_DTYPE=int32|int64 selects CSR offsets and edge-address arithmetic. Both integer settings default to int32 independently of precision. Per-row counts remain int32; search totals/prefix scans use int64, with a range check before storing offsets or allocating neighbor capacity.

The optional warpSPHCore_config module uses precision, dim, index_dtype and offset_dtype, overriding corresponding environment settings. Types cannot be changed after import; start a new process for another configuration. get_type_config() reports scalar_t, dim_t, index_t, offset_t and neighbor_count_t; get_torch_index_dtype() and get_torch_offset_dtype() return the matching Torch dtypes. Manually supplied adjacency/grid buffers must use the configured types; kernels receive these buffers directly without dtype conversion.

Int64 offsets remove the repository's narrowing points but do not remove Warp's current signed-int32 array-dimension limit. Flat neighbor capacity, including padding/headroom, and particle populations are checked against that backend limit before allocation/traversal. Grid cell keys retain int64 independently.

Operators — operations.py​

functionwhat it doesdetails
warpOperation(queryParticles, operationProperties, domain, queryValues=None, referenceValues=None, queryVolumes=None, referenceVolumes=None, adjacency=None, referenceParticles=None, preScatteredQuantities=None, crkState=None, gradHState=None, renormalizationState=None, consistentDivergence=False, covarianceReturnNumNeighbors=False)the unified entry point — dispatches on operationProperties.operation to one of the seven operatorsone page per op: Density, Gradient, Divergence, Curl, Laplacian, Interpolate, Covariance
warpOperationJVP(…, tangentQueryValues=None, tangentReferenceValues=None, queryTangentState=None, referenceTangentState=None, crkTangentState=None, renormalizationTangentState=None, tangentReferenceVolumes=None, …)forward-mode JVP of warpOperation: returns the sum of the requested pieces (value tangent, geometry tangent, correction tangents); scope rules per operator (which schemes/ops accept which tangents)the JVP sections of the operator pages
warpOperationHVP(…, v)the Density position Hessian ∇xx2ρi\nabla^2_{xx}\rho_i applied to a vector field — a dedicated kernel, not a composed JVP (only operator with an HVP)Density — HVP
sphOperation_warp(…)the flat-tensor entry point (queryKinds/referenceKinds as keyword-only required tensors, useCRK/useVolume/useGradHTerms/useGradientRenormalization flags) — the interface the lower-level callers and the integrator repo useAutodiff machinery (the bridge it resolves into)

CUDA neighbor loops can use multiple cooperating lanes per query particle. setNeighborLanes(1) selects serial traversal; setNeighborLanes(32) explicitly selects tiled kernels where available. Other supported choices are 2, 4, 8 and 16. setNeighborLanes(None) restores the environment/per-operator defaults. The environment equivalent is WARPSPHCORE_NEIGHBOR_LANES, read at import time. CPU execution remains serial.

Density, interpolation, gradient, divergence and covariance retain their existing 32-lane defaults. Curl and Laplacian have trial tiled variants and retain serial defaults: explicit lane choices opt into them. Small-problem speedups do not imply a large-problem speedup, so benchmark the intended size, degree and traversal before selecting lanes. Ordinary and prepared launches resolve the same policy. The existing correction and AD scope is preserved; geometry JVPs continue to use their existing kernels. Changing a captured operator's lane configuration requires rebuilding its graph or clearing its owning solver workspace's capture cache.

Neighbor search — radiusSearch/​

functionwhat it doesdetails
radiusSearchCompactHashMap(queryParticles, domain, mode, hashMapLengthMode=NextPrime, fixedHashMapLength=4096, returnCompactHashMap=False, referenceParticles=None)build the compact hash map and collect an AdjacencyListNeighbor search
buildCompactHashMap(…)the hash-map half only (a CompactHashMap)same
radiusSearchOnCompactHashMap(…)the collection half only (hash map → AdjacencyList)same
buildVerletList(…, verletScale=1.0, priorNeighborhood=None)Verlet-list build with skin, reusing a prior list when still validNeighbor search — Verlet
updateNeighborsVerlet(…) / filterVerletList(…)incremental pair additions between steps / dropping pairs that left the true supportsame
radiusNaive(x, y, hx, hy, …) / radiusNaiveFixed(…)the O(N2)O(N^2) all-pairs reference (validation, not production)Neighbor search — other backends
warp_radius_search_small(…)small-system variantsame
checkOffset / getIndexRangethe stencil-offset and neighbor-block accessors every dual-path operator kernel usesNeighbor search

CRK — crk/​

functionwhat it doesdetails
computeCRKFactors(queryParticles, domain, kernel, operationMode=AllToAll, adjacency=None, referenceState=None, *, referenceVolumeMode=None)full CRK pipeline; optional independent reference-to-reference volume rule; returns (apparentArea, crk_density, CRKState)CRK overview
computeCRKFactorsJVP(…)the pipeline's JVP (chained volume → moments → torch.autograd.functional.jvp through the terms solve)CRK overview — JVP
computeKernelCRK(…) / computeKernelGradientCRK(…)the corrected kernel value / gradient W^ij\widehat W_{ij}, ∇W^ij\nabla\widehat W_{ij}CRK overview — corrected kernel
computeKernelGradientCRKJVP(…) / correctGradientCRKJVP(…)the forward-mode building blocks the operator JVPs call for the CRK piecesCRK overview

Renormalization — renorm.py​

functionwhat it doesdetails
computeRenormalizationMatrices(queryParticles, operationProperties, domain, …, returnEigVals=True)covariance (on a properties copy) → low-neighbor identity fallback → pseudo-inverse; returns (C, eigVals, RenormalizationState)Renormalization
computeRenormalizationMatricesJVP(…, queryTangentState, …)masked covariance tangent → selected spectral inverse tangent, including retained/discarded rotationRenormalization — JVP
pinv1x1 / pinv2x2_warpBackend (and the pinv_warp dispatcher, pinv/)the dimension-dispatched pseudo-inverse (2D closed-form symmetric eigendecomposition, Warp kernel)Renormalization — step 3

Polynomial fits and reconstruction — polyfit/​

entry pointwhat it doesdetails
PolyFit.build(particles, domain, kernel, order, ...)local MLS/RKPM or LABFM fit; values, diffuse derivatives and interface states, with rank/condition diagnosticsReconstruction
Reconstructor.teno(...) / Reconstructor.weno(...)component-wise nonlinear candidate weighting; first-order fallback when no candidate is usableReconstruction
interfacePairs(...)live directed/half pair lists and minimum-image vectorsReconstruction

Linear algebra — linalg/​

functionwhat it doesdetails
cg(...) / bicg(...) / bicgstab(...)Matrix-free solves with device stopping predicates, bounded restarts and verified original residualsLinear algebra
gmres(..., restart=30, preconditionerSide='right', accumulationDtype=None)Restarted Arnoldi/Givens solve with left/right preconditioning, bounded residual repair and verified convergenceRestarted GMRES
minres(..., symmetric=True, precond=None, preconditionerSPD=False)Short-recurrence indefinite/singular symmetric solve, explicit inverse-SPD contract and verified original residualMINRES
richardson(..., omega=None, backtracking=True, maxBacktracks=8)Fixed/adaptive scalar updates, bounded true-residual search, finite best-iterate fallback and explicit trial diagnosticsRichardson
LinearOperator(shape, dtype, device, matvec=None, matvecOut=None, adjoint=None)Callable operator metadata, supplied-output action and optional explicit transposeOperator metadata
RestrictedSystem(operator, freeIndices)Owned coordinate restriction, Dirichlet RHS lifting/reconstruction, explicit reduced adjoint and inverse-action restrictionRestricted systems
NullspaceSystem(operator, rightBasis, leftBasis, ...)Declared Euclidean nullspaces, explicit source compatibility/projection, projected inverse actions, gauges and original-source residual reportsNullspaces and gauges
DiagonalPreconditioner(diagonal, ...) / BlockJacobiPreconditioner(blocks, ...)Owned inverse actions, explicit singular/SPD policies, adjoints, fixed-address updates and optional native small-block applicationPreconditioner helpers
CGWorkspace(b, maxiter, history=True, capture=False)Reusable native inference-only CG updates, optional history, owned results, supplied-output matvecs and cached CUDA chunksNative CG workspace
BiCGStabWorkspace(b, maxiter, history=True, capture=False)Native right-preconditioned BiCGStab, reusable scratch, half/full guards, supplied-output operator/preconditioner actions and cached chunksNative BiCGStab workspace
pinvSymmetric(M, rtol=None) / applyPinv(V, M, rtol=None)Small symmetric pseudoinverse and fused application, with reverse/forward AD fallbackSmall symmetric matrices
runStationary(...) / CheckSchedule(...) / residualStatistic(...)Shared stationary loop, checkpoint schedule and pressure residual statisticsStationary iteration

Kernels — kernels/​

functionwhat it doesdetails
sphKernel(x_i, x_j, h_i, h_j, kernelProperties, domain) / sphKernel_ij(…)WijW_{ij} (lattice factor included)Kernel library
sphKernelGradient(…) / sphKernelGradient_ij(…)∇iWij\nabla_i W_{ij}same
sphKernelHessian(…)∇2Wij\nabla^2 W_{ij} (ε\varepsilon-regularized)same
sphKernelDkDh(…) / sphGradientDkDh(…)∂W/∂h\partial W/\partial h, ∂∇W/∂h\partial\nabla W/\partial h (the grad-h building blocks)same
sphKernelLaplacian(…)the analytic kernel Laplacian (the Naive Laplacian scheme's estimator)Kernel library — naive Laplacian
sphKernelJVP(…) / sphKernelJVP_ij(…)(Wij,dWij)(W_{ij}, dW_{ij}) — forward-mode building blockKernel library — JVPs
sphKernelScale / sphKernelC_d / sphKernelN_H / sphKernel_xiDehnen & Aly packing/support properties (not evaluations — the lattice factor is deliberately not applied to them)Kernel library — packing
resolveNormalization(kernelProperties)the 1/L1/L lattice factor (1.0 when the calibration is off)Lattice calibration

Lattice density — util/latticeDensity.py​

functionwhat it doesdetails
latticeDensity(kernel, n_h, dim, method='shells')L(nh)L(n_h) — what a perfect lattice at h/s=nhh/s = n_h measures, in units of ρ0\rho_0 (cached)Lattice calibration — the math
latticeDensityFactor(kernel, n_h, dim, method='shells')1/L1/L — the mass/kernel scalingsame
latticeDensityShells / latticeDensityFourier / latticeDensityClosedthe three evaluation methods (exact shell sum / Poisson identity / Wendland-only Epstein-zeta tail)same
latticeDensityIsStrictlyAbove1(kernel)Wendland ⇒ L>1L > 1 for all nhn_h (no root in hh)same
shellCounts / jacobiR2rd(j)r_d(j) shell multiplicities (direct count / Jacobi's two-square closed form)same
kernelFourierTransform / epsteinZeta / WENDLAND_TAIL_COEFFICIENTSthe W^\widehat W and ZdZ_d constants behind the fourier/closed methodssame

Utilities — util/​

functionwhat it doesdetails
generateNeighborTestData(nx, targetNumNeighbors, dim, periodic, device)the standard nxdn_x^d lattice test case (notebooks + most of tests/operations/)Neighbor search — test-data helpers
volumeToSupport(volume, targetNeighbors, dim) (and _tensor/_warp variants)hh for a target neighbor count from a particle volumesame
n_h_to_nH(n_h, dim) / nH_to_n_h(…)resolution-knob ↔ target-neighbor-count conversionsame
computePairwiseSupport(h_i, h_j, scheme)the per-pair support resolution (the subgradient the JVPs mirror)Kernel library — support schemes
castTorchToWarp / castWarpToTorch / castTorchToWarpAsBuiltinstorch↔Warp conversions (the "as builtins" variant preserves vector/matrix layouts)Autodiff machinery

The autograd bridge — autograd/​

namewhat it isdetails
StateAwareWarpFunction (warpWrapperStateaware)the torch.autograd.Function bridging Warp tapes and the torch graph (forward/backward/jvp)Autodiff machinery — the bridge
warpWrapper2(launcher, kernel, outputSizes, outputDtypes, defaultStateArguments, additionalArguments=(), numThreads=None, jvp_fn=None)the legacy positional entry into _launchAutodiff machinery — call chain
warpWrapper / WarpFunctionWrapperthe older (flat-tensor-only) bridge, kept for compatibilitysame
extractStateInfo(…)the 36-slot flattening + build_fn builder (also where the lattice factor is resolved)Autodiff machinery — the 36-slot layout
launch_kernel(kernel, output_shape, output_dtype, *args, numThreads=None)torch-allocated output + wp.from_torch view + wp.launchsame
asScalarArg(value, *, device)scalar → device tensor for kernel arguments—
OperatorSpec / OutputSpec / ExtraSpec / ExtraKind / ShapeOf / ThreadSpec / JVPSpec / SPHContext / Corrections / EMPTY_CORRECTIONS / launchOperatorthe declared operator ABIAutodiff machinery — the declared ABI

Data types and enums​

All in dataTypes / enumTypes: ParticleState, ParticleTangentState, DomainDescription, OperationProperties, AdjacencyList, CompactHashMap, CRKState, CRKTangentState, GradHState, RenormalizationState, RenormalizationTangentState, kernelState, Field, SupportScheme, KernelFunctions, GradientScheme, LaplacianScheme, WarpOperation, OperationDirection, ParticleType, HashMapLengthMode, ExecutionMode, ViscosityTerms.

Version​

warpSPHCore.__version__ — 0.5.0.