apoCHARMM 1.0.0
High-performance molecular dynamics simulations on GPUs
 
Loading...
Searching...
No Matches
CharmmContext Class Reference

Represents mutable molecular state used by apoCHARMM force calculations. More...

#include <CharmmContext.h>

Inherits std::enable_shared_from_this< CharmmContext >.

Public Member Functions

 CharmmContext (void)
 Constructs an incomplete context without molecular collaborators.
 
 CharmmContext (std::shared_ptr< CharmmPSF > psf, std::shared_ptr< CharmmParameters > prm)
 Constructs a context from a PSF and CHARMM parameters.
 
 CharmmContext (std::shared_ptr< ForceManager > fm)
 Constructs a context from an existing ForceManager.
 
 ~CharmmContext (void) noexcept=default
 Destroys context-owned storage and releases shared collaborators.
 
 CharmmContext (const CharmmContext &other)
 Constructs a context from another context's stored state.
 
void setPrm (std::shared_ptr< CharmmParameters > prm)
 Sets the CHARMM parameter set used by the context.
 
void setPsf (std::shared_ptr< CharmmPSF > psf)
 Sets the molecular PSF and imports its atom data.
 
void setForceManager (std::shared_ptr< ForceManager > fm)
 Sets the ForceManager associated with the context.
 
void setNumAtoms (const int numAtoms)
 Sets the atom count and sizes per-atom state storage.
 
void setCoordinatesCharges (const std::vector< double4 > &coordinatesCharges)
 Sets coordinates and charges from double4 records.
 
void setCoordinatesCharges (const std::vector< std::vector< double > > &coordinatesCharges)
 Sets coordinates and charges from nested scalar rows.
 
void setCoordinatesCharges (const std::vector< double > &coordinatesCharges)
 Sets coordinates and charges from a flat scalar array.
 
void setCoordinates (const std::vector< double3 > &coordinates)
 Sets Cartesian coordinates while preserving stored charges.
 
void setCoordinates (const std::vector< std::vector< double > > &coordinates)
 Sets Cartesian coordinates from nested scalar rows.
 
void setCoordinates (const std::vector< double > &coordinates)
 Sets Cartesian coordinates from a flat scalar array.
 
void setCoordinates (const std::shared_ptr< Coordinates > crd)
 Sets coordinates from a Coordinates object.
 
void setCharges (const std::vector< double > &charges)
 Sets per-atom charges while preserving coordinates.
 
void setVelocitiesInverseMasses (const std::vector< double4 > &velocitiesInverseMasses)
 Sets velocities and inverse masses from double4 records.
 
void setVelocitiesInverseMasses (const std::vector< std::vector< double > > &velocitiesInverseMasses)
 Sets velocities and inverse masses from nested scalar rows.
 
void setVelocitiesInverseMasses (const std::vector< double > &velocitiesInverseMasses)
 Sets velocities and inverse masses from a flat scalar array.
 
void setVelocities (const std::vector< double3 > &velocities)
 Sets velocity components while preserving inverse masses.
 
void setVelocities (const std::vector< std::vector< double > > &velocities)
 Sets velocities from nested scalar rows.
 
void setVelocities (const std::vector< double > &velocities)
 Sets velocities from a flat scalar array.
 
void setVelocitiesFromCHARMMVelocityFile (const std::string &fileName)
 Loads velocities from a CHARMM coordinate-format velocity file.
 
void setMasses (const std::vector< double > &masses)
 Sets masses and stores their reciprocals with the velocities.
 
void setTemperature (const double temperature)
 Sets the stored target temperature.
 
void setPeriodicBoundaryCondition (const PBC pbc)
 Sets the periodic boundary condition.
 
void setBoxDimensions (const std::vector< double > &boxDimensions)
 Sets the orthorhombic box dimensions.
 
void setRandomSeed (const std::uint64_t randomSeed)
 Sets the deterministic random seed used for velocity generation.
 
void useHolonomicConstraints (const bool usingHolonomicConstraints)
 Selects holonomic-constraint degree-of-freedom accounting.
 
void setKappa (const float kappa)
 Sets the Ewald splitting parameter.
 
void setCutoff (const float cutoff)
 Sets the direct-space neighbor-list cutoff.
 
void setCtonnb (const float ctonnb)
 Sets the nonbonded distance exposed as ctonnb.
 
void setCtofnb (const float ctofnb)
 Sets the nonbonded distance exposed as ctofnb.
 
void setFFTGrid (const int nfftx, const int nffty, const int nfftz)
 Sets the three-dimensional PME FFT grid.
 
void setPmeSplineOrder (const int pmeSplineOrder)
 Sets the PME interpolation spline order.
 
void setVdwType (const int vdwType)
 Sets the van der Waals model identifier.
 
int getNumAtoms (void) const
 Returns the configured atom count.
 
int getNumDegreesOfFreedom (void) const
 Returns the current number of degrees of freedom.
 
const CudaContainer< float4 > & getCoordinatesChargesSP (void) const
 Returns the single-precision coordinate/charge container.
 
const CudaContainer< double4 > & getCoordinatesChargesDP (void) const
 Returns the double-precision coordinate/charge container.
 
const CudaContainer< double4 > & getVelocitiesInverseMasses (void) const
 Returns the velocity/inverse-mass container.
 
double getTemperature (void) const
 Returns the stored target temperature.
 
PBC getPeriodicBoundaryCondition (void) const
 Returns the stored periodic boundary condition.
 
const std::vector< double > & getBoxDimensions (void) const
 Returns the stored box dimensions.
 
std::uint64_t getRandomSeed (void) const
 Returns the random seed used for generated velocities.
 
bool usingHolonomicConstraints (void) const
 Reports whether holonomic constraints are included in DOF accounting.
 
double getVolume (void) const
 Returns the orthorhombic box volume.
 
const CudaContainer< double > & getPressure (void) const
 Returns the context-owned pressure storage.
 
const std::vector< Bond > & getBonds (void) const
 Returns the PSF bond records.
 
const CudaContainer< int4 > & getWaterMolecules (void) const
 Returns the PSF water-molecule index records.
 
const CudaContainer< int4 > & getShakeAtoms (void) const
 Returns the initialized SHAKE atom records.
 
const CudaContainer< float4 > & getShakeParams (void) const
 Returns the initialized SHAKE parameter records.
 
float getKappa (void) const
 Returns the stored Ewald splitting parameter.
 
float getCutoff (void) const
 Returns the stored direct-space cutoff.
 
float getCtonnb (void) const
 Returns the distance exposed as ctonnb.
 
float getCtofnb (void) const
 Returns the distance exposed as ctofnb.
 
std::vector< int > getFFTGrid (void) const
 Returns the stored PME FFT grid.
 
int getPmeSplineOrder (void) const
 Returns the stored PME interpolation spline order.
 
int getVdwType (void) const
 Returns the stored van der Waals model identifier.
 
int getForceStride (void) const
 Returns the component stride of the total-force storage.
 
CudaContainer< float4 > & getCoordinatesChargesSP (void)
 Returns mutable single-precision coordinate/charge storage.
 
CudaContainer< double4 > & getCoordinatesChargesDP (void)
 Returns mutable double-precision coordinate/charge storage.
 
CudaContainer< double4 > & getVelocitiesInverseMasses (void)
 Returns mutable velocity/inverse-mass storage.
 
std::vector< double > & getBoxDimensions (void)
 Returns mutable box-dimension storage.
 
double getKineticEnergy (void)
 Computes and returns the current kinetic energy.
 
CudaContainer< double > & getPressure (void)
 Returns mutable pressure storage.
 
std::shared_ptr< CharmmPSFgetPsf (void)
 Returns the attached CharmmPSF.
 
std::shared_ptr< CharmmParametersgetPrm (void)
 Returns the attached CharmmParameters.
 
std::shared_ptr< ForceManagergetForceManager (void)
 Returns the attached ForceManager.
 
CudaContainer< double > & getPotentialEnergy (void)
 Returns the total potential-energy container.
 
float getPotentialEnergies (void)
 Returns the legacy host-summed potential-energy value.
 
std::shared_ptr< Force< double > > getForces (void)
 Returns the total force storage.
 
CudaContainer< double > & getVirial (void)
 Aggregates and returns the total virial storage.
 
std::vector< Bond > & getBonds (void)
 Returns mutable PSF bond records.
 
CudaContainer< int4 > & getWaterMolecules (void)
 Returns mutable PSF water-molecule records.
 
CudaContainer< int4 > & getShakeAtoms (void)
 Returns mutable SHAKE atom records.
 
CudaContainer< float4 > & getShakeParams (void)
 Returns mutable SHAKE parameter records.
 
void assignVelocitiesAtTemperature (const double temperature)
 Assigns Maxwell-Boltzmann velocity components at a temperature.
 
double computeTemperature (void)
 Computes the instantaneous kinetic temperature.
 
void computePressure (void)
 Reports that pressure computation is not implemented.
 
void imageCentering (void)
 Images complete PSF groups into the central periodic box.
 
void resetNeighborList (void)
 Images coordinates and rebuilds the direct-space neighbor list.
 
void calculateKineticEnergy (void)
 Computes kinetic energy into the context-owned device scalar.
 
void calculatePotentialEnergy (const bool reset=false, const bool print=false)
 Computes forces, potential energy, and virial.
 
void calculateForces (const bool reset=false, const bool calcEnergy=false, const bool calcVirial=false)
 Computes forces with selectable energy and virial accumulation.
 
void linkBackForceManager (void)
 Stores a weak context backlink in the attached ForceManager.
 

Protected Member Functions

void printEnergyTable (void)
 Formats and prints the current CHARMM-style energy table.
 
void syncStateFromForceManager (void)
 Imports collaborator state from the attached ForceManager.
 
void syncForceManagerFromState (void)
 Reconciles context state with the attached ForceManager.
 
bool hasCompleteForceManagerState (void) const
 Reports whether force-manager initialization prerequisites exist.
 
void initializeForceManagerIfReady (void)
 Initializes the force manager when all required state is available.
 
void requirePsf (void) const
 Requires an attached PSF.
 
void requireForceManager (void) const
 Requires an attached ForceManager.
 
void requireInitializedForceManager (void) const
 Requires an attached and initialized ForceManager.
 
void finalizeSetupIfReady (void)
 Advances the context/force-manager setup state when possible.
 

Protected Attributes

std::uint64_t m_RandomSeed
 
std::shared_ptr< CharmmPSFm_Psf
 
std::shared_ptr< CharmmParametersm_Prm
 
std::vector< double > m_BoxDimensions
 
bool m_HasBoxDimensions
 
std::shared_ptr< ForceManagerm_ForceManager
 
int m_NumAtoms
 
int m_NumDegreesOfFreedom
 
PBC m_Pbc
 
bool m_HasPbc
 
CudaContainer< float4 > m_CoordinatesChargesSP
 
CudaContainer< double4 > m_CoordinatesChargesDP
 
bool m_HasCoordinates
 
CudaContainer< double4 > m_VelocitiesInverseMasses
 
CudaContainer< double > m_KineticEnergyPartialSums
 
CudaContainer< double > m_KineticEnergy
 
CudaContainer< double > m_Pressure
 
CudaContainer< double > m_VirialKineticEnergyTensor
 
std::uint64_t m_EnergyTableEvaluationCount
 
double m_PreviousPrintedPotentialEnergy
 
bool m_HasPreviousPrintedPotentialEnergy
 
double m_Temperature
 
bool m_UsingHolonomicConstraints
 

Detailed Description

Represents mutable molecular state used by apoCHARMM force calculations.

A context stores coordinates, charges, velocities, inverse masses, thermodynamic bookkeeping, periodic-box state, and force-evaluation output. It shares ownership of an attached CharmmPSF, CharmmParameters, and ForceManager.

Coordinates and charges are maintained as both single-precision and double-precision CudaContainer mirrors. Velocities and inverse masses are maintained in a double-precision double4 container. Host and device storage are coherent only after the explicit transfers performed by the documented mutators or by a caller using the mutable container accessors.

The force manager stores only a weak backlink to the context. Construct a context through std::make_shared<CharmmContext> when the backlink is required.

The class performs no internal locking. Concurrent access requires external synchronization whenever any participating operation can mutate the context, an attached collaborator, a returned container, or device storage.

Copy construction deep-copies the context-owned containers and shares the PSF and parameter objects, but does not copy the force-manager association. Copy assignment remains compiler-generated and therefore performs memberwise assignment, including the force-manager member. No implicit move operations are generated because a copy constructor is explicitly declared.

Warning
Operations that update host state and then perform CUDA work are not transactional. A CUDA or backend failure can leave already-applied host-side changes observable.
See also
charmm_context

Constructor & Destructor Documentation

◆ CharmmContext() [1/4]

CharmmContext::CharmmContext ( void  )

Constructs an incomplete context without molecular collaborators.

The atom count and degree-of-freedom count are initialized to -1, the box is unset, the stored random seed is zero, and coordinate, charge, velocity, and inverse-mass storage is empty. Scalar energy and tensor bookkeeping containers are allocated with their implementation-defined initial sizes.

Postcondition
The context cannot perform force calculations until a PSF, parameters, force manager, valid box, and coordinates have been supplied.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if allocation of context-owned CUDA storage fails.

◆ CharmmContext() [2/4]

CharmmContext::CharmmContext ( std::shared_ptr< CharmmPSF psf,
std::shared_ptr< CharmmParameters prm 
)

Constructs a context from a PSF and CHARMM parameters.

The context retains shared ownership of both arguments, creates and retains a new ForceManager, copies atom charges and masses from the PSF, enables holonomic-constraint degree-of-freedom accounting, and selects a seed with std::random_device. The force manager remains uninitialized until a valid three-dimensional box is also available.

Parameters
[in]psfShared PSF owner. The pointer must be non-null and is retained by the context.
[in]prmShared parameter-set owner. The pointer must be non-null and is retained by the context.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if either pointer is null or imported state violates a native validation rule.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if GPU runtime setup, storage allocation, or a required transfer fails.
ApoCharmmErrorWith code ApoCharmmErrorCode::Runtime if native topology or parameter preparation fails.

◆ CharmmContext() [3/4]

CharmmContext::CharmmContext ( std::shared_ptr< ForceManager fm)

Constructs a context from an existing ForceManager.

The context retains shared ownership of fm and imports any PSF, parameters, periodic-boundary condition, and box already stored by the manager. When the imported state is complete and the manager is not already initialized, construction initializes the manager and computes the constrained degree-of-freedom count.

An incomplete force manager is accepted. Operations requiring initialized force storage continue to report a not-initialized error until the missing state is supplied.

Parameters
[in]fmShared force-manager owner. The pointer must be non-null and is retained by the context.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if fm is null or imported configuration is invalid.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if GPU setup or force-manager initialization encounters a CUDA failure.
ApoCharmmErrorWith code ApoCharmmErrorCode::Runtime if native force-manager initialization fails for another verified runtime condition.

◆ ~CharmmContext()

CharmmContext::~CharmmContext ( void  )
defaultnoexcept

Destroys context-owned storage and releases shared collaborators.

Destruction is non-throwing. Cleanup failures from nested CUDA-owning objects are not propagated from this destructor.

◆ CharmmContext() [4/4]

CharmmContext::CharmmContext ( const CharmmContext other)

Constructs a context from another context's stored state.

Context-owned coordinate, velocity, inverse-mass, energy, and pressure containers are deep-copied. PSF and parameter objects remain shared. Energy table history is reset.

The force-manager association is not copied, so the result cannot evaluate forces until a force manager is attached separately. The kinetic-energy partial-sum workspace and kinetic-virial tensor member are default-constructed rather than copied by the current implementation.

Parameters
[in]otherContext whose current state is copied. The source remains unchanged.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if copying a context-owned CUDA container fails.

Member Function Documentation

◆ assignVelocitiesAtTemperature()

void CharmmContext::assignVelocitiesAtTemperature ( const double  temperature)

Assigns Maxwell-Boltzmann velocity components at a temperature.

A new std::mt19937 is initialized from the stored random seed on every call. For atom i, each Cartesian component is drawn independently from a zero-mean normal distribution with standard deviation sqrt(k_B * temperature * inverse_mass[i]). The resulting velocities are transferred to device storage.

The operation does not remove center-of-mass motion or rescale the sampled kinetic temperature.

Parameters
[in]temperatureSampling temperature in kelvin. The value must be finite and non-negative.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if temperature is NaN, infinite, or negative.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if the host-to-device transfer fails.
Postcondition
The stored target temperature equals temperature.

◆ calculateForces()

void CharmmContext::calculateForces ( const bool  reset = false,
const bool  calcEnergy = false,
const bool  calcVirial = false 
)

Computes forces with selectable energy and virial accumulation.

Parameters
[in]resetRequests the force-manager reset mode. The current ForceManager implementation rejects true as not implemented.
[in]calcEnergytrue to calculate energy components.
[in]calcVirialtrue to calculate virial components.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotImplemented if reset is true.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if force, energy, virial, or stream work fails.

◆ calculateKineticEnergy()

void CharmmContext::calculateKineticEnergy ( void  )

Computes kinetic energy into the context-owned device scalar.

The implementation uses a fixed deterministic reduction hierarchy. The first pass calculates one block-indexed partial sum for each contiguous atom range. When multiple partial sums exist, a single-block second pass reduces them in a fixed index order and directly overwrites the result scalar. A one-block input writes the result directly and skips the second kernel.

No floating-point atomic accumulation is used. The method synchronizes the current CUDA device before returning.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if atom and velocity/inverse-mass storage are inconsistent.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if partial-sum storage allocation, kernel launch, or synchronization fails.
Note
Run-to-run arithmetic order is fixed for a given executable and launch configuration. Changing the block size, items per thread, compiler options, or CUDA target can change floating-point rounding.

◆ calculatePotentialEnergy()

void CharmmContext::calculatePotentialEnergy ( const bool  reset = false,
const bool  print = false 
)

Computes forces, potential energy, and virial.

The call delegates to ForceManager::calcForce() with energy and virial calculation enabled. When print is true, it subsequently prints a CHARMM-style energy table to std::cout and updates the table's evaluation and delta-energy history.

Parameters
[in]resetRequests the force-manager reset mode. The current ForceManager implementation rejects true as not implemented.
[in]printtrue to print the CHARMM-style energy table; otherwise false.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotImplemented if reset is true or energy-table printing is requested for a composite force manager.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if force, energy, virial, transfer, or synchronization work fails.
std::out_of_rangeIf a required named energy component is absent while formatting the printed energy table.

◆ computePressure()

void CharmmContext::computePressure ( void  )

Reports that pressure computation is not implemented.

Exceptions
ApoCharmmErrorAlways, with code ApoCharmmErrorCode::NotImplemented.

◆ computeTemperature()

double CharmmContext::computeTemperature ( void  )

Computes the instantaneous kinetic temperature.

The method computes kinetic energy on the GPU and evaluates K / (0.5 * ndegf * k_B).

Returns
Instantaneous temperature in kelvin.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if atom and velocity storage are inconsistent or the degree-of-freedom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if kinetic energy calculation, synchronization, or transfer fails.

◆ finalizeSetupIfReady()

void CharmmContext::finalizeSetupIfReady ( void  )
protected

Advances the context/force-manager setup state when possible.

The helper establishes the weak backlink, initializes a complete manager, recomputes the degree-of-freedom count for initialized state, and rebuilds the neighbor list when initialization occurred after coordinates were supplied.

◆ getBonds() [1/2]

std::vector< Bond > & CharmmContext::getBonds ( void  )

Returns mutable PSF bond records.

Returns
Borrowed mutable alias to the attached PSF's bond vector.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no PSF is attached.
Warning
Structural mutation can invalidate references and can make the initialized force manager inconsistent with its topology.

◆ getBonds() [2/2]

const std::vector< Bond > & CharmmContext::getBonds ( void  ) const

Returns the PSF bond records.

Returns
Borrowed const alias to the attached PSF's bond vector. The reference is valid while the retained PSF remains alive and is not structurally modified.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no PSF is attached.

◆ getBoxDimensions() [1/2]

std::vector< double > & CharmmContext::getBoxDimensions ( void  )

Returns mutable box-dimension storage.

Returns
Borrowed mutable alias to the context-owned X, Y, Z vector in angstroms.
Warning
Mutations through this alias bypass validation, do not update the internal box-present flag, are not forwarded to the force manager, and do not rebuild the neighbor list.

◆ getBoxDimensions() [2/2]

const std::vector< double > & CharmmContext::getBoxDimensions ( void  ) const

Returns the stored box dimensions.

Returns
Borrowed const alias to the context-owned X, Y, Z vector in angstroms. Before valid dimensions are set, the vector contains the constructor sentinel values.

◆ getCoordinatesChargesDP() [1/2]

CudaContainer< double4 > & CharmmContext::getCoordinatesChargesDP ( void  )

Returns mutable double-precision coordinate/charge storage.

Returns
Borrowed mutable alias to the context-owned double4 container.
Warning
Mutations through this alias bypass coordinate-presence tracking, single-precision mirror updates, host/device transfer, image centering, and neighbor-list rebuilding.

◆ getCoordinatesChargesDP() [2/2]

const CudaContainer< double4 > & CharmmContext::getCoordinatesChargesDP ( void  ) const

Returns the double-precision coordinate/charge container.

Each double4 is [x, y, z, charge] in atom order. Coordinates use angstroms and charges use elementary-charge units.

Returns
Borrowed const alias to context-owned storage. No transfer or CUDA synchronization is performed. The reference remains valid until context destruction, but element addresses can be invalidated by resizing.

◆ getCoordinatesChargesSP() [1/2]

CudaContainer< float4 > & CharmmContext::getCoordinatesChargesSP ( void  )

Returns mutable single-precision coordinate/charge storage.

Returns
Borrowed mutable alias to the context-owned float4 container.
Warning
Mutations through this alias bypass coordinate-presence tracking, double-precision mirror updates, host/device transfer, image centering, and neighbor-list rebuilding.

◆ getCoordinatesChargesSP() [2/2]

const CudaContainer< float4 > & CharmmContext::getCoordinatesChargesSP ( void  ) const

Returns the single-precision coordinate/charge container.

Each float4 is [x, y, z, charge] in atom order. Coordinates use angstroms and charges use elementary-charge units.

Returns
Borrowed const alias to context-owned storage. No transfer or CUDA synchronization is performed. The reference remains valid until context destruction, but element addresses can be invalidated by resizing.

◆ getCtofnb()

float CharmmContext::getCtofnb ( void  ) const

Returns the distance exposed as ctofnb.

Returns
Stored ctofnb value in angstroms.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ getCtonnb()

float CharmmContext::getCtonnb ( void  ) const

Returns the distance exposed as ctonnb.

Returns
Stored ctonnb value in angstroms.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ getCutoff()

float CharmmContext::getCutoff ( void  ) const

Returns the stored direct-space cutoff.

Returns
Cutoff distance in angstroms.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ getFFTGrid()

std::vector< int > CharmmContext::getFFTGrid ( void  ) const

Returns the stored PME FFT grid.

Returns
New three-element vector in X, Y, Z order. Values are dimensionless grid-point counts and can be non-positive before automatic or explicit grid selection.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ getForceManager()

std::shared_ptr< ForceManager > CharmmContext::getForceManager ( void  )

Returns the attached ForceManager.

Returns
A copied shared owner of the manager, or an empty pointer when no manager is attached. The returned manager can outlive the context; its backlink to the context is weak.

◆ getForces()

std::shared_ptr< Force< double > > CharmmContext::getForces ( void  )

Returns the total force storage.

The force manager synchronizes its aggregation stream before returning.

Returns
A copied shared owner of the initialized total Force<double> object. Force values use kilocalories per mole per angstrom and follow the force object's X/Y/Z stride layout.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if stream synchronization fails.

◆ getForceStride()

int CharmmContext::getForceStride ( void  ) const

Returns the component stride of the total-force storage.

Returns
Number of scalar elements between the X, Y, and Z component segments in the force manager's structure-of-arrays representation.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.

◆ getKappa()

float CharmmContext::getKappa ( void  ) const

Returns the stored Ewald splitting parameter.

Returns
Kappa in inverse angstroms.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ getKineticEnergy()

double CharmmContext::getKineticEnergy ( void  )

Computes and returns the current kinetic energy.

The calculation performs a deterministic CUDA reduction over velocity and inverse-mass storage, synchronizes the current CUDA device, and transfers the resulting scalar to host memory.

Returns
Kinetic energy in kilocalories per mole.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count or velocity/inverse-mass storage is not initialized consistently.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if workspace allocation, kernel launch, synchronization, or result transfer fails.

◆ getNumAtoms()

int CharmmContext::getNumAtoms ( void  ) const

Returns the configured atom count.

Returns
Positive atom count after initialization, or -1 in a default-constructed context before setNumAtoms() or setPsf().

◆ getNumDegreesOfFreedom()

int CharmmContext::getNumDegreesOfFreedom ( void  ) const

Returns the current number of degrees of freedom.

Returns
Dimensionless degree-of-freedom count, or -1 before it has been computed.

◆ getPeriodicBoundaryCondition()

PBC CharmmContext::getPeriodicBoundaryCondition ( void  ) const

Returns the stored periodic boundary condition.

Returns
Current PBC value. A default-constructed context stores PBC::P1 even before periodic-boundary state has been explicitly marked present.

◆ getPmeSplineOrder()

int CharmmContext::getPmeSplineOrder ( void  ) const

Returns the stored PME interpolation spline order.

Returns
Positive dimensionless spline order for a configured manager.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ getPotentialEnergies()

float CharmmContext::getPotentialEnergies ( void  )

Returns the legacy host-summed potential-energy value.

The current implementation copies selected standard bonded, direct-space, and reciprocal energy components to host memory and sums them.

Returns
Selected potential-energy sum in kilocalories per mole.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if component transfer or stream synchronization fails.
Warning
The current sum omits CMAP and subscribed-force energy contributions.

◆ getPotentialEnergy()

CudaContainer< double > & CharmmContext::getPotentialEnergy ( void  )

Returns the total potential-energy container.

Returns
Borrowed mutable alias to the initialized force manager's single-element potential-energy container in kilocalories per mole. No host transfer is performed by this accessor.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.

◆ getPressure() [1/2]

CudaContainer< double > & CharmmContext::getPressure ( void  )

Returns mutable pressure storage.

Returns
Borrowed mutable alias to the context-owned nine-element pressure container.
Warning
computePressure() is not implemented. Mutations through this alias have no validation or defined integration with force calculations.

◆ getPressure() [2/2]

const CudaContainer< double > & CharmmContext::getPressure ( void  ) const

Returns the context-owned pressure storage.

Returns
Borrowed const alias to the nine-element pressure container. No transfer or synchronization is performed.
Warning
computePressure() is not implemented, so the current subsystem does not provide a supported operation that populates this container.

◆ getPrm()

std::shared_ptr< CharmmParameters > CharmmContext::getPrm ( void  )

Returns the attached CharmmParameters.

Returns
A copied shared owner of the parameter set, or an empty pointer when no parameters are attached. The returned owner keeps the native object alive independently of the context.

◆ getPsf()

std::shared_ptr< CharmmPSF > CharmmContext::getPsf ( void  )

Returns the attached CharmmPSF.

Returns
A copied shared owner of the PSF, or an empty pointer when no PSF is attached. The returned owner keeps the native PSF alive independently of the context.

◆ getRandomSeed()

std::uint64_t CharmmContext::getRandomSeed ( void  ) const

Returns the random seed used for generated velocities.

Returns
Unsigned 64-bit dimensionless seed.

◆ getShakeAtoms() [1/2]

CudaContainer< int4 > & CharmmContext::getShakeAtoms ( void  )

Returns mutable SHAKE atom records.

Returns
Borrowed mutable alias to the initialized force manager's int4 SHAKE atom container.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.
Warning
Mutations bypass constraint validation and degree-of-freedom recomputation.

◆ getShakeAtoms() [2/2]

const CudaContainer< int4 > & CharmmContext::getShakeAtoms ( void  ) const

Returns the initialized SHAKE atom records.

Returns
Borrowed const alias to the force manager's int4 SHAKE atom container. No transfer or synchronization is performed.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.

◆ getShakeParams() [1/2]

CudaContainer< float4 > & CharmmContext::getShakeParams ( void  )

Returns mutable SHAKE parameter records.

Returns
Borrowed mutable alias to the initialized force manager's float4 SHAKE parameter container.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.
Warning
Mutations bypass constraint validation and host/device coherence management.

◆ getShakeParams() [2/2]

const CudaContainer< float4 > & CharmmContext::getShakeParams ( void  ) const

Returns the initialized SHAKE parameter records.

Returns
Borrowed const alias to the force manager's float4 SHAKE parameter container. No transfer or synchronization is performed.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.

◆ getTemperature()

double CharmmContext::getTemperature ( void  ) const

Returns the stored target temperature.

Returns
Temperature in kelvin. This is the value set by setTemperature() or assignVelocitiesAtTemperature(), not a newly computed kinetic temperature.

◆ getVdwType()

int CharmmContext::getVdwType ( void  ) const

Returns the stored van der Waals model identifier.

Returns
Native model code in the VDW_VSH through VDW_DBEXP range.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ getVelocitiesInverseMasses() [1/2]

CudaContainer< double4 > & CharmmContext::getVelocitiesInverseMasses ( void  )

Returns mutable velocity/inverse-mass storage.

Returns
Borrowed mutable alias to the context-owned double4 container.
Warning
Mutations through this alias bypass unit, shape, and atom-count validation and do not perform host/device transfer.

◆ getVelocitiesInverseMasses() [2/2]

const CudaContainer< double4 > & CharmmContext::getVelocitiesInverseMasses ( void  ) const

Returns the velocity/inverse-mass container.

Each double4 is [vx, vy, vz, inverse_mass] in atom order. Velocity uses angstroms per AKMA time unit and inverse mass uses reciprocal atomic mass units.

Returns
Borrowed const alias to context-owned storage. No transfer or CUDA synchronization is performed. The reference remains valid until context destruction, but element addresses can be invalidated by resizing.

◆ getVirial()

CudaContainer< double > & CharmmContext::getVirial ( void  )

Aggregates and returns the total virial storage.

The force manager combines bonded, reciprocal, direct, and eligible subscribed-force virials into its nine-element total container.

Returns
Borrowed mutable alias to the force manager's total virial container.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if a required transfer or synchronization fails.

◆ getVolume()

double CharmmContext::getVolume ( void  ) const

Returns the orthorhombic box volume.

Returns
Product of the three box lengths in cubic angstroms.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if valid positive box dimensions have not been set.

◆ getWaterMolecules() [1/2]

CudaContainer< int4 > & CharmmContext::getWaterMolecules ( void  )

Returns mutable PSF water-molecule records.

Returns
Borrowed mutable alias to the attached PSF's int4 container.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no PSF is attached.
Warning
Mutations bypass PSF validation and do not rebuild initialized holonomic-constraint state.

◆ getWaterMolecules() [2/2]

const CudaContainer< int4 > & CharmmContext::getWaterMolecules ( void  ) const

Returns the PSF water-molecule index records.

Returns
Borrowed const alias to the attached PSF's int4 CUDA container. No transfer or synchronization is performed. The component interpretation is defined by the PSF representation.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no PSF is attached.

◆ hasCompleteForceManagerState()

bool CharmmContext::hasCompleteForceManagerState ( void  ) const
protected

Reports whether force-manager initialization prerequisites exist.

Returns
true only when a force manager, PSF, parameters, and exactly three positive box dimensions are present.

◆ imageCentering()

void CharmmContext::imageCentering ( void  )

Images complete PSF groups into the central periodic box.

The operation computes each contiguous PSF group's arithmetic coordinate center and translates the full group by box lengths as needed. Under PBC::P21, crossing an X boundary also reflects Y and Z coordinates, velocity components, and force components.

The kernel mutates the device copies of single- and double-precision coordinates, velocity components, and forces. It launches on the default stream and finishes with cudaDeviceSynchronize(). Host mirrors are not updated.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the force manager is missing or not initialized, the PSF is missing, or valid box dimensions are absent.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if the kernel launch or device synchronization fails.
Warning
Host coordinate and velocity mirrors can be stale after this method returns. Transfer from device before reading them on the host.

◆ initializeForceManagerIfReady()

void CharmmContext::initializeForceManagerIfReady ( void  )
protected

Initializes the force manager when all required state is available.

The helper returns without effect when the manager is missing, already initialized, or incomplete. After initialization it reimports manager state into the context.

◆ linkBackForceManager()

void CharmmContext::linkBackForceManager ( void  )

Stores a weak context backlink in the attached ForceManager.

The operation uses weak_from_this().lock(). It has no effect when this object is not currently owned by a std::shared_ptr.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.
Postcondition
When shared ownership exists, the force manager observes this context through a non-owning weak pointer.

◆ printEnergyTable()

void CharmmContext::printEnergyTable ( void  )
protected

Formats and prints the current CHARMM-style energy table.

The helper transfers total potential energy to host, obtains host force components, computes gradient RMS, prints named standard energy components, and advances the context-local print-history counters.

Precondition
The force manager is initialized and exposes all component names read by the formatter.

◆ requireForceManager()

void CharmmContext::requireForceManager ( void  ) const
protected

Requires an attached ForceManager.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no manager is attached.

◆ requireInitializedForceManager()

void CharmmContext::requireInitializedForceManager ( void  ) const
protected

Requires an attached and initialized ForceManager.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the manager is missing or not initialized.

◆ requirePsf()

void CharmmContext::requirePsf ( void  ) const
protected

Requires an attached PSF.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no PSF is attached.

◆ resetNeighborList()

void CharmmContext::resetNeighborList ( void  )

Images coordinates and rebuilds the direct-space neighbor list.

imageCentering() is called first, after which the force manager rebuilds its neighbor list from the single-precision device coordinate/charge array.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if required force-manager, PSF, or box state is missing.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if imaging, synchronization, or neighbor-list rebuilding fails.

◆ setBoxDimensions()

void CharmmContext::setBoxDimensions ( const std::vector< double > &  boxDimensions)

Sets the orthorhombic box dimensions.

boxDimensions must contain [x, y, z] lengths in angstroms. The context requires exactly three positive values. An attached force manager additionally rejects non-finite dimensions and can reject a configuration whose direct-space cutoff exceeds half the X dimension.

Supplying the final missing setup state can initialize the force manager. If it was already initialized and coordinates are present, a successful update image-centers coordinates and rebuilds the neighbor list.

Parameters
[in]boxDimensionsThree host values in X, Y, Z order. The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the vector does not contain exactly three positive values or attached force-manager validation rejects the dimensions or cutoff.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if triggered initialization, image centering, synchronization, or neighbor-list rebuilding fails.

◆ setCharges()

void CharmmContext::setCharges ( const std::vector< double > &  charges)

Sets per-atom charges while preserving coordinates.

Charges are copied in atom order, converted to single precision for the float4 mirror, and transferred to both device mirrors. Charge values use elementary-charge units. This call does not rebuild the neighbor list.

Parameters
[in]chargesOne charge per atom. The input is borrowed for the call and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if charges.size() differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if either host-to-device transfer fails.

◆ setCoordinates() [1/4]

void CharmmContext::setCoordinates ( const std::shared_ptr< Coordinates crd)

Sets coordinates from a Coordinates object.

Double-precision coordinates are read from crd and copied into the context. The context does not retain the supplied object. Existing charges are preserved.

Parameters
[in]crdShared owner of the coordinate object to read. The pointer must be non-null and is borrowed only for this call.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if crd is null or its coordinate count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary coordinate setter.

◆ setCoordinates() [2/4]

void CharmmContext::setCoordinates ( const std::vector< double > &  coordinates)

Sets Cartesian coordinates from a flat scalar array.

The array is interpreted as N consecutive [x, y, z] records with stride three and units of angstroms. Existing charge components are preserved.

Parameters
[in]coordinatesFlat host array. Its length must be exactly 3 * getNumAtoms(). The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the length is not a multiple of three or the derived record count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary coordinate setter.

◆ setCoordinates() [3/4]

void CharmmContext::setCoordinates ( const std::vector< double3 > &  coordinates)

Sets Cartesian coordinates while preserving stored charges.

The vector must contain exactly one double3 per atom. Components are Cartesian coordinates in angstroms. Coordinates are copied to the double-precision array, converted for the single-precision array, and transferred to both device mirrors.

If the force manager was already initialized, a successful update image-centers coordinates and rebuilds its neighbor list.

Parameters
[in]coordinatesContiguous host coordinates in atom order. The input is borrowed for the call and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the coordinate count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if a transfer, image-centering operation, synchronization, or neighbor-list rebuild fails.

◆ setCoordinates() [4/4]

void CharmmContext::setCoordinates ( const std::vector< std::vector< double > > &  coordinates)

Sets Cartesian coordinates from nested scalar rows.

Every row must contain exactly three values in [x, y, z] order and uses angstroms. Existing charge components are preserved.

Parameters
[in]coordinatesHost rows in atom order. The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if a row does not contain exactly three values or the number of rows differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary coordinate setter.

◆ setCoordinatesCharges() [1/3]

void CharmmContext::setCoordinatesCharges ( const std::vector< double > &  coordinatesCharges)

Sets coordinates and charges from a flat scalar array.

The array is interpreted as N consecutive [x, y, z, charge] records with stride four. Coordinates use angstroms and charges use elementary-charge units.

Parameters
[in]coordinatesChargesFlat host array. Its length must be exactly 4 * getNumAtoms(). The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the length is not a multiple of four or the derived record count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary setter.

◆ setCoordinatesCharges() [2/3]

void CharmmContext::setCoordinatesCharges ( const std::vector< double4 > &  coordinatesCharges)

Sets coordinates and charges from double4 records.

The vector must contain exactly one record per atom. Components x, y, and z are Cartesian coordinates in angstroms; component w is charge in elementary-charge units. Values are copied into double-precision storage, converted to float4 for single-precision storage, and transferred to both device mirrors.

If the force manager was already initialized, a successful update image-centers the coordinates and rebuilds its neighbor list.

Parameters
[in]coordinatesChargesContiguous host records in atom order. The input is borrowed for the call and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the record count differs from the context atom count or an initialized non-composite force manager's count.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if a transfer, image-centering operation, synchronization, or neighbor-list rebuild fails.
Postcondition
On success, the host and device coordinate/charge mirrors represent the supplied values, subject to any periodic image-centering performed during neighbor-list rebuilding.

◆ setCoordinatesCharges() [3/3]

void CharmmContext::setCoordinatesCharges ( const std::vector< std::vector< double > > &  coordinatesCharges)

Sets coordinates and charges from nested scalar rows.

Every row must contain exactly four values in [x, y, z, charge] order. Coordinates use angstroms and charges use elementary-charge units. The nested input is converted to double4 records and then processed by the primary coordinate/charge setter.

Parameters
[in]coordinatesChargesHost rows in atom order. The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if any row does not contain exactly four values or the number of rows does not match the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary setter.

◆ setCtofnb()

void CharmmContext::setCtofnb ( const float  ctofnb)

Sets the nonbonded distance exposed as ctofnb.

Parameters
[in]ctofnbDistance in angstroms. The value must be finite and positive.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if ctofnb is non-finite or not positive.
Warning
The current direct-force initialization forwards this stored value to the backend parameter named ron. Configure it before force-manager initialization.

◆ setCtonnb()

void CharmmContext::setCtonnb ( const float  ctonnb)

Sets the nonbonded distance exposed as ctonnb.

Parameters
[in]ctonnbDistance in angstroms. The value must be finite and positive.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if ctonnb is non-finite or not positive.
Warning
The current direct-force initialization forwards this stored value to the backend parameter named roff. Configure it before force-manager initialization.

◆ setCutoff()

void CharmmContext::setCutoff ( const float  cutoff)

Sets the direct-space neighbor-list cutoff.

Parameters
[in]cutoffCutoff distance in angstroms. The value must be finite and positive. Force-manager initialization additionally requires it not to exceed half the X box length.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if cutoff is non-finite or not positive.
Warning
Configure this value before force-manager initialization. The current setter does not rebuild an already initialized neighbor-list implementation.

◆ setFFTGrid()

void CharmmContext::setFFTGrid ( const int  nfftx,
const int  nffty,
const int  nfftz 
)

Sets the three-dimensional PME FFT grid.

Parameters
[in]nfftxPositive number of grid points along X.
[in]nfftyPositive number of grid points along Y.
[in]nfftzPositive number of grid points along Z.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if any dimension is not positive.
Warning
Configure the grid before force-manager initialization. The current setter does not rebuild an initialized PME object.

◆ setForceManager()

void CharmmContext::setForceManager ( std::shared_ptr< ForceManager fm)

Sets the ForceManager associated with the context.

The context retains shared ownership of fm. Existing context PSF, parameter, box, and periodic-boundary state take precedence and are pushed into the manager. State absent from the context is imported from the manager. A complete uninitialized manager is initialized automatically.

When the context is owned by std::shared_ptr, the manager receives a weak backlink to the context. No ownership cycle is created.

Parameters
[in]fmShared force-manager owner. The pointer must be non-null and is retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if fm is null or synchronized configuration is invalid.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if synchronization or initialization encounters a CUDA failure.
ApoCharmmErrorWith code ApoCharmmErrorCode::Runtime if native force initialization fails for another runtime condition.
Warning
Replacing the manager can invalidate force, energy, virial, constraint, and stride references obtained from the previous manager.

◆ setKappa()

void CharmmContext::setKappa ( const float  kappa)

Sets the Ewald splitting parameter.

Parameters
[in]kappaEwald splitting parameter in inverse angstroms. The value must be finite and non-negative.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if kappa is non-finite or negative.
Warning
Configure this value before force-manager initialization. The current setter updates stored configuration but does not rebuild already initialized reciprocal- or direct-space force objects.

◆ setMasses()

void CharmmContext::setMasses ( const std::vector< double > &  masses)

Sets masses and stores their reciprocals with the velocities.

The vector must contain one mass per atom in atomic mass units. For each atom, the context stores 1.0 / masses[i] in the w component and preserves the existing velocity components.

Parameters
[in]massesHost masses in atom order. The input is borrowed for the call and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the number of masses differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if the host-to-device transfer fails.
Warning
The current implementation does not reject zero, negative, infinite, or NaN masses before computing their reciprocals.

◆ setNumAtoms()

void CharmmContext::setNumAtoms ( const int  numAtoms)

Sets the atom count and sizes per-atom state storage.

numAtoms must be positive. When a size changes, the single-precision and double-precision coordinate/charge arrays and the velocity/inverse-mass array are resized to numAtoms and initialized to zero. A coordinate-size change clears the internal coordinates-present flag.

This function does not import charges, masses, coordinates, or velocities.

Parameters
[in]numAtomsNumber of atoms. The value is dimensionless and must be greater than zero.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if numAtoms is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if CUDA storage resizing or initialization fails.
Postcondition
Every per-atom container has active length numAtoms.
Warning
A reallocation invalidates borrowed device pointers and element references into the resized containers.

◆ setPeriodicBoundaryCondition()

void CharmmContext::setPeriodicBoundaryCondition ( const PBC  pbc)

Sets the periodic boundary condition.

The selected value is stored in the context and forwarded to an attached force manager. Supplying this state can initialize a complete force manager. If the manager was already initialized and coordinates are present, a successful update image-centers the coordinates and rebuilds the neighbor list.

Parameters
[in]pbcOne of PBC::NONE, PBC::P1, or PBC::P21.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the completed force configuration is rejected.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if initialization, image centering, synchronization, or neighbor-list rebuilding fails in CUDA.

◆ setPmeSplineOrder()

void CharmmContext::setPmeSplineOrder ( const int  pmeSplineOrder)

Sets the PME interpolation spline order.

Parameters
[in]pmeSplineOrderPositive dimensionless spline order.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if pmeSplineOrder is not positive.
Warning
Configure the order before force-manager initialization. The current setter does not rebuild an initialized PME object.

◆ setPrm()

void CharmmContext::setPrm ( std::shared_ptr< CharmmParameters prm)

Sets the CHARMM parameter set used by the context.

The context retains shared ownership of prm and forwards the same native object to an attached force manager. Supplying the final missing piece of a complete configuration can initialize the force manager.

Parameters
[in]prmShared parameter-set owner. The pointer must be non-null and is retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if prm is null or the completed force configuration is invalid.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if triggered force-manager initialization encounters a CUDA failure.
ApoCharmmErrorWith code ApoCharmmErrorCode::Runtime if triggered parameter or force initialization fails for another runtime condition.
Warning
The operation is not transactional when it triggers force-manager initialization.

◆ setPsf()

void CharmmContext::setPsf ( std::shared_ptr< CharmmPSF psf)

Sets the molecular PSF and imports its atom data.

The context retains shared ownership of psf, sets the atom count, copies charges in elementary-charge units, copies masses in atomic mass units, and forwards the PSF to an attached force manager. Changing from one positive atom count to a different positive atom count is rejected.

Resizing atom storage invalidates previously borrowed element references, iterators, and device pointers from the coordinate/charge and velocity/inverse-mass containers.

Parameters
[in]psfShared PSF owner. The pointer must be non-null and is retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if psf is null or its atom count differs from the context's established positive atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if resizing, copying, or triggered force-manager initialization fails in CUDA.
ApoCharmmErrorWith code ApoCharmmErrorCode::Runtime if PSF or force initialization fails for another runtime condition.
Warning
A failure after resizing or copying atom state does not roll the context back to its previous state.

◆ setRandomSeed()

void CharmmContext::setRandomSeed ( const std::uint64_t  randomSeed)

Sets the deterministic random seed used for velocity generation.

Parameters
[in]randomSeedUnsigned 64-bit seed. The value is dimensionless.
Postcondition
A later call to assignVelocitiesAtTemperature() initializes a new std::mt19937 from this value.

◆ setTemperature()

void CharmmContext::setTemperature ( const double  temperature)

Sets the stored target temperature.

This call updates only the context's stored temperature in kelvin. It does not generate, rescale, or otherwise modify velocities.

Parameters
[in]temperatureTemperature in kelvin. The value must be finite and non-negative.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if temperature is NaN, infinite, or negative.

◆ setVdwType()

void CharmmContext::setVdwType ( const int  vdwType)

Sets the van der Waals model identifier.

Parameters
[in]vdwTypeOne of the native constants from VDW_VSH through VDW_DBEXP, with numeric range [1, 6].
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if vdwType is outside [1, 6].
Warning
Configure the model before force-manager initialization. The current setter does not rebuild an initialized direct-space force object.

◆ setVelocities() [1/3]

void CharmmContext::setVelocities ( const std::vector< double > &  velocities)

Sets velocities from a flat scalar array.

The array is interpreted as N consecutive [vx, vy, vz] records with stride three and units of angstroms per AKMA time unit. Existing inverse masses are preserved.

Parameters
[in]velocitiesFlat host array with length exactly 3 * getNumAtoms(). The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the length is not a multiple of three or the derived record count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary velocity setter.

◆ setVelocities() [2/3]

void CharmmContext::setVelocities ( const std::vector< double3 > &  velocities)

Sets velocity components while preserving inverse masses.

The vector must contain one double3 per atom. Components use angstroms per AKMA time unit. Values are copied to the host mirror and transferred to the device.

Parameters
[in]velocitiesHost velocities in atom order. The input is borrowed for the call and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the velocity count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if the host-to-device transfer fails.

◆ setVelocities() [3/3]

void CharmmContext::setVelocities ( const std::vector< std::vector< double > > &  velocities)

Sets velocities from nested scalar rows.

Every row must contain [vx, vy, vz] in angstroms per AKMA time unit. Existing inverse masses are preserved.

Parameters
[in]velocitiesHost rows in atom order. The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if a row does not contain exactly three values or the row count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary velocity setter.

◆ setVelocitiesFromCHARMMVelocityFile()

void CharmmContext::setVelocitiesFromCHARMMVelocityFile ( const std::string &  fileName)

Loads velocities from a CHARMM coordinate-format velocity file.

Lines beginning with * are skipped as title lines. The next non-title line must contain the atom count, followed by exactly one parseable atom record per context atom. Only the three velocity fields are copied; existing inverse masses are preserved. Parsed velocity values use the units encoded by the source file and are consumed by apoCHARMM as angstroms per AKMA time unit.

Parameters
[in]fileNameNonempty path to the file. The string is borrowed for the call and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if fileName is empty or the file's atom count differs from the context atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::Runtime if the file cannot be opened or its atom count or a velocity record cannot be read or parsed.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if the final host-to-device transfer fails.

◆ setVelocitiesInverseMasses() [1/3]

void CharmmContext::setVelocitiesInverseMasses ( const std::vector< double > &  velocitiesInverseMasses)

Sets velocities and inverse masses from a flat scalar array.

The array is interpreted as N consecutive [vx, vy, vz, inverse_mass] records with stride four.

Parameters
[in]velocitiesInverseMassesFlat host array with length exactly 4 * getNumAtoms(). The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the length is not a multiple of four or the derived record count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary setter.

◆ setVelocitiesInverseMasses() [2/3]

void CharmmContext::setVelocitiesInverseMasses ( const std::vector< double4 > &  velocitiesInverseMasses)

Sets velocities and inverse masses from double4 records.

The vector must contain one record per atom. Components x, y, and z are velocity components in angstroms per AKMA time unit; component w is inverse mass in reciprocal atomic mass units. Values are copied and transferred to device storage.

Parameters
[in]velocitiesInverseMassesHost records in atom order. The input is borrowed for the call and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if the record count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda if the host-to-device transfer fails.

◆ setVelocitiesInverseMasses() [3/3]

void CharmmContext::setVelocitiesInverseMasses ( const std::vector< std::vector< double > > &  velocitiesInverseMasses)

Sets velocities and inverse masses from nested scalar rows.

Every row must contain [vx, vy, vz, inverse_mass]. Velocity components use angstroms per AKMA time unit and inverse masses use reciprocal atomic mass units.

Parameters
[in]velocitiesInverseMassesHost rows in atom order. The input is copied and is not retained.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::InvalidArgument if a row does not contain exactly four values or the row count differs from the atom count.
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if the atom count is not positive.
ApoCharmmErrorWith code ApoCharmmErrorCode::Cuda for failures propagated by the primary setter.

◆ syncForceManagerFromState()

void CharmmContext::syncForceManagerFromState ( void  )
protected

Reconciles context state with the attached ForceManager.

Context PSF, parameters, box, and periodic-boundary state take precedence when present. Missing context state is imported from the manager.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ syncStateFromForceManager()

void CharmmContext::syncStateFromForceManager ( void  )
protected

Imports collaborator state from the attached ForceManager.

Existing PSF atom storage is resized and initialized when the manager's PSF changes. Parameters, box dimensions, and periodic-boundary state are then copied into the context.

Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no force manager is attached.

◆ useHolonomicConstraints()

void CharmmContext::useHolonomicConstraints ( const bool  usingHolonomicConstraints)

Selects holonomic-constraint degree-of-freedom accounting.

The method recomputes the degree-of-freedom count from the atom count, periodic-boundary condition, PSF water molecules, and the force manager's SHAKE atom records. It controls whether those constraints are subtracted from the reported degree-of-freedom count; it does not itself execute a constraint solver.

Parameters
[in]usingHolonomicConstraintstrue to subtract recognized water and SHAKE constraints; false to retain only periodic-boundary reductions.
Exceptions
ApoCharmmErrorWith code ApoCharmmErrorCode::NotInitialized if no PSF or no force manager is attached.
Postcondition
getNumDegreesOfFreedom() returns the newly computed count.

◆ usingHolonomicConstraints()

bool CharmmContext::usingHolonomicConstraints ( void  ) const

Reports whether holonomic constraints are included in DOF accounting.

Returns
true when water and SHAKE constraints are subtracted from the degree-of-freedom count; otherwise false.

Member Data Documentation

◆ m_BoxDimensions

std::vector<double> CharmmContext::m_BoxDimensions
protected

Orthorhombic X, Y, Z box lengths in angstroms.

◆ m_CoordinatesChargesDP

CudaContainer<double4> CharmmContext::m_CoordinatesChargesDP
protected

Double-precision [x, y, z, charge] host/device mirrors.

◆ m_CoordinatesChargesSP

CudaContainer<float4> CharmmContext::m_CoordinatesChargesSP
protected

Single-precision [x, y, z, charge] host/device mirrors.

◆ m_EnergyTableEvaluationCount

std::uint64_t CharmmContext::m_EnergyTableEvaluationCount
protected

Number printed in the next CHARMM-style energy table.

◆ m_ForceManager

std::shared_ptr<ForceManager> CharmmContext::m_ForceManager
protected

Shared force-manager owner. The reverse manager-to-context association is weak.

◆ m_HasBoxDimensions

bool CharmmContext::m_HasBoxDimensions
protected

Records whether valid positive box dimensions were established.

◆ m_HasCoordinates

bool CharmmContext::m_HasCoordinates
protected

Records whether coordinates were supplied after the latest resize.

◆ m_HasPbc

bool CharmmContext::m_HasPbc
protected

Records whether periodic-boundary state was explicitly imported or set.

◆ m_HasPreviousPrintedPotentialEnergy

bool CharmmContext::m_HasPreviousPrintedPotentialEnergy
protected

Records whether a previous printed energy exists for delta calculation.

◆ m_KineticEnergy

CudaContainer<double> CharmmContext::m_KineticEnergy
protected

Single-element kinetic-energy result container.

◆ m_KineticEnergyPartialSums

CudaContainer<double> CharmmContext::m_KineticEnergyPartialSums
protected

Stores one kinetic-energy partial sum per first-pass CUDA block.

◆ m_NumAtoms

int CharmmContext::m_NumAtoms
protected

Number of atoms represented by every per-atom context array.

◆ m_NumDegreesOfFreedom

int CharmmContext::m_NumDegreesOfFreedom
protected

Current mechanical degree-of-freedom count.

◆ m_Pbc

PBC CharmmContext::m_Pbc
protected

Stored periodic-boundary condition.

◆ m_Pressure

CudaContainer<double> CharmmContext::m_Pressure
protected

Nine-element pressure storage; pressure computation is not implemented.

◆ m_PreviousPrintedPotentialEnergy

double CharmmContext::m_PreviousPrintedPotentialEnergy
protected

Total energy printed by the previous table.

◆ m_Prm

std::shared_ptr<CharmmParameters> CharmmContext::m_Prm
protected

Shared parameter-set owner retained by the context.

◆ m_Psf

std::shared_ptr<CharmmPSF> CharmmContext::m_Psf
protected

Shared PSF owner retained by the context.

◆ m_RandomSeed

std::uint64_t CharmmContext::m_RandomSeed
protected

Seed used to initialize the per-call velocity generator.

◆ m_Temperature

double CharmmContext::m_Temperature
protected

Stored target temperature in kelvin.

◆ m_UsingHolonomicConstraints

bool CharmmContext::m_UsingHolonomicConstraints
protected

Selects constrained degree-of-freedom accounting.

◆ m_VelocitiesInverseMasses

CudaContainer<double4> CharmmContext::m_VelocitiesInverseMasses
protected

Double-precision [vx, vy, vz, inverse_mass] host/device mirrors.

◆ m_VirialKineticEnergyTensor

CudaContainer<double> CharmmContext::m_VirialKineticEnergyTensor
protected

Nine-element kinetic virial tensor storage.