C API#

Include <skalaxc/skalaxc.h>. The C ABI uses opaque handles and plain data; no C++, GauXC, or LibTorch types cross it. A C-only consumer can use:

project(my_solver LANGUAGES C)
find_package(SkalaXC REQUIRED CONFIG COMPONENTS C)
add_executable(my_solver main.c)
target_link_libraries(my_solver PRIVATE SkalaXC::skalaxc)

If SkalaXC is installed outside a default prefix, add it to CMAKE_PREFIX_PATH or set SkalaXC_DIR. The *_from_hdf5 functions and the C tutorial: evaluate a density matrix example exist only when SkalaXC is built with HDF5 support.

The pipeline is runtime, molecule/basis, grid, load balancer, molecular weights, functional, and integrator. Check each status against SKALAXC_SUCCESS and report skalaxc_last_error_message() before cleanup. Initialize handles to NULL and destroy each owned handle exactly once, in reverse construction order. The C tutorial: evaluate a density matrix demonstrates cleanup on every failure path.

Atomic numbers, shell angular momentum and pure flags are checked when atoms and shells are added. Coordinates, exponents, coefficients and shell centers are checked when a later stage consumes them (for example skalaxc_molgrid_create_default or skalaxc_load_balancer_create), and the selected backend’s own angular momentum limit applies when the pipeline is built. Diagnostics snapshots must be prepared with skalaxc_diagnostics_snapshot_init, which records the struct size so the library and the caller may be built against different header versions. Status values and every enumeration-valued argument are fixed-width int32_t, so they do not depend on compiler options such as -fshort-enums. Likewise skalaxc_functional_create does not load the model; a missing or misspelled model name, which is case-sensitive, is reported by skalaxc_xc_integrator_create. Named models are looked up in SKALAXC_MODEL_PATH or, if unset, in the model directory recorded when the library was built, so set SKALAXC_MODEL_PATH if the installation is moved.

Evaluation accepts caller-owned double arrays in column-major order, with nbf * nbf elements per density or potential channel. Nuclear gradients need 3 * natoms elements in atom-major xyz order. Inputs are the scalar and z-spin density channels, not separate alpha/beta matrices. The supported calculation is UKS; RKS is not implemented.

MPI builds take the caller’s native communicator and require collective evaluation over that communicator. Keep it alive until dependent handles are destroyed, and destroy those handles before finalizing MPI. A NULL matrix or gradient pointer on any rank makes every rank return an error, but a NULL integrator handle or exc_out is rejected before the collective, so on only some ranks it leaves the others waiting.

Status and error reporting#

/**
 * @file
 * @brief SkalaXC C API: status codes and error reporting.
 *
 * Part of the public C API; include <skalaxc/skalaxc.h> to get the whole API.
 */
#pragma once

#include <stdint.h>

#include <skalaxc/skalaxc_export.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief Status returned by SkalaXC C API functions.
 *
 * A fixed-width integer rather than an enumeration, so its size does not depend
 * on compiler options such as -fshort-enums. Compare it with the values below.
 */
typedef int32_t skalaxc_status_t;

/** @brief Values of skalaxc_status_t. */
enum {
  SKALAXC_SUCCESS = 0,  ///< Success
  SKALAXC_ERROR = 1,    ///< Generic failure (see skalaxc_last_error_message)
  SKALAXC_INVALID_ARGUMENT =
      2  ///< A null pointer, invalid dimension, or invalid enum was passed
};

/**
 * @brief Thread-local message describing the most recent failure on the calling
 * thread.
 *
 * The returned pointer remains valid until the next failure on the same thread.
 * The message is not cleared by later successful calls, so read it only after
 * a call has reported a failure.
 * Long implementation or dependency messages may be truncated. The caller must
 * not modify or free the returned storage.
 * @return Null-terminated error string (empty if no error has occurred).
 */
const char* skalaxc_last_error_message(void) SKALAXC_EXPORT;

#ifdef __cplusplus
}  // extern "C"
#endif

Evaluation and diagnostics#

/**
 * @file
 * @brief SkalaXC C API: XC integrator handle.
 *
 * Mirrors SkalaXC::XCIntegrator / SkalaXC::XCIntegratorFactory (UKS subset).
 * Part of the public C API; include <skalaxc/skalaxc.h> to get the whole API.
 */
#pragma once

#include <stdint.h>

#include <skalaxc/c/diagnostics.h>
#include <skalaxc/c/enums.h>
#include <skalaxc/c/functional.h>
#include <skalaxc/c/load_balancer.h>
#include <skalaxc/c/status.h>
#include <skalaxc/skalaxc_export.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief Opaque XC-integrator handle (mirrors SkalaXC::XCIntegrator).
 *
 * One handle must not be used concurrently from multiple threads. Serialize
 * access to a shared handle or use a separate handle per calling thread.
 */
typedef struct skalaxc_xc_integrator* skalaxc_xc_integrator_t;

/** @brief XC-integrator construction settings. */
typedef struct skalaxc_integrator_settings {
  skalaxc_timing_settings_t timing; /**< Rank-local timing behavior. */
  int32_t domain_batch_mode; /**< SkalaXC_DomainBatchMode: complete-domain model
                                batching policy. */
} skalaxc_integrator_settings_t;

/**
 * @brief Fill XC-integrator settings with conservative defaults.
 * @param settings Output settings; NULL is tolerated.
 */
void skalaxc_integrator_settings_default(
    skalaxc_integrator_settings_t* settings) SKALAXC_EXPORT;

/**
 * @brief Create an XC integrator (mirrors
 * SkalaXC::XCIntegratorFactory::get_instance).
 *
 * The load balancer must carry partitioned weights (see
 * skalaxc_molecular_weights_modify_weights) before this call.
 * @param ex SkalaXC_ExecutionSpace; device requires a CUDA-enabled build and
 *          runtime.
 * @param func Functional handle selecting the Skala model.
 * @param lb Load-balancer handle with partitioned weights.
 * @param out Output owning handle on success (free with
 *            skalaxc_xc_integrator_destroy).
 * @return SKALAXC_SUCCESS on success, or an error status.
 */
skalaxc_status_t skalaxc_xc_integrator_create(
    int32_t ex, skalaxc_functional_t func,
    skalaxc_load_balancer_t lb, skalaxc_xc_integrator_t* out) SKALAXC_EXPORT;

/**
 * @brief Create an XC integrator with explicit timing behavior.
 *
 * This is the settings-bearing counterpart to skalaxc_xc_integrator_create.
 * Passing NULL for @p settings uses non-synchronizing timing defaults.
 * @param ex Execution space; device requires a CUDA-enabled build and runtime.
 * @param func Functional handle selecting the Skala model.
 * @param lb Load-balancer handle with partitioned weights.
 * @param settings Timing settings, or NULL for defaults.
 * @param out Output owning handle on success.
 * @return SKALAXC_SUCCESS on success, or an error status.
 */
skalaxc_status_t skalaxc_xc_integrator_create_with_timing(
    int32_t ex, skalaxc_functional_t func,
    skalaxc_load_balancer_t lb, const skalaxc_timing_settings_t* settings,
    skalaxc_xc_integrator_t* out) SKALAXC_EXPORT;

/**
 * @brief Create an XC integrator with timing and domain batching settings.
 * @param ex Execution space for complete-domain model batching.
 * @param func Functional handle selecting the Skala model.
 * @param lb Load-balancer handle with partitioned weights.
 * @param settings Integrator settings, or NULL for conservative defaults.
 * @param out Output owning handle on success.
 * @return SKALAXC_SUCCESS on success, or an error status.
 */
skalaxc_status_t skalaxc_xc_integrator_create_with_settings(
    int32_t ex, skalaxc_functional_t func,
    skalaxc_load_balancer_t lb, const skalaxc_integrator_settings_t* settings,
    skalaxc_xc_integrator_t* out) SKALAXC_EXPORT;

/**
 * @brief Return the number of basis functions, or -1 if xc is null.
 * @param xc XC-integrator handle.
 * @return Number of basis functions.
 */
int64_t skalaxc_xc_integrator_nbf(skalaxc_xc_integrator_t xc) SKALAXC_EXPORT;

/**
 * @brief Return the number of atoms, or -1 if xc is null.
 * @param xc XC-integrator handle.
 * @return Number of atoms.
 */
int64_t skalaxc_xc_integrator_natoms(skalaxc_xc_integrator_t xc) SKALAXC_EXPORT;

/**
 * @brief Evaluate the UKS ML exchange-correlation energy and potential.
 *
 * Ps/Pz are the input scalar/z spin-density matrices; VXCs/VXCz receive the
 * corresponding potentials. All are nbf x nbf, column-major, leading dim nbf.
 * Under MPI the call is collective. A NULL matrix pointer returns
 * SKALAXC_ERROR on every rank of the communicator. A NULL xc or exc_out is
 * rejected locally (SKALAXC_INVALID_ARGUMENT) before the collective, so if it
 * happens on only some ranks the remaining ranks wait indefinitely. Pass
 * valid values for those on all ranks.
 * @param xc XC-integrator handle.
 * @param Ps Scalar spin-density matrix.
 * @param Pz Z spin-density matrix.
 * @param VXCs Output scalar XC potential.
 * @param VXCz Output z XC potential.
 * @param exc_out Output exchange-correlation energy.
 * @return SKALAXC_SUCCESS on success, or an error status.
 */
skalaxc_status_t skalaxc_xc_integrator_eval_exc_vxc_uks(
    skalaxc_xc_integrator_t xc, const double* Ps, const double* Pz,
    double* VXCs, double* VXCz, double* exc_out) SKALAXC_EXPORT;

/**
 * @brief Evaluate the UKS ML exchange-correlation energy gradient.
 *
 * Ps/Pz are nbf x nbf column-major density matrices. The caller must provide
 * space for 3 * natoms doubles in gradient_out, ordered xyz per atom. Under
 * MPI the call is collective, and a NULL matrix or gradient pointer returns
 * SKALAXC_ERROR on every rank. A NULL xc is rejected locally
 * (SKALAXC_INVALID_ARGUMENT) before the collective, so if it happens on only
 * some ranks the remaining ranks wait indefinitely.
 * @param xc XC-integrator handle.
 * @param Ps Scalar spin-density matrix.
 * @param Pz Z spin-density matrix.
 * @param gradient_out Output atom-major Cartesian gradient.
 * @return SKALAXC_SUCCESS on success, or an error status.
 */
skalaxc_status_t skalaxc_xc_integrator_eval_exc_grad_uks(
    skalaxc_xc_integrator_t xc, const double* Ps, const double* Pz,
    double* gradient_out) SKALAXC_EXPORT;

/**
 * @brief Retrieve a rank-local diagnostics snapshot without MPI collectives.
 * @param xc XC-integrator handle.
 * @param out Output diagnostics snapshot, initialized with
 *            skalaxc_diagnostics_snapshot_init. A snapshot whose struct_size is
 *            not set is rejected with SKALAXC_INVALID_ARGUMENT.
 * @return SKALAXC_SUCCESS on success, or an error status.
 */
skalaxc_status_t skalaxc_xc_integrator_get_diagnostics(
    skalaxc_xc_integrator_t xc,
    skalaxc_diagnostics_snapshot_t* out) SKALAXC_EXPORT;

/**
 * @brief Clear evaluation timings and counters on this integrator.
 * @param xc XC-integrator handle.
 * @return SKALAXC_SUCCESS on success, or an error status.
 */
