Commit 6ccf6169 authored by Peter Eastman's avatar Peter Eastman
Browse files

Removed Brook platform

parent 82e0bd2f
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "openmm/OpenMMException.h"
#include "BrookCalcPeriodicTorsionForceKernel.h"
#include <sstream>
using namespace OpenMM;
using namespace std;
const std::string BrookCalcPeriodicTorsionForceKernel::BondName = "ProperTorsion";
/**
* BrookCalcPeriodicTorsionForceKernel constructor
*
* @param name kernel name
* @param platform platform
* @param OpenMMBrookInterface OpenMM-Brook interface
* @param System System reference
*
*/
BrookCalcPeriodicTorsionForceKernel::BrookCalcPeriodicTorsionForceKernel( std::string name, const Platform& platform,
OpenMMBrookInterface& openMMBrookInterface, System& system ) :
CalcPeriodicTorsionForceKernel( name, platform ), _openMMBrookInterface( openMMBrookInterface ), _system( system ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCalcPeriodicTorsionForceKernel::BrookCalcPeriodicTorsionForceKernel";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
_brookBondParameters = NULL;
_log = NULL;
_openMMBrookInterface.setNumberOfParticles( system.getNumParticles() );
const BrookPlatform& brookPlatform = dynamic_cast<const BrookPlatform&> (platform);
if( brookPlatform.getLog() != NULL ){
setLog( brookPlatform.getLog() );
}
}
/**
* BrookCalcPeriodicTorsionForceKernel destructor
*
*/
BrookCalcPeriodicTorsionForceKernel::~BrookCalcPeriodicTorsionForceKernel( ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCalcPeriodicTorsionForceKernel::BrookCalcPeriodicTorsionForceKernel";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
delete _brookBondParameters;
}
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* BrookCalcPeriodicTorsionForceKernel::getLog( void ) const {
return _log;
}
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int BrookCalcPeriodicTorsionForceKernel::setLog( FILE* log ){
_log = log;
return BrookCommon::DefaultReturnValue;
}
/**
* Initialize the kernel, setting up the values of all the force field parameters.
*
* @param system System reference
* @param force ProperTorsionForce reference
*
*/
void BrookCalcPeriodicTorsionForceKernel::initialize( const System& system, const PeriodicTorsionForce& force ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookCalcPeriodicTorsionForceKernel::initialize";
// ---------------------------------------------------------------------------------------
FILE* log = getLog();
// ---------------------------------------------------------------------------------------
// create _brookBondParameters object containing particle indices/parameters
int numberOfBonds = force.getNumTorsions();
if( _brookBondParameters ){
delete _brookBondParameters;
}
_brookBondParameters = new BrookBondParameters( BondName, NumberOfParticlesInBond, NumberOfParametersInBond, numberOfBonds, getLog() );
for( int ii = 0; ii < numberOfBonds; ii++ ){
int particle1, particle2, particle3, particle4, periodicity;
double phase, k;
int particles[NumberOfParticlesInBond];
double parameters[NumberOfParametersInBond];
force.getTorsionParameters( ii, particle1, particle2, particle3, particle4, periodicity, phase, k );
particles[0] = particle1;
particles[1] = particle2;
particles[2] = particle3;
particles[3] = particle4;
parameters[0] = (double) periodicity;
parameters[1] = phase;
parameters[2] = k;
_brookBondParameters->setBond( ii, particles, parameters );
}
_openMMBrookInterface.setPeriodicTorsionForceParameters( _brookBondParameters );
_openMMBrookInterface.setTriggerForceKernel( this );
_openMMBrookInterface.setTriggerEnergyKernel( this );
if( log ){
std::string contents = _brookBondParameters->getContentsString( );
(void) fprintf( log, "%s contents\n%s", methodName.c_str(), contents.c_str() );
(void) fflush( log );
}
// ---------------------------------------------------------------------------------------
}
/**
* Compute forces given particle coordinates
*
* @param context ContextImpl context
*
*/
void BrookCalcPeriodicTorsionForceKernel::executeForces( ContextImpl& context ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCalcPeriodicTorsionForceKernel::executeForces";
// ---------------------------------------------------------------------------------------
if( _openMMBrookInterface.getTriggerForceKernel() == this ){
_openMMBrookInterface.computeForces( context );
}
return;
// ---------------------------------------------------------------------------------------
}
/**
* Execute the kernel to calculate the energy
*
* @param context ContextImpl context
*
* @return potential energy
*
*/
double BrookCalcPeriodicTorsionForceKernel::executeEnergy( ContextImpl& context ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCalcPeriodicTorsionForceKernel::executeEnergy";
// ---------------------------------------------------------------------------------------
if( _openMMBrookInterface.getTriggerEnergyKernel() == this ){
return (double) _openMMBrookInterface.computeEnergy( context, _system );
} else {
return 0.0;
}
}
#ifndef OPENMM_BROOK_CALC_PERIODIC_TORSION_FORCE_KERNEL_H_
#define OPENMM_BROOK_CALC_PERIODIC_TORSION_FORCE_KERNEL_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "openmm/kernels.h"
#include "BrookPlatform.h"
#include "BrookBondParameters.h"
#include "OpenMMBrookInterface.h"
namespace OpenMM {
/**
* This kernel is invoked to calculate the periodic torsion forces acting on the system.
*/
class BrookCalcPeriodicTorsionForceKernel : public CalcPeriodicTorsionForceKernel {
public:
/**
* BrookCalcPeriodicTorsionForceKernel constructor
*/
BrookCalcPeriodicTorsionForceKernel( std::string name, const Platform& platform, OpenMMBrookInterface& openMMBrookInterface, System& system );
/**
* BrookCalcPeriodicTorsionForceKernel destructor
*/
~BrookCalcPeriodicTorsionForceKernel();
/**
* Initialize the kernel, setting up the values to calculate harmonic bond force & energy
*
* @param system System reference
* @param force ProperTorsionForce reference
*
*/
void initialize( const System& system, const PeriodicTorsionForce& force );
/**
* Execute the kernel to calculate the forces.
*
* @param positions particle coordiantes
* @param forces output forces
*
*/
void executeForces( ContextImpl& context );
/**
* Execute the kernel to calculate the energy.
*
* @param context the context in which to execute this kernel
*
* @return potential energy associated with the harmonic angle force
*
*/
double executeEnergy( ContextImpl& context );
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int setLog( FILE* log );
/*
* Get contents of object
*
* @param level of dump
*
* @return string containing contents
*
* */
std::string getContents( int level ) const;
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* getLog( void ) const;
/**
* Get number of bonds
*
* @return number of bonds
*
*/
int getNumberOfBonds( void ) const;
/**
* Get indices/parameters
*
* @return BrookBondParameters containing particle indices/parameters
*
*/
BrookBondParameters* getBrookBondParameters( void ) const;
private:
static const int NumberOfParticlesInBond = 4;
static const int NumberOfParametersInBond = 3;
// bond name
static const std::string BondName;
// log file reference
FILE* _log;
// Brook bond parameters
BrookBondParameters* _brookBondParameters;
// interface
OpenMMBrookInterface& _openMMBrookInterface;
// System reference
System& _system;
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_CALC_PERIODIC_TORSION_FORCE_KERNEL_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "openmm/OpenMMException.h"
#include "BrookCalcRBTorsionForceKernel.h"
#include <sstream>
using namespace OpenMM;
using namespace std;
const std::string BrookCalcRBTorsionForceKernel::BondName = "RbTorsion";
/**
* BrookCalcRBTorsionForceKernel constructor
*
* @param name kernel name
* @param platform platform
* @param OpenMMBrookInterface OpenMM-Brook interface
* @param System System reference
*
*/
BrookCalcRBTorsionForceKernel::BrookCalcRBTorsionForceKernel( std::string name, const Platform& platform,
OpenMMBrookInterface& openMMBrookInterface, System& system ) :
CalcRBTorsionForceKernel( name, platform ), _openMMBrookInterface( openMMBrookInterface ), _system( system ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCalcRBTorsionForceKernel::BrookCalcRBTorsionForceKernel";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
_brookBondParameters = NULL;
_log = NULL;
_openMMBrookInterface.setNumberOfParticles( system.getNumParticles() );
const BrookPlatform& brookPlatform = dynamic_cast<const BrookPlatform&> (platform);
if( brookPlatform.getLog() != NULL ){
setLog( brookPlatform.getLog() );
}
}
/**
* BrookCalcRBTorsionForceKernel destructor
*
*/
BrookCalcRBTorsionForceKernel::~BrookCalcRBTorsionForceKernel( ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCalcRBTorsionForceKernel::BrookCalcRBTorsionForceKernel";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
delete _brookBondParameters;
}
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* BrookCalcRBTorsionForceKernel::getLog( void ) const {
return _log;
}
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int BrookCalcRBTorsionForceKernel::setLog( FILE* log ){
_log = log;
return BrookCommon::DefaultReturnValue;
}
/**
* Initialize the kernel, setting up the values of all the force field parameters.
*
* @param system System reference
* @param force RbTorsionForce reference
*
*/
void BrookCalcRBTorsionForceKernel::initialize( const System& system, const RBTorsionForce& force ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookCalcRBTorsionForceKernel::initialize";
// ---------------------------------------------------------------------------------------
FILE* log = getLog();
// ---------------------------------------------------------------------------------------
// create _brookBondParameters object containing particle indices/parameters
int numberOfBonds = force.getNumTorsions();
if( _brookBondParameters ){
delete _brookBondParameters;
}
_brookBondParameters = new BrookBondParameters( BondName, NumberOfParticlesInBond, NumberOfParametersInBond, numberOfBonds, getLog() );
for( int ii = 0; ii < numberOfBonds; ii++ ){
int particle1, particle2, particle3, particle4;
double c0, c1, c2, c3, c4, c5;
int particles[NumberOfParticlesInBond];
double parameters[NumberOfParametersInBond];
force.getTorsionParameters( ii, particle1, particle2, particle3, particle4, c0, c1, c2, c3, c4, c5 );
particles[0] = particle1;
particles[1] = particle2;
particles[2] = particle3;
particles[3] = particle4;
parameters[0] = c0;
parameters[1] = c1;
parameters[2] = c2;
parameters[3] = c3;
parameters[4] = c4;
parameters[5] = c5;
_brookBondParameters->setBond( ii, particles, parameters );
}
_openMMBrookInterface.setRBTorsionForceParameters( _brookBondParameters );
_openMMBrookInterface.setTriggerForceKernel( this );
_openMMBrookInterface.setTriggerEnergyKernel( this );
if( log ){
std::string contents = _brookBondParameters->getContentsString( );
(void) fprintf( log, "%s contents\n%s", methodName.c_str(), contents.c_str() );
(void) fflush( log );
}
// ---------------------------------------------------------------------------------------
}
/**
* Compute forces given particle coordinates
*
* @param context ContextImpl context
*
*/
void BrookCalcRBTorsionForceKernel::executeForces( ContextImpl& context ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCalcRBTorsionForceKernel::executeForces";
// ---------------------------------------------------------------------------------------
if( _openMMBrookInterface.getTriggerForceKernel() == this ){
_openMMBrookInterface.computeForces( context );
}
return;
// ---------------------------------------------------------------------------------------
}
/**
* Execute the kernel to calculate the energy
*
* @param context ContextImpl context
*
* @return potential energy
*
*/
double BrookCalcRBTorsionForceKernel::executeEnergy( ContextImpl& context ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCalcRBTorsionForceKernel::executeEnergy";
// ---------------------------------------------------------------------------------------
if( _openMMBrookInterface.getTriggerEnergyKernel() == this ){
return (double) _openMMBrookInterface.computeEnergy( context, _system );
} else {
return 0.0;
}
}
#ifndef OPENMM_BROOK_CALC_RB_TORSION_FORCE_KERNEL_H_
#define OPENMM_BROOK_CALC_RB_TORSION_FORCE_KERNEL_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "openmm/kernels.h"
#include "BrookPlatform.h"
#include "BrookBondParameters.h"
#include "OpenMMBrookInterface.h"
namespace OpenMM {
/**
* This kernel is invoked to calculate the RB torsion forces acting on the system.
*/
class BrookCalcRBTorsionForceKernel : public CalcRBTorsionForceKernel {
public:
/**
* BrookCalcRBTorsionForceKernel constructor
*/
BrookCalcRBTorsionForceKernel( std::string name, const Platform& platform, OpenMMBrookInterface& openMMBrookInterface, System& system );
/**
* BrookCalcRBTorsionForceKernel destructor
*/
~BrookCalcRBTorsionForceKernel();
/**
* Initialize the kernel, setting up the values to calculate harmonic bond force & energy
*
* @param system System reference
* @param force RbTorsionForce reference
*
*/
void initialize( const System& system, const RBTorsionForce& force );
/**
* Execute the kernel to calculate the forces.
*
* @param positions particle coordiantes
* @param forces output forces
*
*/
void executeForces( ContextImpl& context );
/**
* Execute the kernel to calculate the energy.
*
* @param context the context in which to execute this kernel
*
* @return potential energy associated with the harmonic angle force
*
*/
double executeEnergy( ContextImpl& context );
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int setLog( FILE* log );
/*
* Get contents of object
*
* @param level of dump
*
* @return string containing contents
*
* */
std::string getContents( int level ) const;
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* getLog( void ) const;
/**
* Get number of bonds
*
* @return number of bonds
*
*/
int getNumberOfBonds( void ) const;
/**
* Get indices/parameters
*
* @return BrookBondParameters containing particle indices/parameters
*
*/
BrookBondParameters* getBrookBondParameters( void ) const;
private:
static const int NumberOfParticlesInBond = 4;
static const int NumberOfParametersInBond = 6;
// bond name
static const std::string BondName;
// log file reference
FILE* _log;
// Brook bond parameters
BrookBondParameters* _brookBondParameters;
// interface
OpenMMBrookInterface& _openMMBrookInterface;
// System reference
System& _system;
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_CALC_RB_TORSION_FORCE_KERNEL_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookCommon.h"
#include "BrookPlatform.h"
#include "BrookStreamFactory.h"
#include "openmm/OpenMMException.h"
#include <cmath>
#include <sstream>
using namespace OpenMM;
using namespace std;
// bonded streams
const std::string BrookCommon::BondedParticleIndicesStream = "BondedParticleIndicesStream";
const std::string BrookCommon::BondedParametersStream = "BondedParametersStream";
const std::string BrookCommon::UnrolledForceStream = "UnrolledForceStream";
const std::string BrookCommon::BondedChargeStream = "BondedChargeStream";
const std::string BrookCommon::BondedInverseMapStreams = "BondedInverseMapStreams";
// non-bonded streams
const std::string BrookCommon::NonBondedExclusionStream = "NonBondedExclusionStream";
const std::string BrookCommon::OuterVdwStream = "OuterVdwStream";
const std::string BrookCommon::InnerSigmaStream = "InnerSigmaStream";
const std::string BrookCommon::InnerEpsilonStream = "InnerEpsilonStream";
const std::string BrookCommon::NonBondedChargeStream = "NonBondedChargeStream";
const std::string BrookCommon::PartialForceStream = "PartialForceStream";
// OBC Gbsa streams
const std::string BrookCommon::ObcParticleRadiiStream = "ObcParticleRadiiStream";
const std::string BrookCommon::ObcScaledParticleRadiiStream = "ObcScaledParticleRadiiStream";
const std::string BrookCommon::ObcParticleRadiiWithDielectricOffsetStream = "ObcParticleRadiiWithDielectricOffsetStream";
const std::string BrookCommon::ObcBornRadiiStream = "ObcBornRadiiStream";
const std::string BrookCommon::ObcBornRadii2Stream = "ObcBornRadii2Stream";
const std::string BrookCommon::ObcIntermediateForceStream = "ObcIntermediateForceStream";
const std::string BrookCommon::ObcChainStream = "ObcChainStream";
// StochasticDynamics streams
const std::string BrookCommon::SDPC1Stream = "SDPC1Stream";
const std::string BrookCommon::SDPC2Stream = "SDPC2Stream";
const std::string BrookCommon::SD2XStream = "SD2XStream";
const std::string BrookCommon::SD1VStream = "SD1VStream";
const std::string BrookCommon::VPrimeStream = "VPrimeStream";
const std::string BrookCommon::XPrimeStream = "XPrimeStream";
const std::string BrookCommon::InverseMassStream = "InverseMassStream";
// Shake streams
const std::string BrookCommon::ShakeParticleIndicesStream = "ShakeParticleIndicesStream";
const std::string BrookCommon::ShakeParticleParameterStream = "ShakeParticleParameterStream";
const std::string BrookCommon::ShakeXCons0Stream = "ShakeXCons0Stream";
const std::string BrookCommon::ShakeXCons1Stream = "ShakeXCons1Stream";
const std::string BrookCommon::ShakeXCons2Stream = "ShakeXCons2Stream";
const std::string BrookCommon::ShakeXCons3Stream = "ShakeXCons3Stream";
const std::string BrookCommon::ShakeInverseMapStream = "ShakeInverseMapStream";
// Random number streams
const std::string BrookCommon::ShuffleStream = "ShuffleStream";
const std::string BrookCommon::RandomValuesStream = "RandomValuesStream";
// Random number streams
const std::string BrookCommon::BrookVelocityCenterOfMassRemovalWorkStream = "VelocityCenterOfMassRemovalWorkStream";
const std::string BrookCommon::BrookVelocityCenterOfMassRemovalMassStream = "VelocityCenterOfMassRemovalMassStream";
/**
* Constructor
*
*/
BrookCommon::BrookCommon( ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCommon::BrookCommon";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
_numberOfParticles = 0;
_particleSizeModified = 0;
_particleStreamWidth = -1;
_particleStreamHeight = -1;
_particleStreamSize = -1;
_log = NULL;
_isActive = 0;
}
/**
* Destructor
*
*/
BrookCommon::~BrookCommon( ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCommon::~BrookCommon";
//static const int debug = 1;
// ---------------------------------------------------------------------------------------
}
/**
* Get number of particles
*
* @return number of particles
*
*/
int BrookCommon::getNumberOfParticles( void ) const {
return _numberOfParticles;
}
/**
* Get number of particles
*
* @param numberOfParticles number of particles
* @return number of particles
*
*/
int BrookCommon::setNumberOfParticles( int numberOfParticles ){
if( numberOfParticles != _numberOfParticles ){
_particleSizeModified = numberOfParticles;
}
_numberOfParticles = numberOfParticles;
return _numberOfParticles;
}
/**
* Get particle stream width
*
* @param platform platform
*
* @return particle stream width
*
*/
int BrookCommon::getParticleStreamWidth( const Platform& platform ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCommon::getParticleStreamWidth";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
// get particle stream width
if( _particleStreamWidth < 0 ){
_getParticleStreamDimensions( platform );
}
return _particleStreamWidth;
}
/**
* Get particle stream width
*
* @return particle stream width
*
*/
int BrookCommon::getParticleStreamWidth( void ) const {
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCommon::getParticleStreamWidth";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
return _particleStreamWidth;
}
/**
* Get particle stream height
*
* @param platform platform
*
* @return particle stream height
*
*/
int BrookCommon::getParticleStreamHeight( const Platform& platform ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCommon::getParticleStreamHeight";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
// get particle stream height
if( _particleStreamHeight < 0 ){
_getParticleStreamDimensions( platform );
}
return _particleStreamHeight;
}
/**
* Get particle stream height
*
* @return particle stream height
*
*/
int BrookCommon::getParticleStreamHeight( void ) const {
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCommon::getParticleStreamHeight";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
return _particleStreamHeight;
}
/**
* Get particle stream size
*
* @param platform platform
*
* @return particle stream size
*
*/
int BrookCommon::getParticleStreamSize( const Platform& platform ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCommon::getParticleStreamSize";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
// get particle stream size
if( _particleStreamSize < 0 ){
_getParticleStreamDimensions( platform );
}
return _particleStreamSize;
}
/**
* Get particle stream size
*
* @return particle stream size
*
*/
int BrookCommon::getParticleStreamSize( void ) const {
return _particleStreamSize;
}
/**
* Get particle stream dimensions
*
* @param platform platform
*
*/
void BrookCommon::_getParticleStreamDimensions( const Platform& platform ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookCommon::_getParticleStreamDimensions";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
// get particle stream size
const BrookPlatform& brookPlatform = dynamic_cast<const BrookPlatform&> (platform);
const BrookStreamFactory& brookStreamFactory = dynamic_cast<const BrookStreamFactory&> (platform.getDefaultStreamFactory() );
_particleStreamWidth = brookStreamFactory.getDefaultParticleStreamWidth();
_particleStreamSize = brookPlatform.getStreamSize( getNumberOfParticles(), _particleStreamWidth, NULL );
_particleStreamHeight = (int) ( ((float) _particleStreamSize)/( (float) _particleStreamWidth) + 0.001);
return;
}
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* BrookCommon::getLog( void ) const {
return _log;
}
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int BrookCommon::setLog( FILE* log ){
_log = log;
return BrookCommon::DefaultReturnValue;
}
/**
* Get flag signalling whether active
*
* @return flag signalling whether active
*
*/
int BrookCommon::isActive( void ) const {
return _isActive;
}
/**
* Set flag signalling whether active
*
* @param flag signalling whether active
*
* @return DefaultReturnValue
*
*/
int BrookCommon::setIsActive( int isActive ){
_isActive= isActive;
return BrookCommon::DefaultReturnValue;
}
/*
* Get contents of object
*
* @param tab tab
* @param description description
* @param value value
*
* @return string containing contents
*
* */
std::string BrookCommon::_getLine( const std::string& tab, const std::string& description, const std::string& value ) const {
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookCommon::_getLine";
static const unsigned int MAX_LINE_CHARS = 256;
char line[MAX_LINE_CHARS];
// ---------------------------------------------------------------------------------------
std::stringstream message;
memset( line, ' ', MAX_LINE_CHARS );
#ifdef _MSC_VER
(void) sprintf_s( line, MAX_LINE_CHARS, "%s %-40s %s", tab.c_str(), description.c_str(), value.c_str() );
#else
(void) sprintf( line, "%s %-40s %s", tab.c_str(), description.c_str(), value.c_str() );
#endif
message << std::string( line ) << std::endl;
return message.str();
}
/*
* Given number of stream elements and width, returns the appropriate
* height of the stream
*
* @param streamSize stream size
* @param width stream width
*
* @return stream height
*
*/
int BrookCommon::getStreamHeight( int streamSize, int streamWidth ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCommon::getStreamHeight";
// ---------------------------------------------------------------------------------------
int streamHeight = streamSize/streamWidth;
if( streamSize % streamWidth ){
streamHeight++;
}
return streamHeight;
}
/*
* Given number of stream elements, get stream width & height
*
* @param streamSize stream size
* @param streamWidth output stream width
* @param streamHeight output stream height
*
* @return stream height
*
*/
void BrookCommon::getStreamDimensions( int streamSize, int *streamWidth, int *streamHeight ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCommon::getStreamDimensions";
// ---------------------------------------------------------------------------------------
// There are two conditions - stream should be as square
// as possible, but should also be multiple of 16 along
// one dimension
float s = sqrtf( (float) streamSize );
// find nearest multiple of 16 to the perfect square size
int low = ( (int) floor( s/16.0f ) ) * 16;
if ( !low ) {
*streamWidth = 16;
*streamHeight = getStreamHeight( streamSize, *streamWidth );
} else {
int high = low + 1;
// I'm not sure 48 is such a good stream width. Things seem
// to be faster with 32 or 64. Can make this a special
// case later.
// Choose low or high depending on which one is
// more square
int htlow = getStreamHeight( streamSize, low );
int hthigh = getStreamHeight( streamSize, high );
if ( abs( htlow - low ) < abs( hthigh - high ) ) {
*streamWidth = low;
*streamHeight = htlow;
} else {
*streamWidth = high;
*streamHeight = hthigh;
}
}
return;
}
/*
* Allocate array
*
* @param length length of array
* @param width width of array
*
* @return ptr to array
*
*/
RealOpenMM** BrookCommon::allocateRealArray( int length, int width ) const {
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCommon::allocateRealArray";
// ---------------------------------------------------------------------------------------
RealOpenMM** array = new RealOpenMM*[length];
RealOpenMM* buffer = new RealOpenMM[length*width];
for( int ii = 0; ii < length; ii++ ){
array[ii] = buffer;
buffer += width;
}
return array;
}
/*
* Free array
*
* @param array array to be freed (assumed allocated using BrookCommon::allocateRealArray
*
* @return DefaultReturnValue
*
*/
int BrookCommon::disposeRealArray( RealOpenMM** array ) const {
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCommon::disposeRealArray";
// ---------------------------------------------------------------------------------------
delete[] array[0];
delete[] array;
return DefaultReturnValue;
}
/*
* Copy 1D BrookOpenMMFloat* array to 2D array of RealOpenMM
*
* @param length length of array
* @param width width of array
* @param array1D array to copy
*
* @return ptr to array
*
*/
RealOpenMM** BrookCommon::copy1DArrayTo2DArray( int length, int width, BrookOpenMMFloat* array1D ) const {
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookCommon::copy1DArrayTo2DArray";
// ---------------------------------------------------------------------------------------
RealOpenMM** array = allocateRealArray( length, width );
int index = 0;
for( int ii = 0; ii < length; ii++ ){
for( int jj = 0; jj < width; jj++ ){
array[ii][jj] = static_cast<RealOpenMM> (array1D[index++]);
}
}
return array;
}
#ifndef OPENMM_BROOK_COMMON_H_
#define OPENMM_BROOK_COMMON_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include <vector>
#include <set>
#include "BrookFloatStreamInternal.h"
#include "BrookIntStreamInternal.h"
#include "BrookPlatform.h"
namespace OpenMM {
/**
* This kernel is invoked by NonbondedForce to calculate the forces acting on the system.
*/
class BrookCommon {
public:
// return values
static const int DefaultReturnValue = 0;
static const int ErrorReturnValue = -1;
// ---------------------------------------------------------------------------------------
// Stream names
// bonded stream names
static const std::string BondedParticleIndicesStream;
static const std::string BondedParametersStream;
static const std::string UnrolledForceStream;
static const std::string BondedChargeStream;
static const std::string BondedInverseMapStreams;
// nonbonded stream names
static const std::string NonBondedExclusionStream;
static const std::string OuterVdwStream;
static const std::string InnerSigmaStream;
static const std::string InnerEpsilonStream;
static const std::string NonBondedChargeStream;
static const std::string PartialForceStream;
// OBC Gbsa streams
static const std::string ObcParticleRadiiStream;
static const std::string ObcScaledParticleRadiiStream;
static const std::string ObcParticleRadiiWithDielectricOffsetStream;
static const std::string ObcBornRadiiStream;
static const std::string ObcBornRadii2Stream;
static const std::string ObcIntermediateForceStream;
static const std::string ObcChainStream;
// Stochastic Dynamics streams
static const std::string SDPC1Stream;
static const std::string SDPC2Stream;
static const std::string SD2XStream;
static const std::string SD1VStream;
static const std::string VPrimeStream;
static const std::string XPrimeStream;
static const std::string InverseMassStream;
// Shake streams
static const std::string ShakeParticleIndicesStream;
static const std::string ShakeParticleParameterStream;
static const std::string ShakeXCons0Stream;
static const std::string ShakeXCons1Stream;
static const std::string ShakeXCons2Stream;
static const std::string ShakeXCons3Stream;
static const std::string ShakeInverseMapStream;
// Random number generator streams
static const std::string ShuffleStream;
static const std::string RandomValuesStream;
// BrookVelocityCenterOfMassRemoval streams
static const std::string BrookVelocityCenterOfMassRemovalWorkStream;
static const std::string BrookVelocityCenterOfMassRemovalMassStream;
// ---------------------------------------------------------------------------------------
/**
* Constructor
*
*/
BrookCommon( );
/**
* Destructor
*
*/
~BrookCommon();
/**
* Return number of particles
*
* @return number of particles
*
*/
int getNumberOfParticles( void ) const;
/**
* Get particle ceiling parameter
*
* @return particle ceiling parameter
*
*/
int getParticleSizeCeiling( void ) const;
/**
* Get particle stream width
*
* @param platform platform reference
*
* @return particle stream width
*/
int getParticleStreamWidth( const Platform& platform );
/**
* Get particle stream width
*
* @return particle stream width
*/
int getParticleStreamWidth( void ) const;
/**
* Get particle stream height
*
* @param platform platform reference
*
* @return particle stream height
*/
int getParticleStreamHeight( const Platform& platform );
/**
* Get particle stream height
*
* @return particle stream height
*/
int getParticleStreamHeight( void ) const;
/**
* Get particle stream size
*
* @param platform platform reference
*
* @return particle stream size
*/
int getParticleStreamSize( const Platform& platform );
/**
* Get particle stream size
*
* @return particle stream size
*/
int getParticleStreamSize( void ) const;
/**
* Get flag signalling whether active
*
* @return flag signalling whether active
*/
int isActive( void ) const;
/**
* Set flag signalling whether active
*
* @param isActive flag signalling whether active
*
* @return DefaultReturnValue
*/
int setIsActive( int isActive );
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int setLog( FILE* log );
/*
* Get contents of object
*
* @param level of dump
*
* @return string containing contents
*
* */
std::string getContents( int level ) const;
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* getLog( void ) const;
/*
* Given number of stream elements and width, returns the appropriate
* height of the stream
*
* @param streamSize stream size
* @param width stream width
*
* @return stream height
*
*/
static int getStreamHeight( int streamSize, int streamWidth );
/*
* Given number of stream elements, get stream width & height
*
* @param streamSize stream size
* @param streamWidth output stream width
* @param streamHeight output stream height
*
* @return stream height
*
*/
static void getStreamDimensions( int streamSize, int *streamWidth, int *streamHeight );
/*
* Allocate array
*
* @param length length of array
* @param width width of array
*
* @return ptr to array
*
*/
RealOpenMM** allocateRealArray( int length, int width ) const;
/*
* Free array
*
* @param array array to be freed (assumed allocated using BrookCommon::allocateRealArray
*
* @return DefaultReturnValue
*
*/
int disposeRealArray( RealOpenMM** array ) const;
/*
* Copy 1D BrookOpenMMFloat* array to 2D array of RealOpenMM
*
* @param length length of array
* @param width width of array
* @param array1D array to copy
*
* @return ptr to array
*
*/
RealOpenMM** copy1DArrayTo2DArray( int length, int width, BrookOpenMMFloat* array1D ) const;
protected:
// number of particles
int _numberOfParticles;
// particle stream dimensions
int _particleStreamWidth;
int _particleStreamHeight;
int _particleStreamSize;
// particle size mod
int _particleSizeModified;
// log file reference
FILE* _log;
// active flag
int _isActive;
/**
* Set number of particles
*
* @param numberOfParticles number of particles
*
*/
int setNumberOfParticles( int numberOfParticles );
/**
* Get particle stream dimensions
*
* @param platform platform
*
*/
void _getParticleStreamDimensions( const Platform& platform );
/*
* Get line
*
* @param tab tab
* @param description description
* @param value value
*
* @return string containing contents
*
* */
std::string _getLine( const std::string& tab, const std::string& description, const std::string& value ) const;
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_COMMON_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookFloatStreamInternal.h"
#include "BrookPlatform.h"
#include "openmm/OpenMMException.h"
#include <sstream>
using namespace OpenMM;
/**
* BrookFloatStreamInternal constructor
*
* @param name stream name
* @param size stream size
* @param type stream type (float, float2, ...)
* @param platform platform
* @param inputStreamWidth stream width
* @param inputDefaultDangleValue default dangle value
*
* @throw exception if stream type not recognized or stream width < 1
*
*/
BrookFloatStreamInternal::BrookFloatStreamInternal( const std::string& name, int size, int streamWidth, BrookStreamInternal::DataType type,
double inputDefaultDangleValue ) : BrookStreamInternal( name, size, streamWidth, type ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookFloatStreamInternal::BrookFloatStreamInternal";
// ---------------------------------------------------------------------------------------
//fprintf( stderr,"%s %s\n", methodName.c_str(), getName().c_str() );
//fflush( stderr );
// set base type (currently only FLOAT supported)
switch( type ){
case BrookStreamInternal::Float:
case BrookStreamInternal::Float2:
case BrookStreamInternal::Float3:
case BrookStreamInternal::Float4:
_baseType = BrookStreamInternal::Float;
break;
case BrookStreamInternal::Double:
case BrookStreamInternal::Double2:
case BrookStreamInternal::Double3:
case BrookStreamInternal::Double4:
_baseType = BrookStreamInternal::Double;
break;
default:
std::stringstream message;
message << methodName << " stream=" << name << " input type=" << type << " not recognized.";
throw OpenMMException( message.str() );
break;
}
// set _width (FLOAT, FLOAT2, ... )
switch( type ){
case BrookStreamInternal::Float:
case BrookStreamInternal::Double:
_width = 1;
break;
case BrookStreamInternal::Float2:
case BrookStreamInternal::Double2:
_width = 2;
break;
case BrookStreamInternal::Float3:
case BrookStreamInternal::Double3:
_width = 3;
break;
case BrookStreamInternal::Float4:
case BrookStreamInternal::Double4:
_width = 4;
break;
}
_defaultDangleValue = (float) inputDefaultDangleValue;
// set stream height based on specified stream _width
if( streamWidth < 1 ){
std::stringstream message;
message << methodName << " stream=" << name << " input stream width=" << streamWidth << " is less than 1.";
throw OpenMMException( message.str() );
}
// create Brook stream handle
switch( _width ){
case 1:
_aStream = brook::stream::create<float>( _streamHeight, _streamWidth );
break;
case 2:
_aStream = brook::stream::create<float2>( _streamHeight, _streamWidth );
break;
case 3:
_aStream = brook::stream::create<float3>( _streamHeight, _streamWidth );
break;
case 4:
_aStream = brook::stream::create<float4>( _streamHeight, _streamWidth );
break;
}
int streamSize = getStreamSize();
// allocate memory for data buffer
_data = new float[streamSize*_width];
//printf( "%s %s data=%u stream=%d [%d %d] width=%d\n", methodName.c_str(), getName().c_str(), (unsigned int) _data, streamSize, _streamHeight, _streamWidth, _width );
//fflush( stdout );
}
/**
* BrookFloatStreamInternal destructor
*
*/
BrookFloatStreamInternal::~BrookFloatStreamInternal( ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookFloatStreamInternal::~BrookFloatStreamInternal";
// ---------------------------------------------------------------------------------------
//printf( "%s %s data=%u stream=%d [%d %d] width=%d\n", methodName.c_str(), getName().c_str(), (unsigned int) _data, getStreamSize(), _streamHeight, _streamWidth, _width );
//fflush( stdout );
delete[] _data;
}
/**
* Get dangle value
*
* @return dangle value
*/
double BrookFloatStreamInternal::getDangleValue( void ) const {
return _defaultDangleValue;
}
/**
* Load data from input array
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct _data type for this stream. If the stream has a compound _data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*
* @throw exception if baseType not recognized
*
*/
void BrookFloatStreamInternal::loadFromArray( const void* array ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookFloatStreamInternal::loadFromArray";
// ---------------------------------------------------------------------------------------
return loadFromArray( array, getBaseDataType() );
}
/**
* Load data from input array
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct _data type for this stream. If the stream has a compound _data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*
* @throw exception if baseType not float, double, or integer
*
*/
void BrookFloatStreamInternal::loadFromArray( const void* array, BrookStreamInternal::DataType baseType ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookFloatStreamInternal::loadFromArray";
// ---------------------------------------------------------------------------------------
int totalSize = getSize()*getWidth();
//int totalSize = getSize();
/*
fprintf( stderr, "%s %s data=%p stream=%d [%d %d] width=%d type=%d\n",
methodName.c_str(), getName().c_str(), _data, getStreamSize(), _streamHeight, _streamWidth, _width, baseType );
fflush( stderr );
*/
if( baseType == BrookStreamInternal::Float ){
memcpy( _data, array, sizeof( float )*totalSize );
/*
float* arrayData = (float*) array;
for( int ii = 0; ii < totalSize; ii++ ){
_data[ii] = (BrookOpenMMFloat) arrayData[ii];
}
*/
} else if( baseType == BrookStreamInternal::Double ){
double* arrayData = (double*) array;
for( int ii = 0; ii < totalSize; ii++ ){
_data[ii] = (BrookOpenMMFloat) arrayData[ii];
}
} else if( baseType == BrookStreamInternal::Integer ){
int* arrayData = (int*) array;
for( int ii = 0; ii < totalSize; ii++ ){
_data[ii] = (BrookOpenMMFloat) arrayData[ii];
}
} else {
std::stringstream message;
message << methodName << " stream=" << getName() << " base type=" << getTypeString( baseType ) << " not recognized.";
throw OpenMMException( message.str() );
}
// set dangling values
_loadDanglingValues();
// write to GPU
_aStream.read( _data );
}
/**
* Save data to input array
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct _data type for this stream. If the stream has a compound _data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*
* @throw exception if baseType not float, double, or integer
*
*/
void BrookFloatStreamInternal::saveToArray( void* array ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookFloatStreamInternal::saveToArray";
// ---------------------------------------------------------------------------------------
// get _data from GPU
_aStream.write( _data );
// load into array
int totalSize = getSize()*getWidth();
BrookStreamInternal::DataType baseType = getBaseDataType();
if( baseType == BrookStreamInternal::Float ){
//printf( "%s Basetype is float\n", methodName.c_str() );
//fflush( stdout );
memcpy( array, _data, sizeof( float )*totalSize );
/*
float* arrayData = (float*) array;
for( int ii = 0; ii < totalSize; ii++ ){
arrayData[ii] = (float) _data[ii];
}
*/
} else if( baseType == BrookStreamInternal::Double ){
//printf( "%s Basetype is double\n", methodName.c_str() );
//fflush( stdout );
double* arrayData = (double*) array;
for( int ii = 0; ii < totalSize; ii++ ){
arrayData[ii] = (double) _data[ii];
}
} else if( baseType == BrookStreamInternal::Integer ){
//printf( "%s Basetype is int\n", methodName.c_str() );
//fflush( stdout );
int* arrayData = (int*) array;
for( int ii = 0; ii < totalSize; ii++ ){
arrayData[ii] = (int) _data[ii];
}
} else {
std::stringstream message;
message << methodName << " stream=" << getName() << " base type=" << getTypeString( baseType ) << " not recognized.";
throw OpenMMException( message.str() );
}
}
/**
* Fill stream w/ specified value
*
* @param value value to fill stream w/
*
*/
void BrookFloatStreamInternal::fillWithValue( void* value ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookFloatStreamInternal::fillWithValue";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
BrookOpenMMFloat valueData;
if( _baseType == BrookStreamInternal::Float) {
valueData = (BrookOpenMMFloat) *((float*) value);
} else {
valueData = (BrookOpenMMFloat) *((double*) value);
}
//memset( _data, valueData, sizeof( float )*getSize()*getWidth() );
int totalSize = getSize()*getWidth();
for( int ii = 0; ii < totalSize; ii++ ){
_data[ii] = valueData;
}
_loadDanglingValues();
_aStream.read( _data );
}
/**
* Get data
*
* @param readFromBoard if set, read values on board
*
* @return data array
*
*/
void* BrookFloatStreamInternal::getData( int readFromBoard ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookFloatStreamInternal::getData";
// ---------------------------------------------------------------------------------------
if( readFromBoard ){
_aStream.write( _data );
}
return (void*) _data;
}
/**
* Get data
*
* @return data array
*
*/
void* BrookFloatStreamInternal::getData( void ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookFloatStreamInternal::getData";
// ---------------------------------------------------------------------------------------
return getData( 0 );
}
/**
* Load dangling value into stream
*
* @param danglingValue dangling value to load
*
*/
void BrookFloatStreamInternal::_loadDanglingValues( float danglingValue ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookFloatStreamInternal::_loadDanglingValues";
// ---------------------------------------------------------------------------------------
int width = getWidth();
int arraySize = getSize()*width;
int streamSize = getStreamSize()*width;
//printf( "%s array=%d stream=%d width=%d %s\n", methodName.c_str(), arraySize, streamSize, width, getName().c_str() );
//fflush( stdout );
if( arraySize < streamSize ){
for( int ii = arraySize; ii < streamSize; ii++ ){
_data[ii] = danglingValue;
}
}
}
/**
* Load default dangling value into stream
*
*/
void BrookFloatStreamInternal::_loadDanglingValues( void ){
_loadDanglingValues( _defaultDangleValue );
}
/*
* Get contents of object
*
* @param level level of dump
*
* @return string containing contents
*
* */
const std::string BrookFloatStreamInternal::getContentsString( int level ) const {
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookFloatStreamInternal::getContentsString";
static const unsigned int MAX_LINE_CHARS = 256;
char value[MAX_LINE_CHARS];
//static const char* Set = "Set";
//static const char* NotSet = "Not set";
// ---------------------------------------------------------------------------------------
std::stringstream message;
std::string tab = " ";
#ifdef _MSC_VER
#define LOCAL_SPRINTF(a,b,c) sprintf_s( (a), MAX_LINE_CHARS, (b), (c) );
#else
#define LOCAL_SPRINTF(a,b,c) sprintf( (a), (b), (c) );
#endif
(void) LOCAL_SPRINTF( value, "%s", getName().c_str() );
message << _getLine( tab, "Name:", value );
(void) LOCAL_SPRINTF( value, "%d", getWidth() );
message << _getLine( tab, "Width:", value );
(void) LOCAL_SPRINTF( value, "%d", getStreamSize() );
message << _getLine( tab, "Stream size:", value );
(void) LOCAL_SPRINTF( value, "%d", getStreamWidth() );
message << _getLine( tab, "Stream width:", value );
(void) LOCAL_SPRINTF( value, "%d", getStreamHeight() );
message << _getLine( tab, "Stream height:", value );
(void) LOCAL_SPRINTF( value, "%3e", getDangleValue() );
message << _getLine( tab, "Dangle value:", value );
return message.str();
}
/*
* Print array contents of object to file
*
* @param log file to print to
*
* @return DefaultReturnValue
*
* */
int BrookFloatStreamInternal::_bodyPrintToFile( FILE* log, int maxPrint ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookStreamInternal::_bodyPrintToFile";
static const unsigned int MAX_LINE_CHARS = 256;
char value[MAX_LINE_CHARS];
// ---------------------------------------------------------------------------------------
assert( log );
void* dataArrayV = getData( 1 );
#ifdef _MSC_VER
#define LOCAL_SPRINTF(a,b,c) sprintf_s( (a), MAX_LINE_CHARS, (b), (c) );
#else
#define LOCAL_SPRINTF(a,b,c) sprintf( (a), (b), (c) );
#endif
int streamSize = getStreamSize();
int width = getWidth();
int index = 0;
maxPrint = maxPrint < 0 ? streamSize : maxPrint;
maxPrint *= width;
const float* dataArray = (float*) dataArrayV;
for( int ii = 0; ii < streamSize && ii < maxPrint; ii++ ){
std::stringstream message;
(void) LOCAL_SPRINTF( value, "%6d ", ii );
message << value << " [ ";
for( int jj = 0; jj < width; jj++ ){
(void) LOCAL_SPRINTF( value, "%16.7e ", dataArray[index++] );
message << value;
}
message << "]\n";
if( index == (_size+1)*width ){
(void) fprintf( log, "\n" );
}
(void) fprintf( log, "%s", message.str().c_str() );
}
return DefaultReturnValue;
}
/*
* Get stats
*
* @return statistics vector
*
* */
int BrookFloatStreamInternal::getStatistics( std::vector<std::vector<double> >& statistics, int maxScan ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookStreamInternal::getStatistics";
static const int MinIndex = 4;
static const int MinIndexIndex = 5;
static const int MaxIndex = 6;
static const int MaxIndexIndex = 7;
static const int CountIndex = 8;
static const int vectorSize = CountIndex + 1;
static const double bigValue = 1.0e+10;
// ---------------------------------------------------------------------------------------
void* dataArrayV = getData( 1 );
statistics.resize( vectorSize );
int streamSize = getStreamSize();
int width = getWidth();
int index = 0;
const float* dataArray = (float*) dataArrayV;
for( int ii = 0; ii < vectorSize; ii++ ){
for( int jj = 0; jj < width; jj++ ){
if( ii == MinIndex ){
statistics[ii].push_back( bigValue );
} else if( ii == MaxIndex ){
statistics[ii].push_back( -bigValue );
} else {
statistics[ii].push_back( 0.0 );
}
}
}
for( int ii = 0; ii < streamSize && ii < maxScan; ii++ ){
for( int jj = 0; jj < width; jj++ ){
double value = (double) dataArray[index++];
statistics[0][jj] += value;
statistics[1][jj] += value*value;
statistics[2][jj] += fabs( value );
statistics[CountIndex][jj] += 1.0;
if( value < statistics[MinIndex][jj] ){
statistics[MinIndex][jj] = value;
statistics[MinIndexIndex][jj] = ii;
}
if( value > statistics[MaxIndex][jj] ){
statistics[MaxIndex][jj] = value;
statistics[MaxIndexIndex][jj] = ii;
}
}
}
for( int jj = 0; jj < width; jj++ ){
if( statistics[CountIndex][jj] > 0.0 ){
statistics[3][jj] = statistics[0][jj];
statistics[0][jj] /= statistics[CountIndex][jj];
statistics[2][jj] /= statistics[CountIndex][jj];
statistics[1][jj] = statistics[1][jj] - statistics[0][jj]*statistics[0][jj]*statistics[CountIndex][jj];
if( statistics[CountIndex][jj] > 1.0 ){
statistics[1][jj] = sqrt( statistics[1][jj]/( statistics[CountIndex][jj] - 1.0 ) );
}
}
}
return DefaultReturnValue;
}
/**
* Get array of appropritate size for loading data
*
* @return data array -- user's responsibility to free
*/
void* BrookFloatStreamInternal::getDataArray( void ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookStreamInternal::getDataArray";
// ---------------------------------------------------------------------------------------
int totalSize = getStreamSize()*getWidth();
BrookStreamInternal::DataType baseType = getBaseDataType();
if( baseType == Double || baseType == Double2 || baseType == Double3 || baseType == Double4 ){
totalSize *= 2;
}
return new float[totalSize];
}
/**
* BrookFloatStreamInternal constructor
*
* @param stopIndex index to stop sum
* @param sum array of size=getWidth()
*
* @return DefaultReturnValue
*
* @throw exception if stopIndex is too large
*/
int BrookFloatStreamInternal::sumByDimension( int stopIndex, double* sum ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookFloatStreamInternal::sumByDimension";
// ---------------------------------------------------------------------------------------
if( stopIndex > getSize() ){
std::stringstream message;
message << methodName << " stream=" << getName() << " input topIndex" << stopIndex << " is too large: stream size=" << getSize();
throw OpenMMException( message.str() );
}
// get _data from GPU
_aStream.write( _data );
int width = getWidth();
int widthM1 = getWidth() - 1;
stopIndex *= width;
for( int ii = 0; ii < width; ii++ ){
sum[ii] = 0.0;
}
int index = 0;
for( int ii = 0; ii < stopIndex; ii++ ){
sum[index] += (double) _data[ii];
if( index == widthM1 ){
index = 0;
} else {
index++;
}
}
return DefaultReturnValue;
}
#ifndef OPENMM_BROOK_FLOAT_STREAM_INTERNAL_H_
#define OPENMM_BROOK_FLOAT_STREAM_INTERNAL_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookPlatform.h"
#include "BrookStreamInternal.h"
#include "../../reference/src/SimTKUtilities/SimTKOpenMMRealType.h"
namespace OpenMM {
/**
* This is the implementation of Float and Double streams in the Brook Platform.
*/
class BrookFloatStreamInternal : public BrookStreamInternal {
public:
/**
* BrookFloatStreamInternal constructor
*
* @param name stream name
* @param size size of array
* @param streamWidth stream width
* @param type stream type (float, float2, ...)
* @param inputDefaultDangleValue default dangle value
*
*/
BrookFloatStreamInternal( const std::string& name, int size, int inputStreamWidth, BrookStreamInternal::DataType type, double defaultDangleValue = 0.0 );
/**
* BrookFloatStreamInternal destructor
*
*/
~BrookFloatStreamInternal( );
/**
* Load data from input array
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct _data type for this stream. If the stream has a compound _data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*
* @throw exception if baseType not float or double
*
*/
void loadFromArray( const void* array );
/**
* Copy the contents of an array into this stream.
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct data type for this stream. If the stream has a compound data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*/
void loadFromArray( const void* array, BrookStreamInternal::DataType baseType );
/**
* Save data to input array
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct _data type for this stream. If the stream has a compound _data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*
* @throw exception if baseType not float or double
*
*/
void saveToArray( void* array );
/**
* Fill data w/ input value
*
* @param value to set array to
*
*
*/
void fillWithValue( void* value );
/**
* Get data array -- no read from board!
*
* @return data array
*/
void* getData( void );
/**
* Get data array
*
* @param readFromBoard if set, read values on board
*
* @return data array
*/
void* getData( int readFromBoard );
/**
* Get array of appropritate size for loading data
*
* @return data array -- user's responsibility to free
*/
void* getDataArray( void );
/**
* Get dangle value
*
* @return dangle value
*/
double getDangleValue( void ) const;
/*
* Get contents of object
*
*
* @param level level of dump
*
* @return string containing contents
*
* */
const std::string getContentsString( int level = 0 ) const;
/**
* Sum over stream dimensions
*
* @param stopIndex index to stop sum
* @param sum array of size=getWidth()
*
* @return DefaultReturnValue
*
* @throw exception if stopIndex is too large
*/
int sumByDimension( int stopIndex, double* sum );
/*
* Get stats
*
* @return statistics vector
*
* */
int getStatistics( std::vector<std::vector<double>>&, int maxScan );
private:
BrookOpenMMFloat _defaultDangleValue;
float* _data;
RealOpenMM* _realOpenMMData;
void _loadDanglingValues( void );
void _loadDanglingValues( float );
/*
* Print array to file
*
* @param log log file
*
* @return DefaultReturnValue
*
* */
int _bodyPrintToFile( FILE* log, int maxPrint );
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_FLOAT_STREAM_INTERNAL_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookGbsa.h"
#include "BrookPlatform.h"
#include "openmm/OpenMMException.h"
#include "BrookStreamImpl.h"
#include "kernels/kgbsa.h"
#include "kernels/kforce.h"
#include <sstream>
using namespace OpenMM;
using namespace std;
/**
* Constructor
*
*/
BrookGbsa::BrookGbsa( ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookGbsa::BrookGbsa";
// ---------------------------------------------------------------------------------------
_particleSizeCeiling = -1;
_outerUnroll = 4;
_innerUnroll = 4;
_partialForceStreamWidth = 64;
_partialForceStreamHeight = -1;
_partialForceStreamSize = -1;
_gbsaParticleStreamWidth = -1;
_gbsaParticleStreamHeight = -1;
_gbsaParticleStreamSize = -1;
_duplicationFactor = 4;
_includeAce = 1;
_solventDielectric = 78.3;
_soluteDielectric = 1.0;
_dielectricOffset = 0.009;
for( int ii = 0; ii < LastStreamIndex; ii++ ){
_gbsaStreams[ii] = NULL;
}
for( int ii = 0; ii < getNumberOfForceStreams(); ii++ ){
_gbsaForceStreams[ii] = NULL;
}
_bornRadiiInitialized = 0;
//_cpuObc = NULL;
}
/**
* Destructor
*
*/
BrookGbsa::~BrookGbsa( ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookGbsa::~BrookGbsa";
// ---------------------------------------------------------------------------------------
for( int ii = 0; ii < LastStreamIndex; ii++ ){
delete _gbsaStreams[ii];
}
for( int ii = 0; ii < getNumberOfForceStreams(); ii++ ){
delete _gbsaForceStreams[ii];
}
//delete _cpuObc;
}
/**
* Get number of force streams
*
* @return number of force streams (fixed value)
*
*/
int BrookGbsa::getNumberOfForceStreams( void ) const {
return NumberOfForceStreams;
}
/**
* Include ACE approximation in calculation of force
*
* @return true if ACE approximation is to be included in calculation of force
*
*/
int BrookGbsa::includeAce( void ) const {
return _includeAce;
}
/**
* Get inner loop unroll
*
* @return inner loop unroll (fixed value)
*
*/
int BrookGbsa::getInnerLoopUnroll( void ) const {
return _innerUnroll;
}
/**
* Get outer loop unroll
*
* @return outer loop unroll (fixed value)
*
*/
int BrookGbsa::getOuterLoopUnroll( void ) const {
return _outerUnroll;
}
/**
* Get solute dielectric
*
* @return solute dielectric
*
*/
float BrookGbsa::getSoluteDielectric( void ) const {
return (float) _soluteDielectric;
}
/**
* Get solvent dielectric
*
* @return solvent dielectric
*
*/
float BrookGbsa::getSolventDielectric( void ) const {
return (float) _solventDielectric;
}
/**
* Get OBC dielectric offset
*
* @return OBC dielectric offset
*
*/
float BrookGbsa::getDielectricOffset( void ) const {
return (float) _dielectricOffset;
}
/**
* Set duplication factor
*
* @param duplication factor
*
* @return DefaultReturnValue
*
*/
int BrookGbsa::setDuplicationFactor( int duplicationFactor ){
_duplicationFactor = duplicationFactor;
return DefaultReturnValue;
}
/**
* Set outer loop unroll
*
* @param outer loop unroll (fixed value)
*
* @return updated outer loop unroll (fixed value)
*
*/
int BrookGbsa::setOuterLoopUnroll( int outerUnroll ){
if( outerUnroll != _outerUnroll ){
_particleSizeCeiling = -1;
}
_outerUnroll = _outerUnroll;
return _outerUnroll;
}
/**
* Get particle ceiling parameter
*
* @return particle ceiling parameter
*
*/
int BrookGbsa::getParticleSizeCeiling( void ) const {
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookGbsa::getParticleSizeCeiling";
// ---------------------------------------------------------------------------------------
if( _particleSizeCeiling < 0 ){
BrookGbsa* localThis = const_cast<BrookGbsa* const>(this);
localThis->_particleSizeCeiling = localThis->getNumberOfParticles() % localThis->getOuterLoopUnroll();
if( localThis->_particleSizeCeiling ){
localThis->_particleSizeCeiling = localThis->getOuterLoopUnroll() - localThis->_particleSizeCeiling;
}
localThis->_particleSizeCeiling += localThis->getNumberOfParticles();
}
return _particleSizeCeiling;
}
/**
* Get duplication factor
*
* @return duplication factor
*
*/
int BrookGbsa::getDuplicationFactor( void ) const {
return _duplicationFactor;
}
/**
* Get partial force stream width
*
* @return partial force stream width
*
*/
int BrookGbsa::getPartialForceStreamWidth( void ) const {
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookGbsa::getPartialForceStreamWidth";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
return _partialForceStreamWidth;
}
/**
* Get partial force stream height
*
* @return partial force stream height
*
*/
int BrookGbsa::getPartialForceStreamHeight( void ) const {
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookGbsa::getPartialForceStreamHeight";
// ---------------------------------------------------------------------------------------
return _partialForceStreamHeight;
}
/**
* Get partial force stream size
*
* @return partial force stream size
*
*/
int BrookGbsa::getPartialForceStreamSize( void ) const {
return _partialForceStreamSize;
}
/**
* Get Particle stream size
*
* @return Particle stream size
*
*/
int BrookGbsa::getGbsaParticleStreamSize( void ) const {
return _gbsaParticleStreamSize;
}
/**
* Get particle stream width
*
* @return particle stream width
*
*/
int BrookGbsa::getGbsaParticleStreamWidth( void ) const {
return _gbsaParticleStreamWidth;
}
/**
* Get particle stream height
*
* @return particle stream height
*/
int BrookGbsa::getGbsaParticleStreamHeight( void ) const {
return _gbsaParticleStreamHeight;
}
/**
* Get Obc particle radii stream
*
* @return Obc particle radii stream
*
*/
BrookFloatStreamInternal* BrookGbsa::getObcParticleRadii( void ) const {
return _gbsaStreams[ObcParticleRadiiStream];
}
/**
* Get Obc scaled particle radii stream
*
* @return Obc scaled particle radii stream
*
*/
BrookFloatStreamInternal* BrookGbsa::getObcScaledParticleRadii( void ) const {
return _gbsaStreams[ObcScaledParticleRadiiStream];
}
/**
* Get Obc particle radii w/ dielectric offset
*
* @return Obc particle radii w/ dielectric offset
*
*/
BrookFloatStreamInternal* BrookGbsa::getObcParticleRadiiWithDielectricOffset( void ) const {
return _gbsaStreams[ObcParticleRadiiWithDielectricOffsetStream];
}
/**
* Get Obc Born radii
*
* @return Obc Born radii
*
*/
BrookFloatStreamInternal* BrookGbsa::getObcBornRadii( void ) const {
return _gbsaStreams[ObcBornRadiiStream];
}
/**
* Get Obc Born radii2
*
* @return Obc Born radii2
*
*/
BrookFloatStreamInternal* BrookGbsa::getObcBornRadii2( void ) const {
return _gbsaStreams[ObcBornRadii2Stream];
}
/**
* Get Obc intermediate force stream
*
* @return Obcintermediate force stream
*
*/
BrookFloatStreamInternal* BrookGbsa::getObcIntermediateForce( void ) const {
return _gbsaStreams[ObcIntermediateForceStream];
}
/**
* Get Obc chain stream
*
* @return Obc chain stream
*
*/
BrookFloatStreamInternal* BrookGbsa::getObcChain( void ) const {
return _gbsaStreams[ObcChainStream];
}
/**
* Get force streams
*
* @return force streams
*
*/
BrookFloatStreamInternal** BrookGbsa::getForceStreams( void ){
return _gbsaForceStreams;
}
/**
* Return true if force[index] stream is set
*
* @param index into force stream
* @return true if index is valid && force[index] stream is set; else false
*
*/
int BrookGbsa::isForceStreamSet( int index ) const {
return (index >= 0 && index < getNumberOfForceStreams() && _gbsaForceStreams[index]) ? 1 : 0;
}
/**
* Return true if Born radii have been initialized
*
* @return true if Born radii have been initialized
*
*/
int BrookGbsa::haveBornRadiiBeenInitialized( void ) const {
return _bornRadiiInitialized;
}
/**
* Calculate Born radii
*
* @return calculate Born radii
*
*/
/*
int BrookGbsa::calculateBornRadii( const Stream& positions ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookGbsa::calculateBornRadii";
static const int printOn = 0;
// ---------------------------------------------------------------------------------------
const BrookStreamImpl& positionStreamC = dynamic_cast<const BrookStreamImpl&> (positions.getImpl());
BrookStreamImpl& positionStream = const_cast<BrookStreamImpl&> (positionStreamC);
const RealOpenMM* coordinates = (RealOpenMM*) positionStream.getData( );
// load coordinates into RealOpenMM 2d array
int numberOfParticles = getNumberOfParticles();
RealOpenMM** particleCoordinates = new RealOpenMM*[numberOfParticles];
RealOpenMM* particleCoordinatesBlk = new RealOpenMM[3*numberOfParticles];
// Born radii array size needs to match stream size since it will
// be written down to board
int streamSize = getGbsaParticleStreamSize();
RealOpenMM* bornRadii = new RealOpenMM[streamSize];
memset( bornRadii, 0, sizeof( RealOpenMM )*streamSize );
RealOpenMM* obcChain = new RealOpenMM[streamSize];
memset( obcChain, 0, sizeof( RealOpenMM )*streamSize );
int index = 0;
RealOpenMM* particleCoordinatesBlkPtr = particleCoordinatesBlk;
for( int ii = 0; ii < numberOfParticles; ii++ ){
particleCoordinates[ii] = particleCoordinatesBlkPtr;
particleCoordinatesBlkPtr += 3;
particleCoordinates[ii][0] = coordinates[index++];
particleCoordinates[ii][1] = coordinates[index++];
particleCoordinates[ii][2] = coordinates[index++];
}
// calculate Born radii
_cpuObc->computeBornRadii( particleCoordinates, bornRadii, obcChain );
// diagnostics
if( printOn && getLog() ){
(void) fprintf( getLog(), "\n%s: atms=%d\n", methodName.c_str(), numberOfParticles );
for( int ii = 0; ii < numberOfParticles; ii++ ){
(void) fprintf( getLog(), "%d coord=[%.5e %.5e %.5e] bR=%.5e obcChain=%.6e\n", ii,
particleCoordinates[ii][0], particleCoordinates[ii][1], particleCoordinates[ii][2], bornRadii[ii], obcChain[ii] );
}
}
// write radii to board and set flag to indicate radii calculated once
_gbsaStreams[ObcBornRadiiStream]->loadFromArray( bornRadii );
_gbsaStreams[ObcChainStream]->loadFromArray( obcChain );
_bornRadiiInitialized = 1;
// free memory
delete[] particleCoordinatesBlk;
delete[] particleCoordinates;
delete[] bornRadii;
delete[] obcChain;
return DefaultReturnValue;
}
*/
/**
* Initialize stream dimensions
*
* @param numberOfParticles number of particles
* @param platform platform
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
*/
int BrookGbsa::_initializeStreamSizes( int numberOfParticles, const Platform& platform ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookGbsa::_initializeStreamSizes";
// ---------------------------------------------------------------------------------------
_gbsaParticleStreamSize = getParticleStreamSize( platform );
_gbsaParticleStreamWidth = getParticleStreamWidth( platform );
_gbsaParticleStreamHeight = getParticleStreamHeight( platform );
int innerUnroll = getInnerLoopUnroll();
if( innerUnroll < 1 ){
std::stringstream message;
message << methodName << " innerUnrolls=" << innerUnroll << " is less than 1.";
throw OpenMMException( message.str() );
return ErrorReturnValue;
}
if( _partialForceStreamWidth < 1 ){
std::stringstream message;
message << methodName << " partial force stream width=" << _partialForceStreamWidth << " is less than 1.";
throw OpenMMException( message.str() );
return ErrorReturnValue;
}
_partialForceStreamSize = _gbsaParticleStreamSize*getDuplicationFactor()/innerUnroll;
_partialForceStreamHeight = _partialForceStreamSize/_partialForceStreamWidth;
_partialForceStreamHeight += ( (_partialForceStreamSize % _partialForceStreamWidth) ? 1 : 0);
_partialForceStreamSize = _partialForceStreamHeight*_partialForceStreamWidth;
return DefaultReturnValue;
}
/**
* Initialize streams
*
* @param platform platform
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
*/
int BrookGbsa::_initializeStreams( const Platform& platform ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookGbsa::_initializeStreams";
static const double dangleValue = 0.0;
// ---------------------------------------------------------------------------------------
int gbsaParticleStreamSize = getGbsaParticleStreamSize();
int gbsaParticleStreamWidth = getGbsaParticleStreamWidth();
// particle radii & charge
_gbsaStreams[ObcParticleRadiiStream] = new BrookFloatStreamInternal( BrookCommon::ObcParticleRadiiStream,
gbsaParticleStreamSize, gbsaParticleStreamWidth,
BrookStreamInternal::Float2, dangleValue );
// scaled particle radii
_gbsaStreams[ObcScaledParticleRadiiStream] = new BrookFloatStreamInternal( BrookCommon::ObcScaledParticleRadiiStream,
gbsaParticleStreamSize, gbsaParticleStreamWidth,
BrookStreamInternal::Float2, dangleValue );
// particle radii w/ DielectricOffset
_gbsaStreams[ObcParticleRadiiWithDielectricOffsetStream] = new BrookFloatStreamInternal( BrookCommon::ObcParticleRadiiWithDielectricOffsetStream,
gbsaParticleStreamSize, gbsaParticleStreamWidth,
BrookStreamInternal::Float, dangleValue );
// Born radii
_gbsaStreams[ObcBornRadiiStream] = new BrookFloatStreamInternal( BrookCommon::ObcBornRadiiStream,
gbsaParticleStreamSize, gbsaParticleStreamWidth,
BrookStreamInternal::Float, dangleValue );
// Born2 radii
_gbsaStreams[ObcBornRadii2Stream] = new BrookFloatStreamInternal( BrookCommon::ObcBornRadii2Stream,
gbsaParticleStreamSize, gbsaParticleStreamWidth,
BrookStreamInternal::Float, dangleValue );
// IntermediateForce
_gbsaStreams[ObcIntermediateForceStream] = new BrookFloatStreamInternal( BrookCommon::ObcIntermediateForceStream,
gbsaParticleStreamSize, gbsaParticleStreamWidth,
BrookStreamInternal::Float4, dangleValue );
// Obc chain
_gbsaStreams[ObcChainStream] = new BrookFloatStreamInternal( BrookCommon::ObcChainStream,
gbsaParticleStreamSize, gbsaParticleStreamWidth,
BrookStreamInternal::Float, dangleValue );
// partial force streams
std::string partialForceStream = BrookCommon::PartialForceStream;
for( int ii = 0; ii < getNumberOfForceStreams(); ii++ ){
std::stringstream name;
name << partialForceStream << ii;
_gbsaForceStreams[ii] = new BrookFloatStreamInternal( name.str(), getPartialForceStreamSize(),
getPartialForceStreamWidth(), BrookStreamInternal::Float4, dangleValue );
}
return DefaultReturnValue;
}
/*
* Setup of Gbsa parameters
*
* @param particleParameters vector of OBC parameters [particleI][0=charge]
* [particleI][1=radius]
* [particleI][2=scaling factor]
* @param solventDielectric solvent dielectric
* @param soluteDielectric solute dielectric
* @param platform Brook platform
*
* @return nonzero value if error
*
* */
int BrookGbsa::setup( const std::vector<std::vector<double> >& vectorOfParticleParameters,
double solventDielectric, double soluteDielectric, const Platform& platform ){
// ---------------------------------------------------------------------------------------
static const int particleParametersSize = 3;
static const int maxErrors = 20;
static const std::string methodName = "BrookGbsa::setup";
// ---------------------------------------------------------------------------------------
int numberOfParticles = (int) vectorOfParticleParameters.size();
setNumberOfParticles( numberOfParticles );
_solventDielectric = solventDielectric;
_soluteDielectric = soluteDielectric;
// initialize stream sizes and then Brook streams
_initializeStreamSizes( numberOfParticles, platform );
_initializeStreams( platform );
int particleStreamSize = getGbsaParticleStreamSize();
BrookOpenMMFloat* radiiAndCharge = new BrookOpenMMFloat[particleStreamSize*2];
BrookOpenMMFloat* scaledRadiiAndOffset = new BrookOpenMMFloat[particleStreamSize*2];
memset( radiiAndCharge, 0, particleStreamSize*2*sizeof( BrookOpenMMFloat ) );
memset( scaledRadiiAndOffset, 0, particleStreamSize*2*sizeof( BrookOpenMMFloat ) );
// used by CpuObc to calculate initial Born radii
vector<RealOpenMM> particleRadii(numberOfParticles);
vector<RealOpenMM> scaleFactors(numberOfParticles);
float dielectricOffset = getDielectricOffset();
// loop over particle parameters
// track any errors and then throw exception
// check parameter vector is right size
// set parameter entries or board and arrays used by CpuObc
int vectorIndex = 0;
int errors = 0;
std::stringstream message;
typedef std::vector< std::vector<double> > VectorOfDoubleVectors;
typedef VectorOfDoubleVectors::const_iterator VectorOfDoubleVectorsCI;
for( VectorOfDoubleVectorsCI ii = vectorOfParticleParameters.begin(); ii != vectorOfParticleParameters.end(); ii++ ){
std::vector<double> particleParameters = *ii;
if( particleParameters.size() != particleParametersSize && errors < maxErrors ){
message << methodName << " parameter size=" << particleParameters.size() << " for parameter vector index=" << vectorIndex << " is less than expected.\n";
errors++;
} else {
double charge = particleParameters[0];
double radius = particleParameters[1];
double scalingFactor = particleParameters[2];
int streamIndex = 2*vectorIndex;
particleRadii[vectorIndex] = static_cast<RealOpenMM> (radius);
scaleFactors[vectorIndex] = static_cast<RealOpenMM> (scalingFactor);
radiiAndCharge[streamIndex] = static_cast<BrookOpenMMFloat> (radius);
radiiAndCharge[streamIndex+1] = static_cast<BrookOpenMMFloat> (charge);
scaledRadiiAndOffset[streamIndex+1] = static_cast<BrookOpenMMFloat> (radius - dielectricOffset);
scaledRadiiAndOffset[streamIndex] = static_cast<BrookOpenMMFloat> (scaledRadiiAndOffset[streamIndex+1]*scalingFactor);
// scaledRadiiAndOffset[streamIndex] = static_cast<BrookOpenMMFloat> (radius - dielectricOffset);
// scaledRadiiAndOffset[streamIndex+1] = static_cast<BrookOpenMMFloat> (scaledRadiiAndOffset[streamIndex]*scalingFactor);
}
vectorIndex++;
}
// throw exception if errors detected
if( errors ){
throw OpenMMException( message.str() );
}
// load streams
_gbsaStreams[ObcParticleRadiiStream]->loadFromArray( radiiAndCharge );
_gbsaStreams[ObcScaledParticleRadiiStream]->loadFromArray( scaledRadiiAndOffset );
delete[] radiiAndCharge;
delete[] scaledRadiiAndOffset;
// setup for Born radii calculation
/*
ObcParameters* obcParameters = new ObcParameters( numberOfParticles, ObcParameters::ObcTypeII );
obcParameters->setAtomicRadii( particleRadii);
obcParameters->setScaledRadiusFactors( scaleFactors );
obcParameters->setSolventDielectric( static_cast<RealOpenMM>(solventDielectric) );
obcParameters->setSoluteDielectric( static_cast<RealOpenMM>(soluteDielectric) );
*/
//_cpuObc = new CpuObc(obcParameters);
//_cpuObc->setIncludeAceApproximation( true );
return DefaultReturnValue;
}
/*
* Setup of stream dimensions for partial force streams
*
* @param particleStreamSize particle stream size
* @param particleStreamWidth particle stream width
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
* */
int BrookGbsa::_initializePartialForceStreamSize( int particleStreamSize, int particleStreamWidth ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookGbsa::_initializePartialForceStreamSize";
//static const int debug = 1;
// ---------------------------------------------------------------------------------------
int innerUnroll = getInnerLoopUnroll();
if( innerUnroll < 1 ){
std::stringstream message;
message << methodName << " innerUnrolls=" << innerUnroll << " is less than 1.";
throw OpenMMException( message.str() );
return ErrorReturnValue;
}
if( _partialForceStreamWidth < 1 ){
std::stringstream message;
message << methodName << " partial force stream width=" << _partialForceStreamWidth << " is less than 1.";
throw OpenMMException( message.str() );
return ErrorReturnValue;
}
_partialForceStreamSize = particleStreamSize*getDuplicationFactor()/innerUnroll;
_partialForceStreamHeight = _partialForceStreamSize/_partialForceStreamWidth;
_partialForceStreamHeight += ( (_partialForceStreamSize % _partialForceStreamWidth) ? 1 : 0);
return DefaultReturnValue;
}
/*
* Setup of j-stream dimensions
*
* Get contents of object
*
*
* @param level level of dump
*
* @return string containing contents
*
* */
std::string BrookGbsa::getContentsString( int level ) const {
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookGbsa::getContentsString";
static const unsigned int MAX_LINE_CHARS = 256;
char value[MAX_LINE_CHARS];
static const char* Set = "Set";
static const char* NotSet = "Not set";
// ---------------------------------------------------------------------------------------
std::stringstream message;
std::string tab = " ";
#ifdef _MSC_VER
#define LOCAL_SPRINTF(a,b,c) sprintf_s( (a), MAX_LINE_CHARS, (b), (c) );
#else
#define LOCAL_SPRINTF(a,b,c) sprintf( (a), (b), (c) );
#endif
(void) LOCAL_SPRINTF( value, "%d", getNumberOfParticles() );
message << _getLine( tab, "Number of particles:", value );
(void) LOCAL_SPRINTF( value, "%d", includeAce() );
message << _getLine( tab, "ACE included:", value );
(void) LOCAL_SPRINTF( value, "%.5f", getDielectricOffset() );
message << _getLine( tab, "Dielectric offset:", value );
(void) LOCAL_SPRINTF( value, "%d", getNumberOfForceStreams() );
message << _getLine( tab, "Number of force streams:", value );
(void) LOCAL_SPRINTF( value, "%d", getDuplicationFactor() );
message << _getLine( tab, "Duplication factor:", value );
(void) LOCAL_SPRINTF( value, "%d", getInnerLoopUnroll () )
message << _getLine( tab, "Inner loop unroll:", value );
(void) LOCAL_SPRINTF( value, "%d", getOuterLoopUnroll() )
message << _getLine( tab, "Outer loop unroll:", value );
(void) LOCAL_SPRINTF( value, "%d", getParticleSizeCeiling() );
message << _getLine( tab, "Particle ceiling:", value );
(void) LOCAL_SPRINTF( value, "%d", getParticleStreamWidth() );
message << _getLine( tab, "Particle stream width:", value );
(void) LOCAL_SPRINTF( value, "%d", getParticleStreamHeight() );
message << _getLine( tab, "Particle stream height:", value );
(void) LOCAL_SPRINTF( value, "%d", getParticleStreamSize() );
message << _getLine( tab, "Particle stream size:", value );
(void) LOCAL_SPRINTF( value, "%d", getGbsaParticleStreamWidth() );
message << _getLine( tab, "Gbsa stream width:", value );
(void) LOCAL_SPRINTF( value, "%d", getGbsaParticleStreamHeight() );
message << _getLine( tab, "Gbsa stream height:", value );
(void) LOCAL_SPRINTF( value, "%d", getGbsaParticleStreamSize() );
message << _getLine( tab, "Gbsa stream size:", value );
(void) LOCAL_SPRINTF( value, "%d", getPartialForceStreamWidth() );
message << _getLine( tab, "Partial force stream width:", value );
(void) LOCAL_SPRINTF( value, "%d", getPartialForceStreamHeight() );
message << _getLine( tab, "Partial force stream height:", value );
(void) LOCAL_SPRINTF( value, "%d", getPartialForceStreamSize() );
message << _getLine( tab, "Partial force stream size:", value );
message << _getLine( tab, "Log:", (getLog() ? Set : NotSet) );
for( int ii = 0; ii < LastStreamIndex; ii++ ){
message << std::endl;
if( _gbsaStreams[ii] ){
message << _gbsaStreams[ii]->getContentsString( );
}
}
// force streams
for( int ii = 0; ii < getNumberOfForceStreams(); ii++ ){
char description[256];
(void) LOCAL_SPRINTF( description, "PartialForceStream %d", ii );
message << _getLine( tab, description, (isForceStreamSet(ii) ? Set : NotSet) );
}
for( int ii = 0; ii < getNumberOfForceStreams(); ii++ ){
message << std::endl;
if( _gbsaForceStreams[ii] ){
message << _gbsaForceStreams[ii]->getContentsString( );
}
}
#undef LOCAL_SPRINTF
return message.str();
}
/**
* Compute forces
*
*/
void BrookGbsa::computeForces( BrookStreamImpl& positionStream, BrookStreamImpl& forceStream ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookGbsa::executeForces";
int printOn = 0;
FILE* log;
float mergeNonObcForces = 1.0f;
float kcalMolTokJNM = -0.4184f;
// ---------------------------------------------------------------------------------------
//setLog( stderr );
if( printOn && getLog() ){
log = getLog();
} else {
printOn = 0;
}
float includeAceTerm = (float) (includeAce());
BrookFloatStreamInternal** gbsaForceStreams = getForceStreams();
// calculate Born radii
kCalculateBornRadii( (float) getNumberOfParticles(),
(float) getParticleSizeCeiling(),
(float) getDuplicationFactor(),
(float) getParticleStreamWidth( ),
(float) getPartialForceStreamWidth( ),
positionStream.getBrookStream(),
getObcScaledParticleRadii()->getBrookStream(),
gbsaForceStreams[0]->getBrookStream() );
// ---------------------------------------------------------------------------------------
// diagnostics
if( printOn ){
(void) fprintf( log, "\n%s Post kCalculateBornRadii: atms=%d ceil=%d dup=%d particleStrW=%3d prtlF=%3d diel=%.3f %.3f ACE=%.1f\n",
methodName.c_str(), getNumberOfParticles(),
getParticleSizeCeiling(),
getDuplicationFactor(),
getParticleStreamWidth( ),
getPartialForceStreamWidth( ) );
BrookStreamInternal* brookStreamInternalF = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPositionStream\n" );
brookStreamInternalF->printToFile( log );
(void) fprintf( log, "\nRadii\n" );
getObcParticleRadii()->printToFile( log );
(void) fprintf( log, "\nObcScaledParticleRadii\n" );
getObcScaledParticleRadii()->printToFile( log );
}
// ---------------------------------------------------------------------------------------
kPostCalculateBornRadii_nobranch(
(float) getDuplicationFactor(),
(float) getParticleStreamWidth( ),
(float) getPartialForceStreamWidth( ),
(float) getNumberOfParticles(),
(float) getParticleSizeCeiling(),
(float) getInnerLoopUnroll(),
kcalMolTokJNM,
(float) mergeNonObcForces,
gbsaForceStreams[0]->getBrookStream(),
getObcParticleRadii()->getBrookStream(),
getObcBornRadii()->getBrookStream(),
getObcChain()->getBrookStream() );
// ---------------------------------------------------------------------------------------
// diagnostics
if( 0 && printOn ){
(void) fprintf( log, "\n%s Post kPostCalculateBornRadii_nobranch: atms=%d ceil=%d dup=%d particleStrW=%3d prtlF=%3d diel=%.3f %.3f ACE=%.1f\n",
methodName.c_str(), getNumberOfParticles(),
getParticleSizeCeiling(),
getDuplicationFactor(),
getParticleStreamWidth( ),
getPartialForceStreamWidth( ) );
BrookStreamInternal* brookStreamInternalF = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPositionStream\n" );
brookStreamInternalF->printToFile( log );
(void) fprintf( log, "\nInput\n" );
gbsaForceStreams[0]->printToFile( log );
(void) fprintf( log, "\nObcParticleRadii\n" );
getObcParticleRadii()->printToFile( log );
(void) fprintf( log, "\nBornR\n" );
getObcBornRadii()->printToFile( log );
(void) fprintf( log, "\nObcChain\n" );
getObcChain()->printToFile( log );
}
// ---------------------------------------------------------------------------------------
// first major OBC loop
kObcLoop1( (float) getNumberOfParticles(),
(float) getParticleSizeCeiling(),
(float) getDuplicationFactor(),
(float) getParticleStreamWidth( ),
(float) getPartialForceStreamWidth( ),
getSoluteDielectric(),
getSolventDielectric(),
includeAceTerm,
positionStream.getBrookStream(),
getObcBornRadii()->getBrookStream(),
getObcParticleRadii()->getBrookStream(),
gbsaForceStreams[0]->getBrookStream(),
gbsaForceStreams[1]->getBrookStream(),
gbsaForceStreams[2]->getBrookStream(),
gbsaForceStreams[3]->getBrookStream()
);
// ---------------------------------------------------------------------------------------
// diagnostics
if( printOn ){
(void) fprintf( log, "\nPost kObcLoop1: atms=%d ceil=%d dup=%d particleStrW=%3d prtlF=%3d diel=%.3f %.3f ACE=%.1f\n",
getNumberOfParticles(),
getParticleSizeCeiling(),
getDuplicationFactor(),
getParticleStreamWidth( ),
getPartialForceStreamWidth( ),
getSoluteDielectric(),
getSolventDielectric(), includeAceTerm );
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPost kObcLoop1 PositionStream\n" );
brookStreamInternalPos->printToFile( log );
(void) fprintf( log, "\nPost kObcLoop1 BornR\n" );
getObcBornRadii()->printToFile( log );
(void) fprintf( log, "\nPost kObcLoop1 ParticleR\n" );
getObcParticleRadii()->printToFile( log );
(void) fprintf( log, "\nPost kObcLoop1 ForceStreams output\n" );
for( int ii = 0; ii < 4; ii++ ){
(void) fprintf( log, "\nPost kObcLoop1 ForceStream %d output\n", ii );
gbsaForceStreams[ii]->printToFile( log );
}
}
// ---------------------------------------------------------------------------------------
// gather for first loop
kPostObcLoop1_nobranch(
(float) getDuplicationFactor(),
(float) getParticleStreamWidth( ),
(float) getPartialForceStreamWidth( ),
(float) getNumberOfParticles(),
(float) getParticleSizeCeiling(),
(float) getInnerLoopUnroll(),
gbsaForceStreams[0]->getBrookStream(),
gbsaForceStreams[1]->getBrookStream(),
gbsaForceStreams[2]->getBrookStream(),
gbsaForceStreams[3]->getBrookStream(),
getObcChain()->getBrookStream(),
getObcBornRadii()->getBrookStream(),
getObcIntermediateForce()->getBrookStream(),
getObcBornRadii2()->getBrookStream() );
// ---------------------------------------------------------------------------------------
// diagnostics
if( printOn ){
(void) fprintf( log, "\nPost kPostObcLoop1_nobranch: dup=%d aStrW=%d pStrW=%d no.atms=%3d ceil=%3d Unroll=%1d\n",
getDuplicationFactor(),
getParticleStreamWidth( ),
getPartialForceStreamWidth( ),
getNumberOfParticles(),
getParticleSizeCeiling(),
getInnerLoopUnroll() );
(void) fprintf( log, "\nPost kPostObcLoop1_nobranch: ForceStreams\n" );
for( int ii = 0; ii < 4; ii++ ){
(void) fprintf( log, "\nPost kPostObcLoop1_nobranch: %d ForceStreams\n", ii );
gbsaForceStreams[ii]->printToFile( log );
}
(void) fprintf( log, "\nPost kPostObcLoop1_nobranch: ObcChain\n" );
getObcChain()->printToFile( log );
(void) fprintf( log, "\nPost kPostObcLoop1_nobranch: BornR\n" );
getObcBornRadii()->printToFile( log );
// output
(void) fprintf( log, "\nPost kPostObcLoop1_nobranch: ObcIntermediateForce output\n" );
getObcIntermediateForce()->printToFile( log );
// output
(void) fprintf( log, "\nPost kPostObcLoop1_nobranch: ObcBornRadii2 output\n" );
getObcBornRadii2()->printToFile( log );
}
// ---------------------------------------------------------------------------------------
// second major OBC loop
kObcLoop2( (float) getNumberOfParticles(),
(float) getParticleSizeCeiling(),
(float) getDuplicationFactor(),
(float) getParticleStreamWidth( ),
(float) getPartialForceStreamWidth( ),
positionStream.getBrookStream(),
getObcScaledParticleRadii()->getBrookStream(),
getObcBornRadii2()->getBrookStream(),
gbsaForceStreams[0]->getBrookStream(),
gbsaForceStreams[1]->getBrookStream(),
gbsaForceStreams[2]->getBrookStream(),
gbsaForceStreams[3]->getBrookStream()
);
// ---------------------------------------------------------------------------------------
// diagnostics
if( printOn ){
(void) fprintf( log, "\nPost kObcLoop2: no.atms=%5d ceil=%3d dup=%3d strW=%3d pStrW=%3d\n",
getNumberOfParticles(),
getParticleSizeCeiling(),
getDuplicationFactor(),
getParticleStreamWidth( ),
getPartialForceStreamWidth( ) );
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPost kObcLoop2: PositionStream\n" );
brookStreamInternalPos->printToFile( log );
(void) fprintf( log, "\nPost kObcLoop2: ObcScaledParticleRadii\n" );
getObcScaledParticleRadii()->printToFile( log );
(void) fprintf( log, "\nPost kObcLoop2: ObcBornRadii2\n" );
getObcBornRadii2()->printToFile( log );
(void) fprintf( log, "\nPost kObcLoop2: ForceStreams\n" );
for( int ii = 0; ii < 4; ii++ ){
gbsaForceStreams[ii]->printToFile( log );
}
}
// ---------------------------------------------------------------------------------------
// gather for second loop
kPostObcLoop2_nobranch(
(float) getDuplicationFactor(),
(float) getParticleStreamWidth( ),
(float) getPartialForceStreamWidth( ),
(float) getNumberOfParticles(),
(float) getParticleSizeCeiling(),
(float) getInnerLoopUnroll(),
kcalMolTokJNM,
mergeNonObcForces,
getObcIntermediateForce()->getBrookStream(),
forceStream.getBrookStream(),
gbsaForceStreams[0]->getBrookStream(),
gbsaForceStreams[1]->getBrookStream(),
gbsaForceStreams[2]->getBrookStream(),
gbsaForceStreams[3]->getBrookStream(),
getObcParticleRadii()->getBrookStream(),
getObcBornRadii()->getBrookStream(),
getObcChain()->getBrookStream(),
forceStream.getBrookStream()
);
// ---------------------------------------------------------------------------------------
// diagnostics
if( printOn ){
(void) fprintf( log, "\nPost kPostObcLoop2_nobranch: atms=%d ceil=%d dup=%d particleStrW=%3d prtlF=%3d diel=%.3f %.3f ACE=%.1f\n",
getNumberOfParticles(),
getParticleSizeCeiling(),
getDuplicationFactor(),
getParticleStreamWidth( ),
getPartialForceStreamWidth( ),
getSoluteDielectric(),
getSolventDielectric(), includeAceTerm );
(void) fprintf( log, "\nPost kPostObcLoop2_nobranch: PartialForceStreams\n" );
for( int ii = 0; ii < 4; ii++ ){
(void) fprintf( log, "\nPost kPostObcLoop2_nobranch: PartialForceStreams %d\n", ii );
gbsaForceStreams[ii]->printToFile( log );
}
BrookStreamInternal* brookStreamInternalF = forceStream.getBrookStreamInternal();
(void) fprintf( log, "\nPost kPostObcLoop2_nobranch: ForceStream\n" );
brookStreamInternalF->printToFile( log );
(void) fprintf( log, "\nPost kPostObcLoop2_nobranch: Chain\n" );
getObcChain()->printToFile( log );
(void) fprintf( log, "\nPost kPostObcLoop2_nobranch: BornR\n" );
getObcBornRadii()->printToFile( log );
}
// ---------------------------------------------------------------------------------------
}
#ifndef OPENMM_BROOK_GBSA_H_
#define OPENMM_BROOK_GBSA_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include <vector>
#include "BrookStreamImpl.h"
#include "BrookPlatform.h"
#include "BrookCommon.h"
#include "../../../platforms/reference/src/gbsa/CpuObc.h"
namespace OpenMM {
/**
*
* Used by BrookCalcGBSAOBCForceKernel kernel to execute OBC algorithm on GPU
*
*/
class BrookGbsa : public BrookCommon {
public:
/**
* Constructor
*
*/
BrookGbsa( );
/**
* Destructor
*
*/
~BrookGbsa();
/**
* Return number of force streams
*
* @return number of force streams
*
*/
int getNumberOfForceStreams( void ) const;
/**
* Get duplication factor
*
* @return duplication factor
*
*/
int getDuplicationFactor( void ) const;
/**
* Set duplication factor
*
* @param duplication factor
*
* @return DefaultReturnValue
*
*/
int setDuplicationFactor( int duplicationFactor );
/**
* Get particle ceiling parameter
*
* @return particle ceiling parameter
*
*/
int getParticleSizeCeiling( void ) const;
/**
* Get outer loop unroll
*
* @return outer loop unroll (fixed value)
*
*/
int getOuterLoopUnroll( void ) const;
/**
* Set outer loop unroll
*
* @param outer loop unroll (fixed value)
*
* @return updated outer loop unroll (fixed value)
*
*/
int setOuterLoopUnroll( int outerUnroll );
/**
* Return unrolling for inner loops
*
* @return outer loop unrolling
*/
int getInnerLoopUnroll( void ) const;
/**
* Return true if ACE approximation is to be included
*
* @return true if ACE approximation is to be included
*/
int includeAce( void ) const;
/**
* Get partial force stream width
*
* @return partial force stream width
*/
int getPartialForceStreamWidth( void ) const;
/**
* Get partial force stream height
*
* @return partial force stream height
*/
int getPartialForceStreamHeight( void ) const;
/**
* Get partial force stream size
*
* @return partial force stream size
*/
int getPartialForceStreamSize( void ) const;
/**
* Get Gbsa particle stream width
*
* @return particle stream width
*/
int getGbsaParticleStreamWidth( void ) const;
/**
* Get Gbsa particle stream height
*
* @return particle stream height
*/
int getGbsaParticleStreamHeight( void ) const;
/**
* Get Gbsa particle stream size
*
* @return particle stream size
*/
int getGbsaParticleStreamSize( void ) const;
/**
* Get solute dielectric
*
* @return solute dielectric
*/
float getSoluteDielectric( void ) const;
/**
* Get solvent dielectric
*
* @return solvent dielectric
*/
float getSolventDielectric( void ) const;
/**
* Get OBC dielectric offset
*
* @return dielectric offset
*/
float getDielectricOffset( void ) const;
/**
* Get particle radii
*
* @return particle radii stream
*
*/
BrookFloatStreamInternal* getObcParticleRadii( void ) const;
/**
* Get scaled particle radii
*
* @return scaled particle radii stream
*
*/
BrookFloatStreamInternal* getObcScaledParticleRadii( void ) const;
/**
* Get particle radii w/ dielectric offset
*
* @return particle radii w/ dielectric offset stream
*
*/
BrookFloatStreamInternal* getObcParticleRadiiWithDielectricOffset( void ) const;
/**
* Get Born radii stream
*
* @return Born radii stream
*
*/
BrookFloatStreamInternal* getObcBornRadii( void ) const;
/**
* Get Born radii2 stream
*
* @return Born radii2 stream
*
*/
BrookFloatStreamInternal* getObcBornRadii2( void ) const;
/**
* Get Obc intermediate force stream
*
* @return Obc intermediate force stream
*
*/
BrookFloatStreamInternal* getObcIntermediateForce( void ) const;
/**
* Get Obc chain stream
*
* @return Obc chain stream
*
*/
BrookFloatStreamInternal* getObcChain( void ) const;
/**
* Get force streams
*
* @return force streams
*
*/
BrookFloatStreamInternal** getForceStreams( void );
/**
* Get array of Gbsa streams
*
* @return array ofstreams
*
*/
BrookFloatStreamInternal** getStreams( void );
/**
* Return true if force[index] stream is set
*
* @return true if index is valid && force[index] stream is set; else false
*
*/
int isForceStreamSet( int index ) const;
/**
* Return true if Born radii have been initialized
*
* @return true if Born radii have been initialized
*
*/
int haveBornRadiiBeenInitialized( void ) const;
/**
* Calculate Born radii
*
* @return calculate Born radii
*
*/
// int calculateBornRadii( const Stream& positions );
/*
* Setup of Gbsa parameters
*
* @param particleParameters vector of OBC parameters [particleI][0=charge]
* [particleI][1=radius]
* [particleI][2=scaling factor]
* @param solventDielectric solvent dielectric
* @param soluteDielectric solute dielectric
* @param platform Brook platform
*
* @return nonzero value if error
*
* */
int setup( const std::vector<std::vector<double> >& particleParameters,
double solventDielectric, double soluteDielectric, const Platform& platform );
/*
* Get contents of object
*
* @param level of dump
*
* @return string containing contents
*
* */
std::string getContentsString( int level = 0 ) const;
/**
* Compute forces
*
*/
void computeForces( BrookStreamImpl& positionStream, BrookStreamImpl& forceStream );
private:
// fixed number of force streams
static const int NumberOfForceStreams = 4;
// streams indices
enum {
ObcParticleRadiiStream,
ObcScaledParticleRadiiStream,
ObcParticleRadiiWithDielectricOffsetStream,
ObcBornRadiiStream,
ObcBornRadii2Stream,
ObcIntermediateForceStream,
ObcChainStream,
LastStreamIndex
};
// particle ceiling
int _particleSizeCeiling;
// unroll in i/j dimensions
int _outerUnroll;
int _innerUnroll;
// duplication factor
int _duplicationFactor;
// include ACE approximation
int _includeAce;
// force stream width
int _partialForceStreamWidth;
int _partialForceStreamHeight;
int _partialForceStreamSize;
// Particle stream dimensions
int _gbsaParticleStreamWidth;
int _gbsaParticleStreamHeight;
int _gbsaParticleStreamSize;
// dielectrics
double _solventDielectric;
double _soluteDielectric;
// dielectric offset
double _dielectricOffset;
// internal streams
BrookFloatStreamInternal* _gbsaStreams[LastStreamIndex];
BrookFloatStreamInternal* _gbsaForceStreams[NumberOfForceStreams];
int _bornRadiiInitialized;
// CpuObc reference -- was used to calculate initial Born radii
// no longer used -- to be removed?
// CpuObc* _cpuObc;
/*
* Setup of stream dimensions
*
* @param particleStreamSize particle stream size
* @param particleStreamWidth particle stream width
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
* */
int _initializeStreamSizes( int particleStreamSize, int particleStreamWidth );
/**
* Initialize stream dimensions
*
* @param numberOfParticles number of particles
* @param platform platform
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
*/
int _initializeStreamSizes( int numberOfParticles, const Platform& platform );
/**
* Initialize stream dimensions and streams
*
* @param platform platform
*
* @return nonzero value if error
*
*/
int _initializeStreams( const Platform& platform );
/*
* Setup of stream dimensions for partial force streams
*
* @param particleStreamSize particle stream size
* @param particleStreamWidth particle stream width
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
* */
int _initializePartialForceStreamSize( int particleStreamSize, int particleStreamWidth );
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_GBSA_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookStreamImpl.h"
#include "BrookInitializeForcesKernel.h"
#include "openmm/OpenMMException.h"
#include <cmath>
#include <limits>
#include <sstream>
using namespace OpenMM;
using namespace std;
/**
* BrookInitializeForcesKernel constructor
*
* @param name kernel name
* @param platform platform
* @param openMMBrookInterface OpenMMBrookInterface reference
* @param system System reference
*
*/
BrookInitializeForcesKernel::BrookInitializeForcesKernel( std::string name, const Platform& platform,
OpenMMBrookInterface& openMMBrookInterface, System& system ) :
CalcForcesAndEnergyKernel( name, platform ), _openMMBrookInterface( openMMBrookInterface ), _system( system ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookInitializeForcesKernel::BrookInitializeForcesKernel";
// ---------------------------------------------------------------------------------------
_numberOfParticles = 0;
_log = NULL;
const BrookPlatform& brookPlatform = dynamic_cast<const BrookPlatform&> (platform);
if( brookPlatform.getLog() != NULL ){
setLog( brookPlatform.getLog() );
}
}
/**
* BrookInitializeForcesKernel destructor
*
*/
BrookInitializeForcesKernel::~BrookInitializeForcesKernel( ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookInitializeForcesKernel::BrookInitializeForcesKernel";
// ---------------------------------------------------------------------------------------
}
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* BrookInitializeForcesKernel::getLog( void ) const {
return _log;
}
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int BrookInitializeForcesKernel::setLog( FILE* log ){
_log = log;
return BrookCommon::DefaultReturnValue;
}
/**
* Initialize
*
* @param system System reference
*
* @return DefaultReturnValue
*
*/
void BrookInitializeForcesKernel::initialize( const System& system ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookInitializeForcesKernel::initialize";
// ---------------------------------------------------------------------------------------
//FILE* log = getLog();
}
/**
* Zero forces
*
* @param context ContextImpl context
*
*/
void BrookInitializeForcesKernel::execute( ContextImpl& context ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookInitializeForcesKernel::execute";
// ---------------------------------------------------------------------------------------
_openMMBrookInterface.zeroForces( context );
// ---------------------------------------------------------------------------------------
}
#ifndef OPENMM_BROOK_INITIALIZE_FORCES_KERNEL_H_
#define OPENMM_BROOK_INITIALIZE_FORCES_KERNEL_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "openmm/kernels.h"
#include "OpenMMBrookInterface.h"
namespace OpenMM {
/**
* This kernel initializes the forces
*/
class BrookInitializeForcesKernel : public CalcForcesAndEnergyKernel {
public:
BrookInitializeForcesKernel( std::string name, const Platform& platform, OpenMMBrookInterface& openMMBrookInterface, System& system );
~BrookInitializeForcesKernel();
/**
* Initialize the kernel
*
* @param system the System this kernel will be applied to
*/
void initialize( const System& system );
/**
* Execute the kernel to calculate the forces.
*
* @param context the context in which to execute this kernel
*/
void execute( ContextImpl& context );
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int setLog( FILE* log );
/*
* Get contents of object
*
* @param level of dump
*
* @return string containing contents
*
* */
std::string getContents( int level ) const;
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* getLog( void ) const;
private:
// log file reference
FILE* _log;
// number of particles
int _numberOfParticles;
OpenMMBrookInterface& _openMMBrookInterface;
System& _system;
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_INITIALIZE_FORCES_KERNEL_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookIntStreamInternal.h"
#include "openmm/OpenMMException.h"
#include <sstream>
using namespace OpenMM;
/**
* BrookIntStreamInternal constructor
*
* @param name stream name
* @param size array size
* @param streamWidth stream width
* @param type stream type (Integer, Integer2, ...)
* @param dangleValue fill value for tail of stream beyond array size
*
*/
BrookIntStreamInternal::BrookIntStreamInternal( std::string name, int size, int streamWidth,
BrookStreamInternal::DataType type,
int dangleValue ) :
BrookStreamInternal( name, size, streamWidth, type ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookIntStreamInternal::BrookIntStreamInternal";
// ---------------------------------------------------------------------------------------
_dangleValue = dangleValue;
switch( type ){
case BrookStreamInternal::Integer:
_width = 1;
break;
case BrookStreamInternal::Integer2:
_width = 2;
break;
case BrookStreamInternal::Integer3:
_width = 3;
break;
case BrookStreamInternal::Integer4:
_width = 4;
break;
default:
std::stringstream message;
message << methodName << " type=" << type << " not recognized.";
throw OpenMMException( message.str() );
}
_data = new int[size*_width];
}
/**
* BrookIntStreamInternal destructor
*
*/
BrookIntStreamInternal::~BrookIntStreamInternal() {
delete[] _data;
}
/**
* Load data from array into stream
*
* @param array array to load (length=size*width)
*
*/
void BrookIntStreamInternal::loadFromArray( const void* array ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntStreamInternal::loadFromArray";
// static const int debug = 1;
// ---------------------------------------------------------------------------------------
return loadFromArray( array, getBaseDataType() );
}
/**
* Load data from array into stream
*
* @param array array to load (length=size*width)
*
*/
void BrookIntStreamInternal::loadFromArray( const void* array, BrookStreamInternal::DataType baseType ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookIntStreamInternal::loadFromArray(1)";
// ---------------------------------------------------------------------------------------
if( baseType != BrookStreamInternal::Integer ){
std::stringstream message;
message << methodName << " stream=" << getName() << " base type=" << getTypeString( baseType ) << " not handled -- add code.";
throw OpenMMException( message.str() );
}
int* arrayData = (int*) array;
int totalSize = getSize()*getWidth();
for( int ii = 0; ii < totalSize; ii++ ){
_data[ii] = arrayData[ii];
}
}
/**
* Save data from stream to array
*
* @param array array to save data to (length=size*width)
*
*/
void BrookIntStreamInternal::saveToArray( void* array ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntStreamInternal::saveToArray";
// ---------------------------------------------------------------------------------------
int* arrayData = (int*) array;
int totalSize = getSize()*getWidth();
for( int ii = 0; ii < totalSize; ii++ ){
arrayData[ii] = _data[ii];
}
}
/**
* Set all stream entries to input value
*
* @param value value to load into stream
*
*/
void BrookIntStreamInternal::fillWithValue( void* value ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntStreamInternal::fillWithValue";
// ---------------------------------------------------------------------------------------
int valueData = *((int*) value);
int totalSize = getSize()*getWidth();
for( int ii = 0; ii < totalSize; ii++ ){
_data[ii] = valueData;
}
}
/**
* Get array of appropritate size for loading data
*
* @return data array -- user's responsibility to free
*/
void* BrookIntStreamInternal::getDataArray( void ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookIntStreamInternal::getDataArray";
// ---------------------------------------------------------------------------------------
int totalSize = getStreamSize()*getWidth();
return new int[totalSize];
}
/**
* Get data
*
* @return data ptr
*
*/
void* BrookIntStreamInternal::getData( void ){
return _data;
}
/**
* Get data
*
* @param readFromBoard if set, read values on board
*
* @return data array
*
*/
void* BrookIntStreamInternal::getData( int readFromBoard ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntStreamInternal::getData";
// ---------------------------------------------------------------------------------------
if( readFromBoard ){
_aStream.write( _data );
}
return (void*) _data;
}
/*
* Print array contents of object to file
*
* @param log file to print to
*
* @return DefaultReturnValue
*
* */
int BrookIntStreamInternal::_bodyPrintToFile( FILE* log, int maxPrint ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookIntStreamInternal::_bodyPrintToFile";
// ---------------------------------------------------------------------------------------
void* dataArrayV = getDataArray( );
saveToArray( dataArrayV );
int streamSize = getStreamSize();
int width = getWidth();
int index = 0;
int* dataArray = (int*) dataArrayV;
for( int ii = 0; ii < streamSize; ii++ ){
std::stringstream message;
message.width( 10 );
message << ii << " [ ";
for( int jj = 0; jj < width; jj++ ){
message << dataArray[index++] << " ";
}
message << "]\n";
(void) fprintf( log, "%s", message.str().c_str() );
}
delete[] dataArrayV;
return DefaultReturnValue;
}
/*
* Get contents of object
*
* @param level level of dump
*
* @return string containing contents
*
* */
const std::string BrookIntStreamInternal::getContentsString( int level ) const {
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntStreamInternal::getContentsString";
static const unsigned int MAX_LINE_CHARS = 256;
char value[MAX_LINE_CHARS];
//static const char* Set = "Set";
//static const char* NotSet = "Not set";
// ---------------------------------------------------------------------------------------
std::stringstream message;
std::string tab = " ";
#ifdef _MSC_VER
#define LOCAL_SPRINTF(a,b,c) sprintf_s( (a), MAX_LINE_CHARS, (b), (c) );
#else
#define LOCAL_SPRINTF(a,b,c) sprintf( (a), (b), (c) );
#endif
(void) LOCAL_SPRINTF( value, "%s", getName().c_str() );
message << _getLine( tab, "Name:", value );
(void) LOCAL_SPRINTF( value, "%d", getWidth() );
message << _getLine( tab, "Width:", value );
(void) LOCAL_SPRINTF( value, "%d", getStreamSize() );
message << _getLine( tab, "Stream size:", value );
(void) LOCAL_SPRINTF( value, "%d", getStreamWidth() );
message << _getLine( tab, "Stream width:", value );
(void) LOCAL_SPRINTF( value, "%d", getStreamHeight() );
message << _getLine( tab, "Stream height:", value );
return message.str();
}
/**
* BrookFloatStreamInternal constructor
*
* @param stopIndex index to stop sum
* @param sum array of size=getWidth()
*
* @return DefaultReturnValue
*
* @throw exception if stopIndex is too large
*/
int BrookIntStreamInternal::sumByDimension( int stopIndex, double* sum ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookIntStreamInternal::sumByDimension";
// ---------------------------------------------------------------------------------------
if( stopIndex > getSize() ){
std::stringstream message;
message << methodName << " stream=" << getName() << " input topIndex" << stopIndex << " is too large: stream size=" << getSize();
throw OpenMMException( message.str() );
}
// get _data from GPU
_aStream.write( _data );
int width = getWidth();
int widthM1 = getWidth() - 1;
stopIndex *= width;
for( int ii = 0; ii < width; ii++ ){
sum[ii] = 0.0;
}
int index = 0;
for( int ii = 0; ii < stopIndex; ii++ ){
sum[index] += (double) _data[ii];
if( index == widthM1 ){
index = 0;
} else {
index++;
}
}
return DefaultReturnValue;
}
#ifndef OPENMM_BROOK_INT_STREAM_INTERNAL_H_
#define OPENMM_BROOK_INT_STREAM_INTERNAL_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookStreamInternal.h"
#include "brook/brook.hpp"
namespace OpenMM {
/**
* Internalementation of int streams for the Brook platform
*/
class BrookIntStreamInternal : public BrookStreamInternal {
public:
/**
* BrookIntStreamInternal constructor
*
* @param name stream name
* @param size size of array
* @param streamWidth stream width
* @param type stream type (float, float2, ...)
* @param inputDefaultDangleValue default dangle value
*
*/
BrookIntStreamInternal( std::string name, int size, int streamWidth, BrookStreamInternal::DataType type, int dangleValue );
/**
* BrookIntStreamInternal destructor
*
*/
~BrookIntStreamInternal( );
/**
* Copy the contents of an array into this stream.
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct data type for this stream. If the stream has a compound data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*
*/
void loadFromArray( const void* array );
/**
* Copy the contents of an array into this stream.
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct data type for this stream. If the stream has a compound data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*
* @param baseType data type of input array (float, double, int)
*
*/
void loadFromArray( const void* array, BrookStreamInternal::DataType baseType );
/**
* Save data to input array
*
* @param array a pointer to the start of the array. The array is assumed to have the same length as this stream,
* and to contain elements of the correct _data type for this stream. If the stream has a compound _data type, all
* the values should be packed into a single array: all the values for the first element, followed by all the values
* for the next element, etc.
*
* @throw exception if baseType not float or double
*
*/
void saveToArray( void* array );
/**
* Fill data w/ input value
*
* @param value to set array to
*
*
*/
void fillWithValue( void* value );
/**
* Get data array
*
* @return data array
*/
void* getData( void );
/**
* Get data
*
* @param readFromBoard if set, read values on board
*
* @return data array
*
*/
void* getData( int readFromBoard );
/**
* Get array of appropritate size for loading data
*
* @return data array -- user's responsibility to free
*/
void* getDataArray( void );
/*
* Get contents of object
*
*
* @param level level of dump
*
* @return string containing contents
*
* */
const std::string getContentsString( int level = 0 ) const;
/**
* BrookFloatStreamInternal constructor
*
* @param stopIndex index to stop sum
* @param sum array of size=getWidth()
*
* @return DefaultReturnValue
*
* @throw exception if stopIndex is too large
*/
int sumByDimension( int stopIndex, double* sum );
private:
int _dangleValue;
int* _data;
/*
* Print array to file
*
* @param log log file
*
* @return DefaultReturnValue
*
* */
int _bodyPrintToFile( FILE* log, int maxPrint );
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_INT_STREAM_INTERNAL_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookIntegrateLangevinStepKernel.h"
#include "BrookStreamInternal.h"
#include <ctime>
using namespace OpenMM;
using namespace std;
/**
* BrookIntegrateLangevinStepKernel constructor
*
* @param name name of the stream to create
* @param platform platform
* @param openMMBrookInterface OpenMMBrookInterface reference
* @param system System reference
*
*/
BrookIntegrateLangevinStepKernel::BrookIntegrateLangevinStepKernel( std::string name, const Platform& platform,
OpenMMBrookInterface& openMMBrookInterface, System& system ) :
IntegrateLangevinStepKernel( name, platform ), _openMMBrookInterface( openMMBrookInterface ), _system( system ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntegrateLangevinStepKernel::BrookIntegrateLangevinStepKernel";
// ---------------------------------------------------------------------------------------
_brookLangevinDynamics = NULL;
_brookShakeAlgorithm = NULL;
_brookRandomNumberGenerator = NULL;
_log = NULL;
const BrookPlatform& brookPlatform = dynamic_cast<const BrookPlatform&> (platform);
if( brookPlatform.getLog() != NULL ){
setLog( brookPlatform.getLog() );
}
}
/**
* BrookIntegrateVerletStepKernel destructor
*
*/
BrookIntegrateLangevinStepKernel::~BrookIntegrateLangevinStepKernel( ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntegrateLangevinStepKernel::~BrookIntegrateLangevinStepKernel";
// ---------------------------------------------------------------------------------------
delete _brookLangevinDynamics;
delete _brookShakeAlgorithm;
delete _brookRandomNumberGenerator;
}
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* BrookIntegrateLangevinStepKernel::getLog( void ) const {
return _log;
}
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int BrookIntegrateLangevinStepKernel::setLog( FILE* log ){
_log = log;
return DefaultReturnValue;
}
/**
* Initialize the kernel, setting up all parameters related to integrator.
*
* @param system System reference
* @param integrator LangevinIntegrator reference
*
*/
void BrookIntegrateLangevinStepKernel::initialize( const System& system, const LangevinIntegrator& integrator ){
// ---------------------------------------------------------------------------------------
int printOn = 0;
static const std::string methodName = "BrookIntegrateLangevinStepKernel::initialize";
FILE* log = NULL;
// ---------------------------------------------------------------------------------------
//setLog( stderr );
printOn = (printOn && getLog()) ? printOn : 0;
if( printOn ){
log = getLog();
(void) fprintf( log, "%s\n", methodName.c_str() );
(void) fflush( log );
}
int numberOfParticles = system.getNumParticles();
// masses
std::vector<double> masses;
masses.resize( numberOfParticles );
if( printOn ){
(void) fprintf( log, "%s %d\n", methodName.c_str(), numberOfParticles );
(void) fflush( log );
}
for( int ii = 0; ii < numberOfParticles; ii++ ){
masses[ii] = static_cast<double>(system.getParticleMass(ii));
}
// constraints
int numberOfConstraints = system.getNumConstraints();
if( printOn ){
(void) fprintf( log, "%s const=%d\n", methodName.c_str(), numberOfConstraints );
(void) fflush( log );
}
std::vector<std::vector<int> > constraintIndicesVector;
constraintIndicesVector.resize( numberOfConstraints );
std::vector<double> constraintLengths;
for( int ii = 0; ii < numberOfConstraints; ii++ ){
int particle1, particle2;
double distance;
system.getConstraintParameters( ii, particle1, particle2, distance );
constraintIndicesVector[ii].push_back( particle1 );
constraintIndicesVector[ii].push_back( particle2 );
constraintLengths.push_back( distance );
//(void) fprintf( log, "%s shake setup const=%d ", methodName.c_str(), ii ); fflush( log );
//(void) fprintf( log, "[ %d %d %f]\n", particle1, particle2, distance ); fflush( log );
}
_brookLangevinDynamics = new BrookLangevinDynamics( );
_brookLangevinDynamics->setup( masses, getPlatform() );
_brookShakeAlgorithm = new BrookShakeAlgorithm( );
_brookShakeAlgorithm->setup( masses, constraintIndicesVector, constraintLengths, getPlatform() );
// tolerance
BrookOpenMMFloat tolerance = static_cast<BrookOpenMMFloat>( integrator.getConstraintTolerance() );
_brookShakeAlgorithm->setShakeTolerance( tolerance );
_brookShakeAlgorithm->setMaxIterations( 40 );
if( log ){
_brookShakeAlgorithm->setLog( log );
}
// random number generator
_brookRandomNumberGenerator = new BrookRandomNumberGenerator( );
_brookRandomNumberGenerator->setup( (int) masses.size(), getPlatform() );
unsigned long int seed;
if( integrator.getRandomNumberSeed() <= 1 ){
seed = static_cast<unsigned long int>(time(NULL) & 0x000fffff);
} else {
seed = static_cast<unsigned long int>( integrator.getRandomNumberSeed() );
}
_brookRandomNumberGenerator->setRandomNumberSeed( seed );
if( printOn ){
(void) fprintf( log, "%s done setup:\nBrookShakeAlgorithm:\n%s\nBrookRandomNumberGenerator:\n%s\n\n", methodName.c_str(),
_brookShakeAlgorithm->getContentsString().c_str(),
_brookRandomNumberGenerator->getContentsString().c_str() );
(void) fprintf( log, "LangevinIntegrator seed=%d\n", integrator.getRandomNumberSeed() );
(void) fflush( log );
}
}
/**
* Execute kernel
*
* @param context ContextImpl reference
* @param integrator LangevinIntegrator reference
*
*/
void BrookIntegrateLangevinStepKernel::execute( ContextImpl& context, const LangevinIntegrator& integrator ){
// ---------------------------------------------------------------------------------------
double epsilon = 1.0e-06;
static const std::string methodName = "BrookIntegrateLangevinStepKernel::execute";
// ---------------------------------------------------------------------------------------
// first time through initialize _brookLangevinDynamics
// for each subsequent call, check if parameters need to be updated due to a change
// in T, gamma, or the step size
// take step
double differences[3];
differences[0] = integrator.getTemperature() - (double) _brookLangevinDynamics->getTemperature();
differences[1] = integrator.getFriction() - (double) _brookLangevinDynamics->getFriction();
differences[2] = integrator.getStepSize() - (double) _brookLangevinDynamics->getStepSize();
if( fabs( differences[0] ) > epsilon || fabs( differences[1] ) > epsilon || fabs( differences[2] ) > epsilon ){
_brookLangevinDynamics->updateParameters( integrator.getTemperature(), integrator.getFriction(), integrator.getStepSize() );
}
_brookLangevinDynamics->update( *(_openMMBrookInterface.getParticlePositions()), *(_openMMBrookInterface.getParticleVelocities()),
*(_openMMBrookInterface.getParticleForces()), *_brookShakeAlgorithm, *_brookRandomNumberGenerator );
_openMMBrookInterface.setTime(_openMMBrookInterface.getTime());
}
#ifndef OPENMM_BROOK_INTEGRATE_LANGEVIN_STEP_KERNEL_H_
#define OPENMM_BROOK_INTEGRATE_LANGEVIN_STEP_KERNEL_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "openmm/kernels.h"
#include "OpenMMBrookInterface.h"
#include "BrookLangevinDynamics.h"
#include "BrookShakeAlgorithm.h"
#include "BrookRandomNumberGenerator.h"
namespace OpenMM {
/**
* Performs Langevin integration step
*/
class BrookIntegrateLangevinStepKernel : public IntegrateLangevinStepKernel {
public:
// return values
static const int DefaultReturnValue = 0;
static const int ErrorReturnValue = -1;
/**
* BrookIntegrateLangevinStepKernel constructor
*
* @param name name of the stream to create
* @param platform platform
*
*/
BrookIntegrateLangevinStepKernel( std::string name, const Platform& platform, OpenMMBrookInterface& openMMBrookInterface, System& system );
/**
* BrookIntegrateLangevinStepKernel destructor
*
*/
~BrookIntegrateLangevinStepKernel();
/**
* Initialize the kernel, setting up all parameters related to integrator.
*
* @param system System reference
* @param integrator LangevinIntegrator reference
*/
void initialize( const System& system, const LangevinIntegrator& integrator );
/**
* Execute kernel
*
* @param context ContextImpl reference
* @param integrator LangevinIntegrator reference
*
*/
void execute( ContextImpl& context, const LangevinIntegrator& integrator );
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int setLog( FILE* log );
/*
* Get contents of object
*
* @param level of dump
*
* @return string containing contents
*
* */
std::string getContents( int level ) const;
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* getLog( void ) const;
protected:
FILE* _log;
BrookLangevinDynamics* _brookLangevinDynamics;
BrookShakeAlgorithm* _brookShakeAlgorithm;
BrookRandomNumberGenerator* _brookRandomNumberGenerator;
// interface
OpenMMBrookInterface& _openMMBrookInterface;
// System reference
System& _system;
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_INTEGRATE_LANGEVIN_STEP_KERNEL_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookIntegrateVerletStepKernel.h"
#include "BrookStreamInternal.h"
using namespace OpenMM;
using namespace std;
/**
* BrookIntegrateVerletStepKernel constructor
*
* @param name name of the kernel
* @param platform platform
* @param openMMBrookInterface OpenMMBrookInterface reference
* @param system System reference
*
*/
BrookIntegrateVerletStepKernel::BrookIntegrateVerletStepKernel( std::string name, const Platform& platform,
OpenMMBrookInterface& openMMBrookInterface, System& system ) :
IntegrateVerletStepKernel( name, platform ), _openMMBrookInterface( openMMBrookInterface ), _system( system ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntegrateVerletStepKernel::BrookIntegrateVerletStepKernel";
// ---------------------------------------------------------------------------------------
_brookVerletDynamics = NULL;
_brookShakeAlgorithm = NULL;
const BrookPlatform& brookPlatform = dynamic_cast<const BrookPlatform&> (platform);
if( brookPlatform.getLog() != NULL ){
setLog( brookPlatform.getLog() );
} else {
_log = NULL;
}
}
/**
* BrookIntegrateVerletStepKernel destructor
*
*/
BrookIntegrateVerletStepKernel::~BrookIntegrateVerletStepKernel( ){
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "BrookIntegrateVerletStepKernel::~BrookIntegrateVerletStepKernel";
// ---------------------------------------------------------------------------------------
delete _brookVerletDynamics;
delete _brookShakeAlgorithm;
}
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* BrookIntegrateVerletStepKernel::getLog( void ) const {
return _log;
}
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int BrookIntegrateVerletStepKernel::setLog( FILE* log ){
_log = log;
return DefaultReturnValue;
}
/**
* Initialize the kernel, setting up all parameters related to integrator.
*
* @param system System reference
* @param integrator VerletIntegrator reference
*
*/
void BrookIntegrateVerletStepKernel::initialize( const System& system, const VerletIntegrator& integrator ){
// ---------------------------------------------------------------------------------------
int printOn = 0;
static const std::string methodName = "BrookIntegrateVerletStepKernel::initialize";
// ---------------------------------------------------------------------------------------
FILE* log = getLog();
int numberOfParticles = system.getNumParticles();
// masses
std::vector<double> masses;
masses.resize( numberOfParticles );
for( int ii = 0; ii < numberOfParticles; ii++ ){
masses[ii] = static_cast<double>(system.getParticleMass(ii));
}
// constraints
int numberOfConstraints = system.getNumConstraints();
std::vector<std::vector<int> > constraintIndicesVector;
constraintIndicesVector.resize( numberOfConstraints );
std::vector<double> constraintLengths;
for( int ii = 0; ii < numberOfConstraints; ii++ ){
int particle1, particle2;
double distance;
system.getConstraintParameters( ii, particle1, particle2, distance );
constraintIndicesVector[ii].push_back( particle1 );
constraintIndicesVector[ii].push_back( particle2 );
constraintLengths.push_back( distance );
}
_brookVerletDynamics = new BrookVerletDynamics( );
_brookVerletDynamics->setup( masses, getPlatform() );
_brookVerletDynamics->setLog( log );
_brookShakeAlgorithm = new BrookShakeAlgorithm( );
_brookShakeAlgorithm->setLog( log );
_brookShakeAlgorithm->setup( masses, constraintIndicesVector, constraintLengths, getPlatform() );
BrookOpenMMFloat tolerance = static_cast<BrookOpenMMFloat>( integrator.getConstraintTolerance() );
_brookShakeAlgorithm->setShakeTolerance( tolerance );
_brookShakeAlgorithm->setMaxIterations( 40 );
if( printOn && log ){
(void) fprintf( log, "%s done w/ setup: particles=%d const=%d\n", methodName.c_str(), numberOfParticles, numberOfConstraints );
(void) fflush( log );
}
}
/**
* Execute kernel
*
* @param context ContextImpl reference
* @param integrator VerletIntegrator reference
*
*/
void BrookIntegrateVerletStepKernel::execute( ContextImpl& context, const VerletIntegrator& integrator ){
// ---------------------------------------------------------------------------------------
double epsilon = 1.0e-04;
static const std::string methodName = "BrookIntegrateVerletStepKernel::execute";
// ---------------------------------------------------------------------------------------
// for each subsequent call, check if parameters need to be updated due to a change
// in the step size
// take step
double stepSize = integrator.getStepSize();
double difference = stepSize - (double) _brookVerletDynamics->getStepSize();
if( fabs( difference ) > epsilon ){
_brookVerletDynamics->updateParameters( stepSize );
}
_brookVerletDynamics->update( *(_openMMBrookInterface.getParticlePositions()), *(_openMMBrookInterface.getParticleVelocities()),
*(_openMMBrookInterface.getParticleForces()), *_brookShakeAlgorithm );
_openMMBrookInterface.setTime(_openMMBrookInterface.getTime());
}
#ifndef OPENMM_BROOK_INTEGRATE_VERLET_STEP_KERNEL_H_
#define OPENMM_BROOK_INTEGRATE_VERLET_STEP_KERNEL_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "openmm/kernels.h"
#include "OpenMMBrookInterface.h"
#include "BrookVerletDynamics.h"
#include "BrookShakeAlgorithm.h"
namespace OpenMM {
/**
* This is the base class of Float and Double streams in the Brook Platform.
*/
class BrookIntegrateVerletStepKernel : public IntegrateVerletStepKernel {
public:
// return values
static const int DefaultReturnValue = 0;
static const int ErrorReturnValue = -1;
/**
* BrookIntegrateVerletStepKernel constructor
*
* @param name name of the stream to create
* @param platform platform
*
*/
BrookIntegrateVerletStepKernel( std::string name, const Platform& platform, OpenMMBrookInterface& openMMBrookInterface, System& system );
/**
* BrookIntegrateVerletStepKernel destructor
*
*/
~BrookIntegrateVerletStepKernel();
/**
* Initialize the kernel, setting up all parameters related to integrator.
*
* @param system System reference
* @param integrator VerletIntegrator reference
*/
void initialize( const System& system, const VerletIntegrator& integrator );
/**
* Execute kernel
*
* @param context ContextImpl reference
* @param integrator VerletIntegrator reference
*
*/
void execute( ContextImpl& context, const VerletIntegrator& integrator );
/**
* Set log file reference
*
* @param log file reference
*
* @return DefaultReturnValue
*
*/
int setLog( FILE* log );
/*
* Get contents of object
*
* @param level of dump
*
* @return string containing contents
*
* */
std::string getContents( int level ) const;
/**
* Get log file reference
*
* @return log file reference
*
*/
FILE* getLog( void ) const;
private:
FILE* _log;
BrookVerletDynamics* _brookVerletDynamics;
BrookShakeAlgorithm* _brookShakeAlgorithm;
// interface
OpenMMBrookInterface& _openMMBrookInterface;
// System reference
System& _system;
};
} // namespace OpenMM
#endif /* OPENMM_BROOK_INTEGRATE_VERLET_STEP_KERNEL_H_ */
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookKernelFactory.h"
#include "BrookInitializeForcesKernel.h"
#include "BrookUpdateTimeKernel.h"
#include "BrookCalcHarmonicBondForceKernel.h"
#include "BrookCalcHarmonicAngleForceKernel.h"
#include "BrookCalcPeriodicTorsionForceKernel.h"
#include "BrookCalcRBTorsionForceKernel.h"
#include "BrookCalcNonbondedForceKernel.h"
#include "BrookIntegrateLangevinStepKernel.h"
#include "BrookIntegrateVerletStepKernel.h"
//#include "BrookIntegrateBrownianStepKernel.h"
#include "BrookCalcKineticEnergyKernel.h"
#include "BrookCalcGBSAOBCForceKernel.h"
#include "BrookRemoveCMMotionKernel.h"
#include "openmm/internal/ContextImpl.h"
using namespace OpenMM;
KernelImpl* BrookKernelFactory::createKernelImpl( std::string name, const Platform& platform, ContextImpl& context ) const {
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookKernelFactory::createKernelImpl";
// ---------------------------------------------------------------------------------------
OpenMMBrookInterface& openMMBrookInterface = *static_cast<OpenMMBrookInterface*>(context.getPlatformData());
// initialize forces
if( name == CalcForcesAndEnergyKernel::Name() ){
return new BrookInitializeForcesKernel( name, platform, openMMBrookInterface, context.getSystem() );
// update time
} else if( name == UpdateStateDataKernel::Name() ){
return new BrookUpdateTimeKernel( name, platform, openMMBrookInterface );
// harmonic bonds
} else if( name == CalcHarmonicBondForceKernel::Name() ){
return new BrookCalcHarmonicBondForceKernel( name, platform, openMMBrookInterface, context.getSystem() );
// angle bonds
} else if( name == CalcHarmonicAngleForceKernel::Name() ){
return new BrookCalcHarmonicAngleForceKernel( name, platform, openMMBrookInterface, context.getSystem() );
// periodic torsion bonds
} else if( name == CalcPeriodicTorsionForceKernel::Name() ){
return new BrookCalcPeriodicTorsionForceKernel( name, platform, openMMBrookInterface, context.getSystem() );
// RB torsion bonds
} else if( name == CalcRBTorsionForceKernel::Name() ){
return new BrookCalcRBTorsionForceKernel( name, platform, openMMBrookInterface, context.getSystem() );
// nonbonded
} else if( name == CalcNonbondedForceKernel::Name() ){
return new BrookCalcNonbondedForceKernel( name, platform, openMMBrookInterface, context.getSystem() );
// GBSA OBC
} else if( name == CalcGBSAOBCForceKernel::Name() ){
return new BrookCalcGBSAOBCForceKernel( name, platform, openMMBrookInterface, context.getSystem() );
// Verlet integrator
} else if( name == IntegrateVerletStepKernel::Name() ){
return new BrookIntegrateVerletStepKernel( name, platform, openMMBrookInterface, context.getSystem() );
// Brownian integrator
} else if( name == IntegrateBrownianStepKernel::Name() ){
// return new BrookIntegrateBrownianStepKernel( name, platform, openMMBrookInterface );
// Andersen thermostat
} else if( name == ApplyAndersenThermostatKernel::Name() ){
// return new BrookIntegrateAndersenThermostatKernel( name, platform, openMMBrookInterface );
// Langevin integrator
} else if( name == IntegrateLangevinStepKernel::Name() ){
return new BrookIntegrateLangevinStepKernel( name, platform, openMMBrookInterface, context.getSystem() );
// Remove com
} else if( name == RemoveCMMotionKernel::Name() ){
return new BrookRemoveCMMotionKernel( name, platform, openMMBrookInterface, context.getSystem() );
// KE calculator
} else if( name == CalcKineticEnergyKernel::Name() ){
return new BrookCalcKineticEnergyKernel( name, platform, openMMBrookInterface, context.getSystem() );
}
(void) fprintf( stderr, "%s: name=<%s> not found.", methodName.c_str(), name.c_str() );
(void) fflush( stderr );
return NULL;
}
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Mark Friedrichs, Mike Houston *
* Contributors: *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* -------------------------------------------------------------------------- */
#include "BrookLangevinDynamics.h"
#include "BrookPlatform.h"
#include "openmm/OpenMMException.h"
#include "BrookStreamImpl.h"
#include "kernels/kshakeh.h"
#include "kernels/kupdatesd.h"
#include "kernels/kcommon.h"
#include <sstream>
// use random number generator
#include "../../reference/src/SimTKUtilities/SimTKOpenMMUtilities.h"
using namespace OpenMM;
using namespace std;
/**
*
* Constructor
*
*/
BrookLangevinDynamics::BrookLangevinDynamics( ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookLangevinDynamics::BrookLangevinDynamics";
BrookOpenMMFloat zero = (BrookOpenMMFloat) 0.0;
BrookOpenMMFloat one = (BrookOpenMMFloat) 1.0;
BrookOpenMMFloat oneMinus = (BrookOpenMMFloat) -1.0;
// ---------------------------------------------------------------------------------------
_numberOfParticles = -1;
_internalStepCount = 0;
// mark stream dimension variables as unset
_sdParticleStreamWidth = -1;
_sdParticleStreamHeight = -1;
_sdParticleStreamSize = -1;
for( int ii = 0; ii < LastStreamIndex; ii++ ){
_sdStreams[ii] = NULL;
}
for( int ii = 0; ii < MaxDerivedParameters; ii++ ){
_derivedParameters[ii] = oneMinus;
}
_temperature = oneMinus;
_stepSize = oneMinus;
_tau = oneMinus;
// setup inverse sqrt masses
_inverseSqrtMasses = NULL;
// set randomNumber seed
_randomNumberSeed = 1393;
//_randomNumberSeed = randomNumberSeed ? randomNumberSeed : 1393;
//SimTKOpenMMUtilities::setRandomNumberSeed( randomNumberSeed );
}
/**
* Destructor
*
*/
BrookLangevinDynamics::~BrookLangevinDynamics( ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookLangevinDynamics::~BrookLangevinDynamics";
// ---------------------------------------------------------------------------------------
for( int ii = 0; ii < LastStreamIndex; ii++ ){
delete _sdStreams[ii];
}
delete[] _inverseSqrtMasses;
}
/**
* Get tau
*
* @return tau
*
*/
BrookOpenMMFloat BrookLangevinDynamics::getTau( void ) const {
return _tau;
}
/**
* Get friction
*
* @return friction
*
*/
BrookOpenMMFloat BrookLangevinDynamics::getFriction( void ) const {
static const BrookOpenMMFloat zero = static_cast<BrookOpenMMFloat>( 0.0 );
static const BrookOpenMMFloat one = static_cast<BrookOpenMMFloat>( 1.0 );
return ( (_tau == zero) ? zero : (one/_tau) );
}
/**
* Get temperature
*
* @return temperature
*
*/
BrookOpenMMFloat BrookLangevinDynamics::getTemperature( void ) const {
return _temperature;
}
/**
* Get stepSize
*
* @return stepSize
*
*/
BrookOpenMMFloat BrookLangevinDynamics::getStepSize( void ) const {
return _stepSize;
}
/**
* Set tau
*
* @param tau new tau value
*
* @return DefaultReturnValue
*
*/
int BrookLangevinDynamics::_setTau( BrookOpenMMFloat tau ){
_tau = tau;
return DefaultReturnValue;
}
/**
* Set friction = 1/tau
*
* @param friction new friction value
*
* @return DefaultReturnValue
*
*/
int BrookLangevinDynamics::_setFriction( BrookOpenMMFloat friction ){
_tau = static_cast<BrookOpenMMFloat>( (friction != 0.0) ? 1.0/friction : 0.0);
return DefaultReturnValue;
}
/**
* Set temperature
*
* @parameter temperature
*
* @return DefaultReturnValue
*
*/
int BrookLangevinDynamics::_setTemperature( BrookOpenMMFloat temperature ){
_temperature = temperature;
return DefaultReturnValue;
}
/**
* Set stepSize
*
* @param stepSize
*
* @return DefaultReturnValue
*
*/
int BrookLangevinDynamics::_setStepSize( BrookOpenMMFloat stepSize ){
_stepSize = stepSize;
return DefaultReturnValue;
}
/**
* Update derived parameters
*
* @return DefaultReturnValue
*
* @throw OpenMMException if tau too small
*
*/
int BrookLangevinDynamics::_updateDerivedParameters( void ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "\nBrookLangevinDynamics::_updateDerivedParameters";
static const BrookOpenMMFloat zero = 0.0;
static const BrookOpenMMFloat one = 1.0;
static const BrookOpenMMFloat two = 2.0;
static const BrookOpenMMFloat three = 3.0;
static const BrookOpenMMFloat four = 4.0;
static const BrookOpenMMFloat half = 0.5;
float epsilon = 1.0e-08f;
// ---------------------------------------------------------------------------------------
BrookOpenMMFloat tau = getTau();
BrookOpenMMFloat temperature = getTemperature();
BrookOpenMMFloat stepSize = getStepSize();
if( fabsf( (float) tau ) < epsilon ){
std::stringstream message;
message << methodName << " tau=" << tau << " too small.";
throw OpenMMException( message.str() );
}
_derivedParameters[GDT] = stepSize/tau;
_derivedParameters[EPH] = EXP( half*_derivedParameters[GDT] );
_derivedParameters[EMH] = EXP( -half*_derivedParameters[GDT] );
_derivedParameters[EM] = EXP( -_derivedParameters[GDT] );
_derivedParameters[EP] = EXP( _derivedParameters[GDT] );
if( _derivedParameters[GDT] >= static_cast<BrookOpenMMFloat>( 0.1 ) ){
BrookOpenMMFloat term1 = _derivedParameters[EPH] - one;
term1 *= term1;
_derivedParameters[B] = _derivedParameters[GDT]*(_derivedParameters[EP] - one) - four*term1;
_derivedParameters[C] = _derivedParameters[GDT] - three + four*_derivedParameters[EMH] - _derivedParameters[EM];
_derivedParameters[D] = two - _derivedParameters[EPH] - _derivedParameters[EMH];
} else {
BrookOpenMMFloat term1 = half*_derivedParameters[GDT];
BrookOpenMMFloat term2 = term1*term1;
BrookOpenMMFloat term4 = term2*term2;
BrookOpenMMFloat third = static_cast<BrookOpenMMFloat>( ( 1.0/3.0 ) );
BrookOpenMMFloat o7_9 = static_cast<BrookOpenMMFloat>( ( 7.0/9.0 ) );
BrookOpenMMFloat o1_12 = static_cast<BrookOpenMMFloat>( ( 1.0/12.0 ) );
BrookOpenMMFloat o17_90 = static_cast<BrookOpenMMFloat>( ( 17.0/90.0 ) );
BrookOpenMMFloat o7_30 = static_cast<BrookOpenMMFloat>( ( 7.0/30.0 ) );
BrookOpenMMFloat o31_1260 = static_cast<BrookOpenMMFloat>( ( 31.0/1260.0 ) );
BrookOpenMMFloat o_360 = static_cast<BrookOpenMMFloat>( ( 1.0/360.0 ) );
_derivedParameters[B] = term4*( third + term1*( third + term1*( o17_90 + term1*o7_9 )));
_derivedParameters[C] = term2*term1*( two*third + term1*( -half + term1*( o7_30 + term1*(-o1_12 + term1*o31_1260 ))));
_derivedParameters[D] = term2*( -one + term2*(-o1_12 - term2*o_360));
}
BrookOpenMMFloat kT = static_cast<BrookOpenMMFloat>( BOLTZ )*temperature;
_derivedParameters[V] = SQRT( kT*( one - _derivedParameters[EM]) );
_derivedParameters[X] = tau*SQRT( kT*_derivedParameters[C] );
_derivedParameters[Yv] = SQRT( kT*_derivedParameters[B]/_derivedParameters[C] );
_derivedParameters[Yx] = tau*SQRT( kT*_derivedParameters[B]/(one - _derivedParameters[EM]) );
_derivedParameters[Sd1pc1] = tau*( one - _derivedParameters[EM] );
_derivedParameters[Sd1pc2] = tau*( _derivedParameters[EPH] - _derivedParameters[EMH] );
if( fabsf( _derivedParameters[Sd1pc2] ) < 1.0e-06 ){
_derivedParameters[Sd1pc2] = tau*_derivedParameters[GDT];
}
_derivedParameters[Sd1pc3] = _derivedParameters[D]/(tau*_derivedParameters[C] );
// if tau was greater than 20000, then _derivedParameters[Sd1pc2] was zero
// using tau*_derivedParameters[GDT] as approximation to tau*( _derivedParameters[EPH] - _derivedParameters[EMH] ) for values in this
// range
if( fabsf( _derivedParameters[Sd1pc2] ) > 1.0e-10 ){
_derivedParameters[Sd2pc1] = one/_derivedParameters[Sd1pc2];
} else {
std::stringstream message;
message << methodName << " Sd1pc2=" << _derivedParameters[Sd1pc2] << " is too small (Sd2pc1 is 1/Sd1pc2)";
throw OpenMMException( message.str() );
}
_derivedParameters[Sd2pc2] = tau*_derivedParameters[D]/( _derivedParameters[EM] - one );
return DefaultReturnValue;
}
/**
* Update parameters -- only way parameters can be set
*
* @param temperature temperature
* @param friction friction
* @param step size step size
*
* @return solute dielectric
*
*/
int BrookLangevinDynamics::updateParameters( double temperature, double friction, double stepSize ){
// ---------------------------------------------------------------------------------------
static int showUpdate = 1;
static int maxShowUpdate = 3;
static const std::string methodName = "\nBrookLangevinDynamics::updateParameters";
// ---------------------------------------------------------------------------------------
_setStepSize( (BrookOpenMMFloat) stepSize );
_setFriction( (BrookOpenMMFloat) friction );
//_setTau( (BrookOpenMMFloat) friction );
_setTemperature( (BrookOpenMMFloat) temperature );
_updateDerivedParameters( );
_updateSdStreams( );
// show update
if( showUpdate && getLog() && (showUpdate++ < maxShowUpdate) ){
std::string contents = getContentsString( );
(void) fprintf( getLog(), "%s contents\n%s", methodName.c_str(), contents.c_str() );
(void) fflush( getLog() );
}
return DefaultReturnValue;
}
/**
*
* Get array of derived parameters indexed by 'DerivedParameters' enums
*
* @return array
*
*/
const BrookOpenMMFloat* BrookLangevinDynamics::getDerivedParameters( void ) const {
// ---------------------------------------------------------------------------------------
// static const std::string methodName = "\nBrookLangevinDynamics::getDerivedParameters";
// ---------------------------------------------------------------------------------------
return _derivedParameters;
}
/**
* Get Particle stream size
*
* @return Particle stream size
*
*/
int BrookLangevinDynamics::getLangevinDynamicsParticleStreamSize( void ) const {
return _sdParticleStreamSize;
}
/**
* Get particle stream width
*
* @return particle stream width
*
*/
int BrookLangevinDynamics::getLangevinDynamicsParticleStreamWidth( void ) const {
return _sdParticleStreamWidth;
}
/**
* Get particle stream height
*
* @return particle stream height
*/
int BrookLangevinDynamics::getLangevinDynamicsParticleStreamHeight( void ) const {
return _sdParticleStreamHeight;
}
/**
* Get SDPC1 stream
*
* @return SDPC1 stream
*
*/
BrookFloatStreamInternal* BrookLangevinDynamics::getSDPC1Stream( void ) const {
return _sdStreams[SDPC1Stream];
}
/**
* Get SDPC2 stream
*
* @return SDPC2 stream
*
*/
BrookFloatStreamInternal* BrookLangevinDynamics::getSDPC2Stream( void ) const {
return _sdStreams[SDPC2Stream];
}
/**
* Get SD2X stream
*
* @return SD2X stream
*
*/
BrookFloatStreamInternal* BrookLangevinDynamics::getSD2XStream( void ) const {
return _sdStreams[SD2XStream];
}
/**
* Get SD1V stream
*
* @return SD1V stream
*
*/
BrookFloatStreamInternal* BrookLangevinDynamics::getSD1VStream( void ) const {
return _sdStreams[SD1VStream];
}
/**
* Get VPrime stream
*
* @return Vprime stream
*
*/
BrookFloatStreamInternal* BrookLangevinDynamics::getVPrimeStream( void ) const {
return _sdStreams[VPrimeStream];
}
/**
* Get XPrime stream
*
* @return Xprime stream
*
*/
BrookFloatStreamInternal* BrookLangevinDynamics::getXPrimeStream( void ) const {
return _sdStreams[XPrimeStream];
}
/**
* Get InverseMass stream
*
* @return inverse mass stream
*
*/
BrookFloatStreamInternal* BrookLangevinDynamics::getInverseMassStream( void ) const {
return _sdStreams[InverseMassStream];
}
/**
* Initialize stream dimensions
*
* @param numberOfParticles number of particles
* @param platform platform
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
*/
int BrookLangevinDynamics::_initializeStreamSizes( int numberOfParticles, const Platform& platform ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookLangevinDynamics::_initializeStreamSizes";
// ---------------------------------------------------------------------------------------
_sdParticleStreamSize = getParticleStreamSize( platform );
_sdParticleStreamWidth = getParticleStreamWidth( platform );
_sdParticleStreamHeight = getParticleStreamHeight( platform );
return DefaultReturnValue;
}
/**
* Initialize stream dimensions
*
* @param numberOfParticles number of particles
* @param platform platform
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
*/
//std::string BrookLangevinDynamics::_getDerivedParametersString( BrookLangevinDynamics::DerivedParameters derivedParametersIndex ) const {
std::string BrookLangevinDynamics::_getDerivedParametersString( int derivedParametersIndex ) const {
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookLangevinDynamics::_getDerivedParametersString";
// ---------------------------------------------------------------------------------------
std::string returnString;
switch( derivedParametersIndex ){
case GDT:
returnString = "GDT";
break;
case EPH:
returnString = "EPH";
break;
case EMH:
returnString = "EMH";
break;
case EP:
returnString = "EP";
break;
case EM:
returnString = "EM";
break;
case B:
returnString = "B";
break;
case C:
returnString = "C";
break;
case D:
returnString = "D";
break;
case V:
returnString = "V";
break;
case X:
returnString = "X";
break;
case Yv:
returnString = "Yv";
break;
case Yx:
returnString = "Yx";
break;
case Sd1pc1:
returnString = "Sd1pc1";
break;
case Sd1pc2:
returnString = "Sd1pc2";
break;
case Sd1pc3:
returnString = "Sd1pc3";
break;
case Sd2pc1:
returnString = "Sd2pc1";
break;
case Sd2pc2:
returnString = "Sd2pc2";
break;
default:
returnString = "Unknown";
break;
}
return returnString;
}
/**
* Initialize streams
*
* @param platform platform
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
*/
int BrookLangevinDynamics::_initializeStreams( const Platform& platform ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookLangevinDynamics::_initializeStreams";
BrookOpenMMFloat dangleValue = (BrookOpenMMFloat) 0.0;
// ---------------------------------------------------------------------------------------
int sdParticleStreamSize = getLangevinDynamicsParticleStreamSize();
int sdParticleStreamWidth = getLangevinDynamicsParticleStreamWidth();
_sdStreams[SDPC1Stream] = new BrookFloatStreamInternal( BrookCommon::SDPC1Stream,
sdParticleStreamSize, sdParticleStreamWidth,
BrookStreamInternal::Float2, dangleValue );
_sdStreams[SDPC2Stream] = new BrookFloatStreamInternal( BrookCommon::SDPC2Stream,
sdParticleStreamSize, sdParticleStreamWidth,
BrookStreamInternal::Float2, dangleValue );
_sdStreams[SD2XStream] = new BrookFloatStreamInternal( BrookCommon::SD2XStream,
sdParticleStreamSize, sdParticleStreamWidth,
BrookStreamInternal::Float3, dangleValue );
_sdStreams[SD1VStream] = new BrookFloatStreamInternal( BrookCommon::SD1VStream,
sdParticleStreamSize, sdParticleStreamWidth,
BrookStreamInternal::Float3, dangleValue );
_sdStreams[VPrimeStream] = new BrookFloatStreamInternal( BrookCommon::VPrimeStream,
sdParticleStreamSize, sdParticleStreamWidth,
BrookStreamInternal::Float3, dangleValue );
_sdStreams[XPrimeStream] = new BrookFloatStreamInternal( BrookCommon::XPrimeStream,
sdParticleStreamSize, sdParticleStreamWidth,
BrookStreamInternal::Float3, dangleValue );
_sdStreams[InverseMassStream] = new BrookFloatStreamInternal( BrookCommon::InverseMassStream,
sdParticleStreamSize, sdParticleStreamWidth,
BrookStreamInternal::Float, dangleValue );
return DefaultReturnValue;
}
/**
* Update sd streams -- called after parameters change
*
* @return ErrorReturnValue if error, else DefaultReturnValue
*
*/
int BrookLangevinDynamics::_updateSdStreams( void ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookLangevinDynamics::_updateSdStreams";
// ---------------------------------------------------------------------------------------
int sdParticleStreamSize = getLangevinDynamicsParticleStreamSize();
// create and initialize sdpc streams
BrookOpenMMFloat* sdpc[2];
for( int ii = 0; ii < 2; ii++ ){
sdpc[ii] = new BrookOpenMMFloat[2*sdParticleStreamSize];
memset( sdpc[ii], 0, 2*sdParticleStreamSize*sizeof( BrookOpenMMFloat ) );
}
BrookOpenMMFloat* inverseMass = new BrookOpenMMFloat[sdParticleStreamSize];
memset( inverseMass, 0, sdParticleStreamSize*sizeof( BrookOpenMMFloat ) );
const BrookOpenMMFloat* derivedParameters = getDerivedParameters( );
int numberOfParticles = getNumberOfParticles();
int index = 0;
for( int ii = 0; ii < numberOfParticles; ii++, index += 2 ){
sdpc[0][index] = _inverseSqrtMasses[ii]*( static_cast<BrookOpenMMFloat> (derivedParameters[Yv]) );
sdpc[0][index+1] = _inverseSqrtMasses[ii]*( static_cast<BrookOpenMMFloat> (derivedParameters[V]) );
sdpc[1][index] = _inverseSqrtMasses[ii]*( static_cast<BrookOpenMMFloat> (derivedParameters[Yx]) );
sdpc[1][index+1] = _inverseSqrtMasses[ii]*( static_cast<BrookOpenMMFloat> (derivedParameters[X]) );
inverseMass[ii] = _inverseSqrtMasses[ii]*_inverseSqrtMasses[ii];
}
_sdStreams[SDPC1Stream]->loadFromArray( sdpc[0] );
_sdStreams[SDPC2Stream]->loadFromArray( sdpc[1] );
_sdStreams[InverseMassStream]->loadFromArray( inverseMass );
for( int ii = 0; ii < 2; ii++ ){
delete[] sdpc[ii];
}
delete[] inverseMass;
// initialize SD2X
BrookOpenMMFloat* sd2x = new BrookOpenMMFloat[3*sdParticleStreamSize];
//SimTKOpenMMUtilities::setRandomNumberSeed( (uint32_t) getRandomNumberSeed() );
memset( sd2x, 0, 3*sdParticleStreamSize*sizeof( BrookOpenMMFloat ) );
index = 0;
int useFixedRandomValue = 0;
if( useFixedRandomValue ){
// diagnostics only!
BrookOpenMMFloat fixedRandomValue = static_cast<BrookOpenMMFloat>( 0.1 );
for( int ii = 0; ii < numberOfParticles; ii++, index += 3 ){
BrookOpenMMFloat value = _inverseSqrtMasses[ii]*derivedParameters[X]*fixedRandomValue;
sd2x[index] = value;
sd2x[index+1] = value;
sd2x[index+2] = value;
}
// print message letting user know non-random value being used
FILE* log = getLog() ? getLog() : stderr;
(void) fprintf( log, "%s using fixed 'random value'=%.3f to initialize sd2x\n", methodName.c_str(), fixedRandomValue );
} else {
for( int ii = 0; ii < numberOfParticles; ii++, index += 3 ){
sd2x[index] = _inverseSqrtMasses[ii]*derivedParameters[X]*( static_cast<BrookOpenMMFloat> (SimTKOpenMMUtilities::getNormallyDistributedRandomNumber()) );
sd2x[index+1] = _inverseSqrtMasses[ii]*derivedParameters[X]*( static_cast<BrookOpenMMFloat> (SimTKOpenMMUtilities::getNormallyDistributedRandomNumber()) );
sd2x[index+2] = _inverseSqrtMasses[ii]*derivedParameters[X]*( static_cast<BrookOpenMMFloat> (SimTKOpenMMUtilities::getNormallyDistributedRandomNumber()) );
}
}
_sdStreams[SD2XStream]->loadFromArray( sd2x );
delete[] sd2x;
return DefaultReturnValue;
}
/**
* Set masses
*
* @param masses particle masses
*
*/
int BrookLangevinDynamics::_setInverseSqrtMasses( const std::vector<double>& masses ){
// ---------------------------------------------------------------------------------------
//static const std::string methodName = "BrookLangevinDynamics::_setInverseSqrtMasses";
BrookOpenMMFloat zero = static_cast<BrookOpenMMFloat>( 0.0 );
BrookOpenMMFloat one = static_cast<BrookOpenMMFloat>( 1.0 );
// ---------------------------------------------------------------------------------------
// setup inverse sqrt masses
_inverseSqrtMasses = new BrookOpenMMFloat[masses.size()];
int index = 0;
for( std::vector<double>::const_iterator ii = masses.begin(); ii != masses.end(); ii++, index++ ){
if( *ii != 0.0 ){
BrookOpenMMFloat value = static_cast<BrookOpenMMFloat>(*ii);
_inverseSqrtMasses[index] = ( SQRT( one/value ) );
} else {
_inverseSqrtMasses[index] = zero;
}
}
return DefaultReturnValue;
}
/*
* Setup of LangevinDynamics parameters
*
* @param masses masses
* @param platform Brook platform
*
* @return nonzero value if error
*
* */
int BrookLangevinDynamics::setup( const std::vector<double>& masses, const Platform& platform ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookLangevinDynamics::setup";
// ---------------------------------------------------------------------------------------
const BrookPlatform& brookPlatform = dynamic_cast<const BrookPlatform&> (platform);
setLog( brookPlatform.getLog() );
int numberOfParticles = (int) masses.size();
setNumberOfParticles( numberOfParticles );
// set stream sizes and then create streams
_initializeStreamSizes( numberOfParticles, platform );
_initializeStreams( platform );
_setInverseSqrtMasses( masses );
return DefaultReturnValue;
}
/**
* Get T
*
* @param velocities velocities
* @param inverseMassStream inverse masses
* @param numberOfConstraints number of constraints
*
* @return temperature
*/
float BrookLangevinDynamics::getTemperature( BrookStreamInternal* velocities, BrookFloatStreamInternal* inverseMassStream,
int numberOfConstraints ) const {
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookLangevinDynamics::getTemperature";
// ---------------------------------------------------------------------------------------
void* dataArrayV = velocities->getData( 1 );
float* velocitiesI = (float*) dataArrayV;
void* inverseMassStreamV = inverseMassStream->getData( 1 );
float* inverseMassStreamI = (float*) inverseMassStreamV;
float ke = 0.0f;
int index = 0;
int numberOfParticles = getNumberOfParticles();
for( int ii = 0; ii < numberOfParticles; ii++, index += 3 ){
ke += (velocitiesI[index]*velocitiesI[index] + velocitiesI[index+1]*velocitiesI[index+1] + velocitiesI[index+2]*velocitiesI[index+2] )/inverseMassStreamI[ii];
}
int degreesOfFreedom = 3*getNumberOfParticles() - numberOfConstraints;
float denominator = 1.0f/( ((float) BOLTZ)*((float) ( degreesOfFreedom )) );
//(void) fprintf( stderr, "%s ke=%.5e T=%.3f dof=%d\n", methodName.c_str(), ke, (ke*denominator), degreesOfFreedom );
ke *= denominator;
return ke;
}
/**
* Remove velocity com (diagnostics)
*
* @param velocities velocities
* @param inverseMassStream inverse masses
*
* @return DefaultReturnValue
*/
int BrookLangevinDynamics::removeCom( BrookStreamInternal* velocities, BrookFloatStreamInternal* inverseMassStream ) const {
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookLangevinDynamics::removeCom";
// ---------------------------------------------------------------------------------------
void* dataArrayV = velocities->getData( 1 );
float* velocitiesI = (float*) dataArrayV;
void* inverseMassStreamV = inverseMassStream->getData( 1 );
float* inverseMassStreamI = (float*) inverseMassStreamV;
float totalMass = 0.0f;
float com[3] = { 0.0f, 0.0f, 0.0f };
int index = 0;
for( int ii = 0; ii < getNumberOfParticles(); ii++ ){
float mass = 1.0f/inverseMassStreamI[ii];
totalMass += mass;
com[0] += mass*velocitiesI[index];
com[1] += mass*velocitiesI[index+1];
com[2] += mass*velocitiesI[index+2];
index += 3;
}
totalMass = 1.0f/totalMass;
com[0] *= totalMass;
com[1] *= totalMass;
com[2] *= totalMass;
index = 0;
double* newVelocities = new double[velocities->getStreamSize()*velocities->getWidth()];
memset( newVelocities, 0, sizeof( double )*velocities->getStreamSize()*velocities->getWidth() );
for( int ii = 0; ii < getNumberOfParticles(); ii++ ){
newVelocities[index] = (double) velocitiesI[index] - com[0];
newVelocities[index+1] = (double) velocitiesI[index+1] - com[1];
newVelocities[index+2] = (double) velocitiesI[index+2] - com[2];
index += 3;
}
velocities->loadFromArray( newVelocities );
dataArrayV = velocities->getData( 1 );
velocitiesI = (float*) dataArrayV;
/*
(void) fprintf( stderr, "%s readback\n", methodName.c_str() );
for( int ii = 0; ii < velocities->getStreamSize()*3; ii += 3 ){
(void) fprintf( stderr, "%s %d velocitiesI[%14.5e %14.5e %14.5e]\n", methodName.c_str(), ii/3, velocitiesI[ii], velocitiesI[ii+1], velocitiesI[ii+2] );
}
*/
velocities->loadFromArray( newVelocities );
delete[] newVelocities;
return DefaultReturnValue;
}
/**
* Reset velocities (diagnostics)
*
* @param velocities velocities
*
* @return DefaultReturnValue
*/
int BrookLangevinDynamics::resetVelocities( BrookStreamInternal* velocities ) const {
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookLangevinDynamics::resetVelocities";
// ---------------------------------------------------------------------------------------
// reset velocities to determinisitic values
// note use of double instead of float for the load array
double* newVelocities = new double[velocities->getStreamSize()*velocities->getWidth()];
memset( newVelocities, 0, sizeof( double )*velocities->getStreamSize()*velocities->getWidth() );
for( int ii = 1; ii <= 3*getNumberOfParticles(); ii++ ){
int jj = ii % 10;
double sign = jj % 2 ? 0.1 : -0.1;
newVelocities[ii-1] = sign*( (double) jj);
}
velocities->loadFromArray( newVelocities );
delete[] newVelocities;
return DefaultReturnValue;
}
/*
* Get contents of object
*
* @param level level of dump
*
* @return string containing contents
*
* */
std::string BrookLangevinDynamics::getContentsString( int level ) const {
// ---------------------------------------------------------------------------------------
static const std::string methodName = "BrookLangevinDynamics::getContentsString";
static const unsigned int MAX_LINE_CHARS = 256;
char value[MAX_LINE_CHARS];
static const char* Set = "Set";
static const char* NotSet = "Not set";
// ---------------------------------------------------------------------------------------
std::stringstream message;
std::string tab = " ";
#ifdef _MSC_VER
#define LOCAL_SPRINTF(a,b,c) sprintf_s( (a), MAX_LINE_CHARS, (b), (c) );
#else
#define LOCAL_SPRINTF(a,b,c) sprintf( (a), (b), (c) );
#endif
(void) LOCAL_SPRINTF( value, "%d", getNumberOfParticles() );
message << _getLine( tab, "Number of particles:", value );
(void) LOCAL_SPRINTF( value, "%d", getParticleStreamWidth() );
message << _getLine( tab, "Particle stream width:", value );
(void) LOCAL_SPRINTF( value, "%d", getParticleStreamHeight() );
message << _getLine( tab, "Particle stream height:", value );
(void) LOCAL_SPRINTF( value, "%d", getParticleStreamSize() );
message << _getLine( tab, "Particle stream size:", value );
(void) LOCAL_SPRINTF( value, "%.5f", getTau() );
message << _getLine( tab, "Tau:", value );
(void) LOCAL_SPRINTF( value, "%.5f", getTemperature() );
message << _getLine( tab, "Temperature:", value );
(void) LOCAL_SPRINTF( value, "%.5f", getStepSize() );
message << _getLine( tab, "Step size:", value );
const BrookOpenMMFloat* derivedParameters = getDerivedParameters();
for( int ii = 0; ii < MaxDerivedParameters; ii++ ){
(void) LOCAL_SPRINTF( value, "%.5e", derivedParameters[ii] );
message << _getLine( tab, _getDerivedParametersString( ii ), value );
}
(void) LOCAL_SPRINTF( value, "%.5f", getTemperature() );
message << _getLine( tab, "Temperature:", value );
message << _getLine( tab, "Log:", (getLog() ? Set : NotSet) );
message << _getLine( tab, "SDPC1:", (getSDPC1Stream() ? Set : NotSet) );
message << _getLine( tab, "SDPC2:", (getSDPC2Stream() ? Set : NotSet) );
message << _getLine( tab, "SD2X:", (getSD2XStream() ? Set : NotSet) );
message << _getLine( tab, "SD1V:", (getSD1VStream() ? Set : NotSet) );
for( int ii = 0; ii < LastStreamIndex; ii++ ){
message << std::endl;
if( _sdStreams[ii] ){
message << _sdStreams[ii]->getContentsString( );
}
}
#undef LOCAL_SPRINTF
return message.str();
}
/**
* Update
*
* @param positions particle positions
* @param velocities particle velocities
* @param forces particle forces
* @param brookShakeAlgorithm BrookShakeAlgorithm reference
* @param brookRandomNumberGenerator BrookRandomNumberGenerator reference
*
* @return DefaultReturnValue
*
*/
int BrookLangevinDynamics::update( BrookStreamImpl& positionStream, BrookStreamImpl& velocityStream,
BrookStreamImpl& forceStream,
BrookShakeAlgorithm& brookShakeAlgorithm,
BrookRandomNumberGenerator& brookRandomNumberGenerator ){
// ---------------------------------------------------------------------------------------
static const std::string methodName = "\nBrookLangevinDynamics::update";
int printOn = 0;
FILE* log;
// ---------------------------------------------------------------------------------------
_internalStepCount++;
//setLog( stderr );
if( printOn && getLog() ){
log = getLog();
} else {
printOn = 0;
}
const BrookOpenMMFloat* derivedParameters = getDerivedParameters();
if( printOn ){
static int showAux = 1;
if( printOn && showAux ){
(void) fprintf( log, "%s step=%d shake=%d\n", methodName.c_str(), _internalStepCount, brookShakeAlgorithm.getNumberOfConstraints() );
(void) fflush( log );
}
// show update
if( showAux ){
showAux = 0;
std::string contents = getContentsString( );
(void) fprintf( log, "%s step=%d contents\n%s", methodName.c_str(), _internalStepCount, contents.c_str() );
contents = brookRandomNumberGenerator.getContentsString( );
(void) fprintf( log, "%s step=%d RNG contents\n%s", methodName.c_str(), _internalStepCount, contents.c_str() );
// brookRandomNumberGenerator.getRandomNumberStream( brookRandomNumberGenerator.getRvStreamIndex() )->printToFile( log );
contents = brookShakeAlgorithm.getContentsString( );
(void) fprintf( log, "%s step=%d Shake contents\n%s", methodName.c_str(), _internalStepCount, contents.c_str() );
(void) fflush( log );
}
}
// diagnostics
if( 0 && _internalStepCount == 1 ){
//resetVelocities( velocityStream.getBrookStreamInternal() );
std::string velocityFileName = "kupdate_sd1_strV.in";
std::string rvName0 = "kupdate_sd1_0.fgauss.in";
std::string rvName1 = "kupdate_sd1_1.fgauss.in";
std::string sd2xName = "kupdate_sd1_strSD2X.in";
velocityStream.getBrookStreamInternal()->loadStreamGivenFileName( velocityFileName );
brookRandomNumberGenerator.getRandomNumberStream( 0 )->loadStreamGivenFileName( rvName0 );
brookRandomNumberGenerator.getRandomNumberStream( 1 )->loadStreamGivenFileName( rvName1 );
getSD2XStream()->loadStreamGivenFileName( sd2xName );
}
// more diagnostics
if( 0 && (_internalStepCount % 10) == 0 ){
FILE* log1 = stderr;
(void) fprintf( log1, "\nVelocityStream %d XX\n", _internalStepCount ); fflush( log1 );
BrookStreamInternal* brookStreamInternalPos = velocityStream.getBrookStreamInternal();
float temperature = getTemperature( brookStreamInternalPos, getInverseMassStream(), brookShakeAlgorithm.getNumberOfConstraints() );
// removeCom( brookStreamInternalPos, getInverseMassStream() );
float temperaturePost = getTemperature( brookStreamInternalPos, getInverseMassStream(), brookShakeAlgorithm.getNumberOfConstraints() );
(void) fprintf( log1, "\nVelocityStream %d Tp=%.3f %.3f\n", _internalStepCount, temperature, temperaturePost );
(void) fprintf( log1, "\n%s step=%d Post kupdate_sd1_fix1: particleStrW=%3d rngStrW=%3d rngOff=%5d "
"EM=%12.5e Sd1pc[]=[%12.5e %12.5e %12.5e]", methodName.c_str(), _internalStepCount,
getLangevinDynamicsParticleStreamWidth(),
brookRandomNumberGenerator.getRandomNumberStreamWidth(),
brookRandomNumberGenerator.getRvStreamOffset(),
derivedParameters[EM], derivedParameters[Sd1pc1], derivedParameters[Sd1pc2], derivedParameters[Sd1pc3] );
(void) fprintf( log1, "\nRvStreamIndex=%d step=%d\n", brookRandomNumberGenerator.getRvStreamIndex(), _internalStepCount );
fflush( log1 );
}
// first integration step
kupdate_sd1_fix1(
(float) getLangevinDynamicsParticleStreamWidth(),
(float) brookRandomNumberGenerator.getRandomNumberStreamWidth(),
(float) brookRandomNumberGenerator.getRvStreamOffset(),
derivedParameters[EM],
derivedParameters[Sd1pc1],
derivedParameters[Sd1pc2],
derivedParameters[Sd1pc3],
getSDPC1Stream()->getBrookStream(),
brookRandomNumberGenerator.getRandomNumberStream( brookRandomNumberGenerator.getRvStreamIndex() )->getBrookStream(),
getSD2XStream()->getBrookStream(),
positionStream.getBrookStream(),
forceStream.getBrookStream(),
velocityStream.getBrookStream(),
getInverseMassStream()->getBrookStream(),
getSD1VStream()->getBrookStream(),
getVPrimeStream()->getBrookStream(),
getXPrimeStream()->getBrookStream() );
// diagnostics
if( 0 && printOn ){
(void) fprintf( log, "\n%s step=%d Post kupdate_sd1_fix1: particleStrW=%3d rngStrW=%3d rngOff=%5d "
"EM=%12.5e Sd1pc[]=[%12.5e %12.5e %12.5e]", methodName.c_str(), _internalStepCount,
getLangevinDynamicsParticleStreamWidth(),
brookRandomNumberGenerator.getRandomNumberStreamWidth(),
brookRandomNumberGenerator.getRvStreamOffset(),
derivedParameters[EM], derivedParameters[Sd1pc1], derivedParameters[Sd1pc2], derivedParameters[Sd1pc3] );
if( _internalStepCount == 1 ){
(void) fprintf( log, "\nSDPC1Stream fixed input sd1 step=%d\n", _internalStepCount );
getSDPC1Stream()->printToFile( log );
(void) fprintf( log, "\nSD2XStream fixed input sd1 step=%d\n", _internalStepCount );
getSD2XStream()->printToFile( log );
(void) fprintf( log, "\nInverseMassStream fixed input sd1 step=%d\n", _internalStepCount );
getInverseMassStream()->printToFile( log );
}
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPositionStream input sd1 step=%d\n", _internalStepCount );
brookStreamInternalPos->printToFile( log );
(void) fprintf( log, "\nForceStream input sd1 step=%d\n", _internalStepCount );
BrookStreamInternal* brookStreamInternalF = forceStream.getBrookStreamInternal();
brookStreamInternalF->printToFile( log );
BrookStreamInternal* brookStreamInternalV = velocityStream.getBrookStreamInternal();
(void) fprintf( log, "\nVelocityStream input sd1 step=%d\n", _internalStepCount );
brookStreamInternalV->printToFile( log );
(void) fprintf( log, "\nSD1VStream output sd1 step=%d\n", _internalStepCount );
getSD1VStream()->printToFile( log );
(void) fprintf( log, "\nVPrimeStream output sd1 step=%d\n", _internalStepCount );
getVPrimeStream()->printToFile( log );
(void) fprintf( log, "\nXPrimeStream output sd1 step=%d\n", _internalStepCount );
getXPrimeStream()->printToFile( log );
if( _internalStepCount == 1 ){
std::vector<BrookStreamInternal*> streams;
streams.push_back( brookStreamInternalPos );
streams.push_back( getXPrimeStream() );
std::stringstream fileNameBaseS;
fileNameBaseS << "Brook_Sd1PreShk_" << _internalStepCount << ".txt";
BrookStreamInternal::printStreamsToFile( fileNameBaseS.str(), streams );
}
(void) fprintf( log, "\nRvStreamIndex=%d step=%d\n", brookRandomNumberGenerator.getRvStreamIndex(), _internalStepCount );
// brookRandomNumberGenerator.getRandomNumberStream( brookRandomNumberGenerator.getRvStreamIndex() )->printToFile( log );
}
// advance random number cursor
brookRandomNumberGenerator.advanceGVCursor( 2*getNumberOfParticles() );
// first Shake step
if( brookShakeAlgorithm.getNumberOfConstraints() > 0 ){
kshakeh_fix1(
(float) brookShakeAlgorithm.getMaxIterations(),
(float) getLangevinDynamicsParticleStreamWidth(),
brookShakeAlgorithm.getShakeTolerance(),
brookShakeAlgorithm.getShakeParticleIndicesStream()->getBrookStream(),
positionStream.getBrookStream(),
getXPrimeStream()->getBrookStream(),
brookShakeAlgorithm.getShakeParticleParameterStream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons0Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons1Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons2Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons3Stream()->getBrookStream() );
// first Shake gather
kshakeh_update1_fix1(
(float) brookShakeAlgorithm.getShakeConstraintStreamWidth(),
brookShakeAlgorithm.getShakeInverseMapStream()->getBrookStream(),
getXPrimeStream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons0Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons1Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons2Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons3Stream()->getBrookStream(),
getXPrimeStream()->getBrookStream() );
if( 0 && printOn ){
(void) fprintf( log, "\n%s Post kshakeh_update1: sw=%d ShkCnstStrW=%3d tol=%.3f maxIt=%d",
methodName.c_str(), getLangevinDynamicsParticleStreamWidth(),
brookShakeAlgorithm.getShakeConstraintStreamWidth(),
brookShakeAlgorithm.getShakeTolerance(), brookShakeAlgorithm.getMaxIterations() );
if( _internalStepCount == 1 ){
(void) fprintf( log, "\nShakeInverseMapStream fixed input sd shake1 at step=%d\n" );
brookShakeAlgorithm.getShakeInverseMapStream()->printToFile( log );
}
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPositionStream input sd shake1 at step=%d\n", _internalStepCount );
brookStreamInternalPos->printToFile( log );
(void) fprintf( log, "\nXPrimeStream output sd shake1 at step=%d\n", _internalStepCount );
getXPrimeStream()->printToFile( log );
(void) fprintf( log, "\nShakeXCons0 output sd shake1 at step=%d\n", _internalStepCount );
brookShakeAlgorithm.getShakeXCons0Stream()->printToFile( log );
(void) fprintf( log, "\nShakeXCons1 output sd shake1 at step=%d\n", _internalStepCount );
brookShakeAlgorithm.getShakeXCons1Stream()->printToFile( log );
(void) fprintf( log, "\nShakeXCons2 output sd shake1 at step=%d\n", _internalStepCount );
brookShakeAlgorithm.getShakeXCons2Stream()->printToFile( log );
(void) fprintf( log, "\nShakeXCons3 output sd shake1 at step=%d\n", _internalStepCount );
brookShakeAlgorithm.getShakeXCons3Stream()->printToFile( log );
if( _internalStepCount < 2 ){
std::vector<BrookStreamInternal*> streams;
streams.push_back( brookStreamInternalPos );
streams.push_back( getXPrimeStream() );
std::stringstream fileNameBaseS;
fileNameBaseS << "Brook_Sd1PostShk_" << _internalStepCount << ".txt";
BrookStreamInternal::printStreamsToFile( fileNameBaseS.str(), streams );
}
}
}
// second integration step
kupdate_sd2_fix1(
(float) getLangevinDynamicsParticleStreamWidth(),
(float) brookRandomNumberGenerator.getRandomNumberStreamWidth(),
(float) brookRandomNumberGenerator.getRvStreamOffset(),
derivedParameters[Sd2pc1],
derivedParameters[Sd2pc2],
getSDPC2Stream()->getBrookStream(),
brookRandomNumberGenerator.getRandomNumberStream( brookRandomNumberGenerator.getRvStreamIndex() )->getBrookStream(),
getSD1VStream()->getBrookStream(),
positionStream.getBrookStream(),
getXPrimeStream()->getBrookStream(),
getVPrimeStream()->getBrookStream(),
getSD2XStream()->getBrookStream(),
velocityStream.getBrookStream(),
getXPrimeStream()->getBrookStream()
);
// diagnostics
if( 0 && printOn ){
(void) fprintf( log, "\n%s step=%d Post kupdate_sd2_fix1: particleStrW=%3d rngStrW=%3d rngOff=%5d "
"Sd2pc[]=[%12.5e %12.5e]", methodName.c_str(), _internalStepCount,
getLangevinDynamicsParticleStreamWidth(),
brookRandomNumberGenerator.getRandomNumberStreamWidth(),
brookRandomNumberGenerator.getRvStreamOffset(),
derivedParameters[Sd2pc1], derivedParameters[Sd2pc2] );
(void) fprintf( log, "\nSDPC2Stream input sd2 step=%d\n", _internalStepCount );
getSDPC2Stream()->printToFile( log );
(void) fprintf( log, "\ngetSD1VStream input sd2 step=%d\n", _internalStepCount );
getSD1VStream()->printToFile( log );
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPositionStream input sd2 step=%d \n", _internalStepCount );
brookStreamInternalPos->printToFile( log );
(void) fprintf( log, "\nVPrimeStream input sd2 step=%d\n", _internalStepCount );
getVPrimeStream()->printToFile( log );
(void) fprintf( log, "\nXPrimeStream output sd2 step=%d\n", _internalStepCount );
getXPrimeStream()->printToFile( log );
(void) fprintf( log, "\nSD2XStream output sd2 step=%d\n", _internalStepCount );
getSD2XStream()->printToFile( log );
BrookStreamInternal* brookStreamInternalVel = velocityStream.getBrookStreamInternal();
(void) fprintf( log, "\nVelocityStream output sd2 step=%d\n", _internalStepCount );
brookStreamInternalVel->printToFile( log );
(void) fprintf( log, "\nRvStreamIndex=%d step=%d\n", brookRandomNumberGenerator.getRvStreamIndex(), _internalStepCount );
// brookRandomNumberGenerator.getRandomNumberStream( brookRandomNumberGenerator.getRvStreamIndex() )->printToFile( log );
if( _internalStepCount < 3 ){
std::vector<BrookStreamInternal*> streams;
streams.push_back( brookStreamInternalVel );
streams.push_back( getXPrimeStream() );
std::stringstream fileNameBaseS;
fileNameBaseS << "Brook_Sd2Out_" << _internalStepCount << ".txt";
BrookStreamInternal::printStreamsToFile( fileNameBaseS.str(), streams );
}
}
// advance random number cursor
brookRandomNumberGenerator.advanceGVCursor( 2*getNumberOfParticles() );
// second Shake step
if( brookShakeAlgorithm.getNumberOfConstraints() > 0 ){
kshakeh_fix1(
(float) brookShakeAlgorithm.getMaxIterations(),
(float) getLangevinDynamicsParticleStreamWidth(),
brookShakeAlgorithm.getShakeTolerance(),
brookShakeAlgorithm.getShakeParticleIndicesStream()->getBrookStream(),
positionStream.getBrookStream(),
getXPrimeStream()->getBrookStream(),
brookShakeAlgorithm.getShakeParticleParameterStream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons0Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons1Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons2Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons3Stream()->getBrookStream() );
// second Shake gather
kshakeh_update2_fix1(
(float) brookShakeAlgorithm.getShakeConstraintStreamWidth(),
brookShakeAlgorithm.getShakeInverseMapStream()->getBrookStream(),
positionStream.getBrookStream(),
getXPrimeStream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons0Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons1Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons2Stream()->getBrookStream(),
brookShakeAlgorithm.getShakeXCons3Stream()->getBrookStream(),
positionStream.getBrookStream() );
// diagnostics
if( 0 && printOn ){
(void) fprintf( log, "\n%s step=%d Post kshakeh_update2_fix1: ShakeConstraintStreamWidth=%3d rngStrW=%3d rngOff=%5d "
"Sd2pc[]=[%12.5e %12.5e]\n", methodName.c_str(), _internalStepCount,
brookShakeAlgorithm.getShakeConstraintStreamWidth(),
brookRandomNumberGenerator.getRandomNumberStreamWidth(),
brookRandomNumberGenerator.getRvStreamOffset(),
derivedParameters[Sd2pc1], derivedParameters[Sd2pc2] );
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
std::string violationString;
brookShakeAlgorithm.checkConstraints( brookStreamInternalPos, violationString, 0.0001f );
(void) fprintf( log, "\nPositionStream output sd shake2 step=%d %s\n", _internalStepCount, violationString.c_str() );
brookStreamInternalPos->printToFile( log );
BrookStreamInternal* brookStreamInternalF = forceStream.getBrookStreamInternal();
std::vector<std::vector<double> > forceStatistics;
brookStreamInternalF->getStatistics( forceStatistics, getNumberOfParticles() );
std::stringstream tag;
tag << _internalStepCount << " Fxx ";
std::string stats = brookStreamInternalF->printStatistics( tag.str(), forceStatistics );
(void) fprintf( log, "\nStep %d Force stats:\n%s", _internalStepCount, stats.c_str() );
brookStreamInternalF->printToFile( log );
brookStreamInternalPos = velocityStream.getBrookStreamInternal();
std::vector<std::vector<double> > velocityStatistics;
brookStreamInternalPos->getStatistics( velocityStatistics, getNumberOfParticles() );
std::stringstream tagV;
tagV << _internalStepCount << " Vxx ";
stats = brookStreamInternalPos->printStatistics( tagV.str(), velocityStatistics );
(void) fprintf( log, "\nStep %d Velocity stats:\n%s", _internalStepCount, stats.c_str() );
float temperature = getTemperature( brookStreamInternalPos, getInverseMassStream(), brookShakeAlgorithm.getNumberOfConstraints() );
(void) fprintf( log, "\nVelocityStream %d T=%.3f\n", _internalStepCount, temperature );
brookStreamInternalPos->printToFile( log );
(void) fprintf( log, "\nXPrimeStream input sd shake2 step=%d\n", _internalStepCount );
getXPrimeStream()->printToFile( log );
// brookRandomNumberGenerator.getRandomNumberStream( brookRandomNumberGenerator.getRvStreamIndex() )->printToFile( log );
}
} else {
// no constraints
if( 0 && printOn ){
(void) fprintf( log, "\n%s Pre ksetStr3 (no constraints)", methodName.c_str() );
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPositionStream\n" );
brookStreamInternalPos->printToFile( log );
}
kadd3( getXPrimeStream()->getBrookStream(), positionStream.getBrookStream(), positionStream.getBrookStream() );
// diagnostics
if( printOn ){
(void) fprintf( log, "\n%s Post ksetStr3 (no constraints)", methodName.c_str() );
(void) fprintf( log, "\nXPrimeStream\n" );
getXPrimeStream()->printToFile( log );
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
(void) fprintf( log, "\nPositionStream\n" );
brookStreamInternalPos->printToFile( log );
// brookRandomNumberGenerator.getRandomNumberStream( brookRandomNumberGenerator.getRvStreamIndex() )->printToFile( log );
}
}
// diagnostics
if( 0 && (_internalStepCount % 1000) == 0 ){
FILE* log1 = stderr;
float epsilon = 1.0e-01f;
BrookStreamInternal* brookStreamInternalPos = positionStream.getBrookStreamInternal();
BrookStreamInternal* brookStreamInternalVel = velocityStream.getBrookStreamInternal();
BrookStreamInternal* brookStreamInternalFrc = forceStream.getBrookStreamInternal();
// check for nan and infinities
int coordinateNans = brookStreamInternalPos->checkForNans( );
int velocityNans = brookStreamInternalVel->checkForNans( );
int forceNans = brookStreamInternalFrc->checkForNans( );
int abort = abs( coordinateNans ) + abs( velocityNans ) + abs( forceNans );
// Shake violations
std::string violationString;
int constraintViolations = brookShakeAlgorithm.checkConstraints( brookStreamInternalPos, violationString, 0.0001f );
abort += abs( constraintViolations );
// check T consistent w/ specified value
float temperature = getTemperature( brookStreamInternalVel, getInverseMassStream(), brookShakeAlgorithm.getNumberOfConstraints() );
if( fabsf( temperature - getTemperature() ) > 2.0f*temperature ){
abort++;
}
// force sums ~ 0?
std::vector<float> sums;
brookStreamInternalFrc->sumColumns( sums );
// check if should abort
(void) fprintf( log1, "%d T=%.3f Nans: x=%d v=%d f=%d ", _internalStepCount, temperature, coordinateNans, velocityNans, forceNans );
(void) fprintf( log1, " Fsum[" );
for( int ii = 0; ii < 3; ii++ ){
if( fabsf( sums[ii] ) > epsilon ){
abort++;
}
(void) fprintf( log1, "%12.4e ", sums[ii] );
}
(void) fprintf( log1, "] %s abort=%d\n", violationString.c_str(), abort );
(void) fflush( log1 );
if( abort ){
int nans[2];
nans[0] = brookRandomNumberGenerator.getRandomNumberStream( 0 )->checkForNans();
nans[1] = brookRandomNumberGenerator.getRandomNumberStream( 1 )->checkForNans();
(void) fprintf( log1, "Aborting: Nans rng: active index=%d %d %d\n", brookRandomNumberGenerator.getRvStreamIndex(), nans[0], nans[1] );
brookStreamInternalPos->printToFile( log1 );
brookStreamInternalVel->printToFile( log1 );
brookStreamInternalFrc->printToFile( log1 );
brookRandomNumberGenerator.getRandomNumberStream( brookRandomNumberGenerator.getRvStreamIndex() )->printToFile( log1 );
exit(1);
}
/*
std::vector<std::vector<double> > velocityStatistics;
brookStreamInternalPos->getStatistics( velocityStatistics, getNumberOfParticles() );
std::stringstream tagV;
tagV << _internalStepCount << " Vxx ";
std::string stats = brookStreamInternalPos->printStatistics( tagV.str(), velocityStatistics );
(void) fprintf( log1, "\nStep %d Velocity stats:\n%s", _internalStepCount, stats.c_str() );
*/
//removeCom( brookStreamInternalPos, getInverseMassStream() );
}
return DefaultReturnValue;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment