Oakfield API Documentation 1.0.0
Numerical core APIs
Loading...
Searching...
No Matches
integrator.h File Reference

Base definitions for time-integration schemes in libsimintegrators. More...

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "oakfield/field.h"
Include dependency graph for integrator.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  IntegratorConfig
 Configuration parameters for integrator construction. More...
 
struct  Integrator
 Integrator instance shared across schemes. More...
 

Typedefs

typedef SimField Field
 Alias matching the simulation field type used by integrator APIs.
 
typedef SimResult(* IntegratorDriftFn) (struct Integrator *integrator, const Field *field, const double *state, double *out_derivative, size_t count)
 Drift callback computing deterministic derivatives.
 
typedef SimResult(* IntegratorNoiseFn) (struct Integrator *integrator, const Field *field, double *out_noise, size_t count)
 Hook producing stochastic source samples.
 
typedef void(* IntegratorDestroyFn) (struct Integrator *integrator)
 Optional teardown hook for integrator-owned state.
 
typedef void(* IntegratorStepFn) (struct Integrator *integrator, Field *field, double dt)
 Integrator step function signature.
 
typedef struct IntegratorConfig IntegratorConfig
 Configuration parameters for integrator construction.
 
typedef struct Integrator Integrator
 Integrator instance shared across schemes.
 

Functions

SimResult integrator_configure (Integrator *integrator, const char *name, IntegratorStepFn step_fn, const IntegratorConfig *config)
 Initialize an integrator object.
 
void integrator_destroy (Integrator *integrator)
 Release resources held by an integrator.
 
SimResult integrator_ensure_workspace (Integrator *integrator, size_t buffers, size_t elements)
 Ensure scratch buffers are available.
 
double * integrator_buffer (Integrator *integrator, size_t index)
 Access a real workspace buffer.
 
size_t integrator_state_length (const Field *field)
 Compute the scalar length of a field.
 
double integrator_clamp_dt (const Integrator *integrator, double dt)
 Clamp a timestep to configured bounds.
 
double integrator_suggest_dt (const Integrator *integrator, double dt, double error_norm, double method_order)
 Suggest a new timestep based on an error estimate.
 
double integrator_reject_dt (const Integrator *integrator, double dt, double error_norm, double method_order)
 Shrink a rejected timestep using the observed error when available.
 
double integrator_measure_error (const double *a, const double *b, size_t count)
 Measure scaled infinity-norm error between two real state vectors.
 
double integrator_rng_normal (Integrator *integrator)
 Generate a standard normal variate using the integrator RNG.
 
uint64_t integrator_workspace_bytes (const Integrator *integrator)
 Report allocated workspace bytes owned by the integrator buffers.
 
uint64_t integrator_drift_scratch_bytes (const Integrator *integrator)
 Report reusable drift scratch bytes owned by the integrator.
 
void integrator_apply_stochastic (Integrator *integrator, Field *field, double *scratch, size_t count, double dt)
 Apply stochastic increments to the field when enabled.
 
double integrator_last_step (const Integrator *integrator)
 Retrieve the timestep used by the previous update.
 
double integrator_next_step (const Integrator *integrator)
 Retrieve the suggested timestep for the next call.
 
double integrator_measure_error_complex (const SimComplexDouble *a, const SimComplexDouble *b, size_t n)
 Measure scaled RMS error between two complex state vectors.
 
SimComplexDoubleintegrator_buffer_complex (Integrator *integrator, unsigned int index)
 Access a complex workspace buffer.
 
SimResult integrator_noise_gaussian (struct Integrator *integrator, const Field *field, double *out_noise, size_t count)
 Fill a buffer with zero-mean, unit-variance Gaussian noise samples.
 
SimResult integrator_noise_uniform (struct Integrator *integrator, const Field *field, double *out_noise, size_t count)
 Fill a buffer with zero-mean, unit-variance uniform noise samples.
 
SimResult integrator_noise_laplace (struct Integrator *integrator, const Field *field, double *out_noise, size_t count)
 Fill a buffer with zero-mean, unit-variance Laplace noise samples.
 
double integrator_last_error (const Integrator *integrator)
 Retrieve the error norm reported by the last step.
 
SimResult integrator_context_drift (Integrator *integrator, const Field *field, const double *state, double *out_derivative, size_t count)
 Drift helper evaluating the current context plan side-effect free.
 
SimResult integrator_step_context (Integrator *integrator, struct SimContext *context, struct SimBackend *backend, double dt)
 Step a context-backed integrator without advancing context time.
 

Detailed Description

Base definitions for time-integration schemes in libsimintegrators.

Integrators advance one target field by repeatedly evaluating a drift callback, optionally adding stochastic increments, and recording timestep diagnostics for adaptive controllers and runtime reporting. The public contract uses scalar counts: real fields have one scalar per element, while complex fields have one SimComplexDouble per element and are passed through callback buffers as double* storage with real/imag components preserved by the field representation.

Typedef Documentation

◆ Integrator

typedef struct Integrator Integrator

Integrator instance shared across schemes.

The struct is public so host runtimes can inspect diagnostics and attach context userdata. Buffers and drift snapshots are owned by the integrator after successful configuration and are released by integrator_destroy().

◆ IntegratorConfig

Configuration parameters for integrator construction.

Zero-initialized optional fields select the defaults in integrator_configure(). The drift callback is required for all concrete integrators.

◆ IntegratorDestroyFn

typedef void(* IntegratorDestroyFn) (struct Integrator *integrator)

Optional teardown hook for integrator-owned state.

Parameters
integratorIntegrator being destroyed; the hook may clear userdata.

◆ IntegratorDriftFn

typedef SimResult(* IntegratorDriftFn) (struct Integrator *integrator, const Field *field, const double *state, double *out_derivative, size_t count)

Drift callback computing deterministic derivatives.

The callback must evaluate the derivative at state without taking ownership of any buffer. Real states contain count doubles. Complex states are passed as storage compatible with SimComplexDouble[count], cast through double* for the shared callback signature.

Parameters
integratorCalling integrator instance.
fieldField metadata associated with the state.
stateRead-only state vector owned by the caller.
[out]out_derivativeOutput buffer receiving d(state)/dt.
countNumber of real entries or complex entries in the state vector.
Returns
SIM_RESULT_OK on success, or an error code propagated by the stepper.

◆ IntegratorNoiseFn

typedef SimResult(* IntegratorNoiseFn) (struct Integrator *integrator, const Field *field, double *out_noise, size_t count)

Hook producing stochastic source samples.

The hook fills caller-owned storage with unit-variance, zero-mean samples before stochastic_strength * sqrt(dt) scaling is applied.

Parameters
integratorCalling integrator instance.
fieldField metadata associated with the state.
[out]out_noiseOutput buffer receiving count samples.
countNumber of scalar elements to populate.
Returns
SIM_RESULT_OK on success, or an error code when sampling fails.

◆ IntegratorStepFn

typedef void(* IntegratorStepFn) (struct Integrator *integrator, Field *field, double dt)

Integrator step function signature.

The implementation updates field in place and records last_step, last_error, attempt counters, and the next current_dt suggestion.

Parameters
integratorConfigured integrator instance.
fieldTarget field advanced in place.
dtRequested timestep; nonpositive values let the integrator use its current timestep suggestion.

Function Documentation

◆ integrator_apply_stochastic()

void integrator_apply_stochastic ( Integrator integrator,
Field field,
double *  scratch,
size_t  count,
double  dt 
)

Apply stochastic increments to the field when enabled.

Built-in real noise laws are Gaussian, uniform, and Laplace, all normalized to unit variance before scaling by stochastic_strength * sqrt(dt). Complex storage currently receives Gaussian real/imag samples.

Parameters
integratorIntegrator instance.
fieldField to modify in place.
scratchScratch buffer to reuse for noise samples.
countNumber of real entries or complex entries in the state.
dtDuration of the realized timestep.

◆ integrator_buffer()

double * integrator_buffer ( Integrator integrator,
size_t  index 
)

Access a real workspace buffer.

Parameters
integratorIntegrator instance.
indexZero-based buffer index.
Returns
Pointer to the buffer, or NULL when index is unavailable.

◆ integrator_buffer_complex()

SimComplexDouble * integrator_buffer_complex ( Integrator integrator,
unsigned int  index 
)

Access a complex workspace buffer.

Parameters
integratorIntegrator instance.
indexZero-based buffer index.
Returns
Pointer to complex scratch storage, or NULL when unavailable.

◆ integrator_clamp_dt()

double integrator_clamp_dt ( const Integrator integrator,
double  dt 
)

Clamp a timestep to configured bounds.

Parameters
integratorIntegrator instance; NULL leaves dt unchanged.
dtProposed timestep.
Returns
Timestep constrained to [min_dt, max_dt] when possible.

◆ integrator_configure()

SimResult integrator_configure ( Integrator integrator,
const char *  name,
IntegratorStepFn  step_fn,
const IntegratorConfig config 
)

Initialize an integrator object.

Parameters
[out]integratorTarget integrator; overwritten on success.
nameHuman-readable identifier copied into Integrator::name.
step_fnStep function implementation; must be non-NULL.
configConfiguration parameters, or NULL to use defaults.
Returns
SIM_RESULT_OK on success, SIM_RESULT_INVALID_ARGUMENT when required pointers or drift callbacks are missing, or SIM_RESULT_OUT_OF_MEMORY when preallocated workspace cannot be prepared.

◆ integrator_context_drift()

SimResult integrator_context_drift ( Integrator integrator,
const Field field,
const double *  state,
double *  out_derivative,
size_t  count 
)

Drift helper evaluating the current context plan side-effect free.

The integrator userdata must point at a SimContext. The helper snapshots context fields, writes state into field, executes the prepared plan, and restores the original field data before returning the finite-difference drift.

Parameters
integratorIntegrator whose userdata is a SimContext*.
fieldTarget field metadata.
stateCandidate state vector owned by the caller.
[out]out_derivativeBuffer receiving the context-derived derivative.
countNumber of real entries or complex entries in state.
Returns
SIM_RESULT_OK, SIM_RESULT_INVALID_ARGUMENT, or an error propagated from context plan preparation/execution.

◆ integrator_destroy()

void integrator_destroy ( Integrator integrator)

Release resources held by an integrator.

Calls the optional destroy hook, frees scratch buffers and drift snapshots, and zeroes the struct. Passing NULL is a no-op.

Parameters
integratorIntegrator to destroy; may be NULL.

◆ integrator_drift_scratch_bytes()

uint64_t integrator_drift_scratch_bytes ( const Integrator integrator)

Report reusable drift scratch bytes owned by the integrator.

Parameters
integratorIntegrator to inspect.
Returns
Drift scratch and snapshot footprint in bytes, or 0 for NULL.

◆ integrator_ensure_workspace()

SimResult integrator_ensure_workspace ( Integrator integrator,
size_t  buffers,
size_t  elements 
)

Ensure scratch buffers are available.

Buffers are aligned for SIMD-friendly field kernels and sized for either real doubles or SimComplexDouble entries depending on integrator->is_complex.

Parameters
integratorIntegrator instance.
buffersNumber of buffers required; must be greater than zero.
elementsNumber of real or complex entries per buffer.
Returns
SIM_RESULT_OK when the workspace is ready, SIM_RESULT_INVALID_ARGUMENT for invalid input, or SIM_RESULT_OUT_OF_MEMORY.

◆ integrator_last_error()

double integrator_last_error ( const Integrator integrator)

Retrieve the error norm reported by the last step.

Parameters
integratorIntegrator to inspect.
Returns
Last normalized error estimate, or 0 for NULL.

◆ integrator_last_step()

double integrator_last_step ( const Integrator integrator)

Retrieve the timestep used by the previous update.

Parameters
integratorIntegrator to inspect.
Returns
Last realized timestep, or 0 for NULL.

◆ integrator_measure_error()

double integrator_measure_error ( const double *  a,
const double *  b,
size_t  count 
)

Measure scaled infinity-norm error between two real state vectors.

Each component is normalized by max(abs(a[i]), abs(b[i]), 1).

Parameters
aFirst real state vector.
bSecond real state vector.
countNumber of double entries.
Returns
Maximum normalized component difference, or 0 for invalid/empty input.

◆ integrator_measure_error_complex()

double integrator_measure_error_complex ( const SimComplexDouble a,
const SimComplexDouble b,
size_t  n 
)

Measure scaled RMS error between two complex state vectors.

Component differences use squared complex magnitude and are normalized by max(|a[i]|^2, |b[i]|^2, 1) before the mean square root is taken.

Parameters
aFirst complex state vector.
bSecond complex state vector.
nNumber of complex entries.
Returns
Normalized RMS complex difference, or 0 for invalid/empty input.

◆ integrator_next_step()

double integrator_next_step ( const Integrator integrator)

Retrieve the suggested timestep for the next call.

Parameters
integratorIntegrator to inspect.
Returns
Current timestep suggestion, or 0 for NULL.

◆ integrator_noise_gaussian()

SimResult integrator_noise_gaussian ( struct Integrator integrator,
const Field field,
double *  out_noise,
size_t  count 
)

Fill a buffer with zero-mean, unit-variance Gaussian noise samples.

Parameters
integratorIntegrator containing RNG state.
fieldField associated with the samples; currently informational.
[out]out_noiseBuffer receiving count samples.
countNumber of samples to generate.
Returns
SIM_RESULT_OK, or SIM_RESULT_INVALID_ARGUMENT for NULL inputs.

◆ integrator_noise_laplace()

SimResult integrator_noise_laplace ( struct Integrator integrator,
const Field field,
double *  out_noise,
size_t  count 
)

Fill a buffer with zero-mean, unit-variance Laplace noise samples.

Parameters
integratorIntegrator containing RNG state.
fieldField associated with the samples; currently informational.
[out]out_noiseBuffer receiving count samples.
countNumber of samples to generate.
Returns
SIM_RESULT_OK, or SIM_RESULT_INVALID_ARGUMENT for NULL inputs.

◆ integrator_noise_uniform()

SimResult integrator_noise_uniform ( struct Integrator integrator,
const Field field,
double *  out_noise,
size_t  count 
)

Fill a buffer with zero-mean, unit-variance uniform noise samples.

Samples are drawn from [-sqrt(3), sqrt(3)].

Parameters
integratorIntegrator containing RNG state.
fieldField associated with the samples; currently informational.
[out]out_noiseBuffer receiving count samples.
countNumber of samples to generate.
Returns
SIM_RESULT_OK, or SIM_RESULT_INVALID_ARGUMENT for NULL inputs.

◆ integrator_reject_dt()

double integrator_reject_dt ( const Integrator integrator,
double  dt,
double  error_norm,
double  method_order 
)

Shrink a rejected timestep using the observed error when available.

Falls back to a conservative halving strategy if the controller would not reduce the step or the estimate is not finite.

Parameters
integratorIntegrator instance.
dtRejected timestep.
error_normDimensionless normalized error estimate.
method_orderOrder of the embedded error estimator.
Returns
Smaller timestep clamped to the configured timestep bounds.

◆ integrator_rng_normal()

double integrator_rng_normal ( Integrator integrator)

Generate a standard normal variate using the integrator RNG.

Parameters
integratorIntegrator containing RNG state.
Returns
One zero-mean, unit-variance Gaussian sample, or 0 for NULL input.

◆ integrator_state_length()

size_t integrator_state_length ( const Field field)

Compute the scalar length of a field.

Parameters
fieldField instance.
Returns
Number of real entries for real fields or complex entries for complex fields; returns 0 for NULL, empty, or unsupported element sizes.

◆ integrator_step_context()

SimResult integrator_step_context ( Integrator integrator,
struct SimContext context,
struct SimBackend backend,
double  dt 
)

Step a context-backed integrator without advancing context time.

This updates field state and integrator metadata only. Call sim_context_accept_step after a successful step if you want the context clock and step index to advance. The backend parameter is retained for API compatibility and is not used by the current implementation.

Parameters
integratorIntegrator to execute.
contextSimulation context containing the target field.
backendOptional backend pointer reserved for future dispatch.
dtRequested timestep passed to the integrator step function.
Returns
SIM_RESULT_OK, SIM_RESULT_INVALID_ARGUMENT, SIM_RESULT_NOT_FOUND, SIM_RESULT_OUT_OF_MEMORY in debug invariant tracking, or a plan preparation error from the context.

◆ integrator_suggest_dt()

double integrator_suggest_dt ( const Integrator integrator,
double  dt,
double  error_norm,
double  method_order 
)

Suggest a new timestep based on an error estimate.

The controller applies the configured tolerance, safety factor, and growth clamps. Non-adaptive integrators simply return the clamped current timestep.

Parameters
integratorIntegrator instance.
dtCurrent timestep.
error_normDimensionless normalized error estimate.
method_orderOrder of the embedded error estimator; values below 1 are treated as first order.
Returns
Suggested timestep for the next iteration, clamped to integrator bounds.

◆ integrator_workspace_bytes()

uint64_t integrator_workspace_bytes ( const Integrator integrator)

Report allocated workspace bytes owned by the integrator buffers.

Parameters
integratorIntegrator to inspect.
Returns
Buffer footprint in bytes, or 0 for NULL.