skalaxc_status_t skalaxc_xc_integrator_reset_diagnostics(
    skalaxc_xc_integrator_t xc) SKALAXC_EXPORT;

/**
 * @brief Destroy an XC-integrator handle (NULL is tolerated).
 * @param xc XC-integrator handle to destroy.
 */
void skalaxc_xc_integrator_destroy(skalaxc_xc_integrator_t xc) SKALAXC_EXPORT;

#ifdef __cplusplus
}  // extern "C"
#endif
/**
 * @file
 * @brief SkalaXC C API: lightweight rank-local diagnostics.
 */
#pragma once

#include <stdint.h>

#include <skalaxc/c/enums.h>
#include <skalaxc/c/status.h>
#include <skalaxc/skalaxc_export.h>

#ifdef __cplusplus
extern "C" {
#endif

/** @brief Number of entries in a diagnostics timing array. */
#define SKALAXC_TIMING_METRIC_COUNT 11

/** @brief Stable identifiers for XC-integrator timing phases. */
enum SkalaXC_TimingMetric {
  SkalaXC_TimingMetric_ModelLoad,            ///< TorchScript model loading
  SkalaXC_TimingMetric_FeatureConstruction,  ///< ML feature construction
  SkalaXC_TimingMetric_ModelBatchPacking,    ///< Complete-domain batch packing
  SkalaXC_TimingMetric_ModelForward,         ///< ML model forward evaluation
  SkalaXC_TimingMetric_ModelBackward,        ///< ML model backward evaluation
  SkalaXC_TimingMetric_PotentialMapping,     ///< Potential mapping to grid data
  SkalaXC_TimingMetric_AOAssembly,           ///< AO matrix assembly
  SkalaXC_TimingMetric_GradientAssembly,     ///< Nuclear-gradient assembly
  SkalaXC_TimingMetric_MPIReduction,         ///< MPI result reduction
  SkalaXC_TimingMetric_TotalEXCVXC,          ///< Complete EXC/VXC evaluation
  SkalaXC_TimingMetric_TotalEXCGradient      ///< Complete gradient evaluation
};

/** @brief Availability of a timing value in a diagnostics snapshot. */
enum SkalaXC_TimingStatus {
  SkalaXC_TimingStatus_Unavailable,  ///< Timing is unavailable for this backend
  SkalaXC_TimingStatus_Pending,  ///< Asynchronous timing is not yet complete
  SkalaXC_TimingStatus_Complete  ///< Timing contains a complete value
};

/** @brief Rank-local timing and debug-logging configuration. */
typedef struct skalaxc_timing_settings {
  int32_t verbose;       /**< Nonzero requests complete CUDA timings on read. */
  int32_t debug_logging; /**< Nonzero emits rank-local diagnostics to stderr. */
} skalaxc_timing_settings_t;

/** @brief Last and cumulative values for one timing phase. */
typedef struct skalaxc_timing_value {
  int64_t last_nanoseconds;   ///< Most recent completed duration
  int64_t total_nanoseconds;  ///< Sum of all completed durations
  int64_t call_count;         ///< Number of recorded phase invocations
  int32_t status;             ///< One of enum SkalaXC_TimingStatus
} skalaxc_timing_value_t;

/**
 * @brief Rank-local, non-collective snapshot of integrator diagnostics.
 *
 * New members are only ever appended. The caller states the size of the struct
 * it was compiled with in @c struct_size (use
 * skalaxc_diagnostics_snapshot_init), and the library fills only the members
 * that fit in it, so programs built against an older or newer header keep
 * working with a different library version. After a successful call,
 * @c struct_size is the number of bytes that were filled.
 */
typedef struct skalaxc_diagnostics_snapshot {
  int32_t struct_size;           /**< Size of this struct, in bytes. */
  int32_t backend;               /**< Host or device execution space. */
  int32_t rank;                  /**< Rank in the runtime communicator. */
  int32_t communicator_size;     /**< Size of the runtime communicator. */
  int32_t device_id;             /**< CUDA ordinal, or -1 for host execution. */
  int32_t openmp_threads;        /**< Maximum OpenMP threads at construction. */
  double device_memory_fraction; /**< GauXC CUDA arena fraction, or zero. */
  int32_t domain_batch_mode;     /**< Configured SkalaXC_DomainBatchMode. */
  skalaxc_timing_value_t timings[SKALAXC_TIMING_METRIC_COUNT];
  /**< Timing values indexed by enum SkalaXC_TimingMetric. */
  int64_t exc_vxc_calls;            ///< Number of EXC/VXC evaluations
  int64_t exc_gradient_calls;       ///< Number of gradient evaluations
  int64_t model_batches;            ///< Model batches evaluated since reset
  int64_t domains;                  ///< Atomic domains evaluated since reset
  int64_t tasks;                    ///< Local quadrature tasks processed
  int64_t points;                   ///< Local quadrature points processed
  int64_t local_atoms;              ///< Atomic domains owned by this rank
  int64_t configured_model_batches; /**< Model batches planned at construction.
                                     */
  int64_t task_points_min;          ///< Minimum points in a processed task
  int64_t task_points_max;          ///< Maximum points in a processed task
  int64_t task_basis_min;           ///< Minimum basis functions in a task
  int64_t task_basis_max;           ///< Maximum basis functions in a task
  int64_t model_batch_points_min;   ///< Minimum points in a model batch
  int64_t model_batch_points_max;   ///< Maximum points in a model batch
  int64_t max_domains_per_model_batch; /**< Maximum domains per model batch. */
} skalaxc_diagnostics_snapshot_t;

/**
 * @brief Initialize timing settings with synchronization and logging disabled.
 * @param settings Output settings; NULL is tolerated.
 */
void skalaxc_timing_settings_default(skalaxc_timing_settings_t* settings)
    SKALAXC_EXPORT;

/**
 * @brief Prepare a snapshot for skalaxc_xc_integrator_get_diagnostics.
 *
 * Zeroes the struct and sets its @c struct_size. No-op if snapshot is NULL.
 * @param snapshot Snapshot to initialize.
 */
void skalaxc_diagnostics_snapshot_init(
    skalaxc_diagnostics_snapshot_t* snapshot) SKALAXC_EXPORT;

#ifdef __cplusplus
}  // extern "C"
#endif

The umbrella header lists the remaining construction and configuration APIs:

/**
 * @file
 * @brief SkalaXC public C API umbrella header.
 *
 * ABI isolation contract: this API exposes only opaque handles and C POD types.
 * No GauXC or LibTorch type crosses this boundary. Densities and potentials are
 * passed as raw double arrays (column-major, nbf x nbf).
 * No C++ exception crosses this API. Failures are reported through status
 * codes, documented sentinel return values, and skalaxc_last_error_message().
 *
 * The C API mirrors the SkalaXC C++ pipeline
 * (runtime environment -> molecule / basis set -> molecular grid ->
 * load balancer -> molecular weights -> functional -> XC integrator) with one
 * opaque handle per stage. The API is organized into the skalaxc/c/ headers;
 * this umbrella includes them all. Consumers may include the individual headers
 * instead if preferred.
 */
#pragma once

#include <skalaxc/c/basisset.h>
#include <skalaxc/c/diagnostics.h>
#include <skalaxc/c/enums.h>
#include <skalaxc/c/functional.h>
#include <skalaxc/c/grid.h>
#include <skalaxc/c/integrator.h>
#include <skalaxc/c/load_balancer.h>
#include <skalaxc/c/molecular_weights.h>
#include <skalaxc/c/molecule.h>
#include <skalaxc/c/molgrid.h>
#include <skalaxc/c/runtime.h>
#include <skalaxc/c/status.h>
#include <skalaxc/c/version.h>