Commit 3cb25ad8 authored by Lee-Ping Wang's avatar Lee-Ping Wang
Browse files

Merge branch 'master' of github.com:leeping/openmm

parents 7bfb75c7 24608623
......@@ -93,7 +93,7 @@ FOREACH(EX_ROOT ${F_EXAMPLES})
INSTALL(FILES ${EX_ROOT}.f90 DESTINATION examples)
ENDFOREACH(EX_ROOT ${F_EXAMPLES})
INSTALL(FILES simulateAmber.py simulatePdb.py testInstallation.py argon-chemical-potential.py input.inpcrd input.prmtop input.pdb
INSTALL(FILES simulateAmber.py simulatePdb.py simulateGromacs.py testInstallation.py argon-chemical-potential.py input.inpcrd input.prmtop input.pdb input.gro input.top
DESTINATION examples)
INSTALL(FILES VisualStudio/HelloArgon.vcproj
......
......@@ -15,6 +15,7 @@
# [1] Michael R. Shirts and John D. Chodera. Statistically optimal analysis of samples from multiple equilibrium states.
# J. Chem. Phys. 129:124105 (2008) http://dx.doi.org/10.1063/1.2978177
from __future__ import print_function
from simtk.openmm import *
from simtk.unit import *
import numpy
......@@ -51,15 +52,15 @@ nlambda = len(lambda_values)
volume = nparticles*(sigma**3)/reduced_density
box_edge = volume**(1.0/3.0)
cutoff = min(box_edge*0.49, 2.5*sigma) # Compute cutoff
print "sigma = %s" % sigma
print "box_edge = %s" % box_edge
print "cutoff = %s" % cutoff
print("sigma = %s" % sigma)
print("box_edge = %s" % box_edge)
print("cutoff = %s" % cutoff)
# =============================================================================
# Build systems at each alchemical lambda value.
# =============================================================================
print "Building alchemically-modified systems..."
print("Building alchemically-modified systems...")
alchemical_systems = list() # alchemical_systems[i] is the alchemically-modified System object corresponding to lambda_values[i]
for lambda_value in lambda_values:
# Create argon system where first particle is alchemically modified by lambda_value.
......@@ -112,17 +113,17 @@ for (lambda_index, lambda_value) in enumerate(lambda_values):
context.setPositions(positions)
# Minimize energy from coordinates.
print "Lambda %d/%d : minimizing..." % (lambda_index+1, nlambda)
print("Lambda %d/%d : minimizing..." % (lambda_index+1, nlambda))
LocalEnergyMinimizer.minimize(context)
# Equilibrate.
print "Lambda %d/%d : equilibrating..." % (lambda_index+1, nlambda)
print("Lambda %d/%d : equilibrating..." % (lambda_index+1, nlambda))
integrator.step(nequil_steps)
# Sample.
position_history = list() # position_history[i] is the set of positions after iteration i
for iteration in range(nprod_iterations):
print "Lambda %d/%d : production iteration %d/%d" % (lambda_index+1, nlambda, iteration+1, nprod_iterations)
print("Lambda %d/%d : production iteration %d/%d" % (lambda_index+1, nlambda, iteration+1, nprod_iterations))
# Run dynamics.
integrator.step(nprod_steps)
......@@ -138,7 +139,7 @@ for (lambda_index, lambda_value) in enumerate(lambda_values):
del context, integrator
# Compute reduced potentials of all snapshots at all alchemical states for MBAR.
print "Lambda %d/%d : computing energies at all states..." % (lambda_index+1, nlambda)
print("Lambda %d/%d : computing energies at all states..." % (lambda_index+1, nlambda))
beta = 1.0 / (BOLTZMANN_CONSTANT_kB * AVOGADRO_CONSTANT_NA * temperature) # inverse temperature
for l in range(nlambda):
# Set up Context just to evaluate energies.
......@@ -159,13 +160,13 @@ try:
from timeseries import subsampleCorrelatedData
from pymbar import MBAR
except:
raise "pymbar [https://simtk.org/home/pymbar] must be installed to complete analysis of free energies."
raise ImportError("pymbar [https://simtk.org/home/pymbar] must be installed to complete analysis of free energies.")
# =============================================================================
# Subsample correlated samples to generate uncorrelated subsample.
# =============================================================================
print "Subsampling data to remove correlation..."
print("Subsampling data to remove correlation...")
K = nlambda # number of states
N_k = nprod_iterations*numpy.ones([K], numpy.int32) # N_k[k] is the number of uncorrelated samples at state k
u_kln_subsampled = numpy.zeros([K,K,nprod_iterations], numpy.float64) # subsampled data
......@@ -176,24 +177,24 @@ for k in range(K):
N_k[k] = len(indices)
for l in range(K):
u_kln_subsampled[k,l,0:len(indices)] = u_kln[k,l,indices]
print "Number of uncorrelated samples per state:"
print N_k
print("Number of uncorrelated samples per state:")
print(N_k)
# =============================================================================
# Analyze with MBAR to compute free energy differences and statistical errors.
# =============================================================================
print "Analyzing with MBAR..."
print("Analyzing with MBAR...")
mbar = MBAR(u_kln_subsampled, N_k)
[Deltaf_ij, dDeltaf_ij] = mbar.getFreeEnergyDifferences()
print "Free energy differences (in kT)"
print Deltaf_ij
print "Statistical errors (in kT)"
print dDeltaf_ij
Deltaf_ij, dDeltaf_ij = mbar.getFreeEnergyDifferences()
print("Free energy differences (in kT)")
print(Deltaf_ij)
print("Statistical errors (in kT)")
print(dDeltaf_ij)
# =============================================================================
# Report result.
# =============================================================================
print "Free energy of inserting argon particle: %.3f +- %.3f kT" % (Deltaf_ij[0,K-1], dDeltaf_ij[0,K-1])
print("Free energy of inserting argon particle: %.3f +- %.3f kT" % (Deltaf_ij[0,K-1], dDeltaf_ij[0,K-1]))
from __future__ import print_function
# First make sure OpenMM is installed.
import sys
try:
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
except ImportError as err:
print "Failed to import OpenMM packages:", err.message
print "Make sure OpenMM is installed and the library path is set correctly."
print("Failed to import OpenMM packages:", err.message)
print("Make sure OpenMM is installed and the library path is set correctly.")
sys.exit()
# Create a System for the tests.
......@@ -19,28 +21,28 @@ system = forcefield.createSystem(pdb.topology, nonbondedMethod=PME, nonbondedCut
# List all installed platforms and compute forces with each one.
numPlatforms = Platform.getNumPlatforms()
print "There are", numPlatforms, "Platforms available:"
print
print("There are", numPlatforms, "Platforms available:")
print()
forces = [None]*numPlatforms
for i in range(numPlatforms):
platform = Platform.getPlatform(i)
print i+1, platform.getName(),
print(i+1, platform.getName(), end=" ")
integrator = LangevinIntegrator(300*kelvin, 1/picosecond, 0.002*picoseconds)
try:
simulation = Simulation(pdb.topology, system, integrator, platform)
simulation.context.setPositions(pdb.positions)
forces[i] = simulation.context.getState(getForces=True).getForces()
del simulation
print "- Successfully computed forces"
print("- Successfully computed forces")
except:
print "- Error computing forces with", platform.getName(), "platform"
print("- Error computing forces with", platform.getName(), "platform")
# See how well the platforms agree.
if numPlatforms > 1:
print
print "Median difference in forces between platforms:"
print
print()
print("Median difference in forces between platforms:")
print()
for i in range(numPlatforms):
for j in range(i):
if forces[i] is not None and forces[j] is not None:
......@@ -49,4 +51,6 @@ if numPlatforms > 1:
d = f1-f2
error = sqrt((d[0]*d[0]+d[1]*d[1]+d[2]*d[2])/(f1[0]*f1[0]+f1[1]*f1[1]+f1[2]*f1[2]))
errors.append(error)
print "%s vs. %s: %g" % (Platform.getPlatform(j).getName(), Platform.getPlatform(i).getName(), sorted(errors)[len(errors)/2])
print("{} vs. {}: {:g}".format(Platform.getPlatform(j).getName(),
Platform.getPlatform(i).getName(),
sorted(errors)[len(errors)//2]))
/*
100% free public domain implementation of the SHA-1 algorithm
by Dominik Reichl <dominik.reichl@t-online.de>
Web: http://www.dominik-reichl.de/
Version 2.1 - 2012-06-19
- Deconstructor (resetting internal variables) is now only
implemented if SHA1_WIPE_VARIABLES is defined (which is the
default).
- Renamed inclusion guard to contain a GUID.
- Demo application is now using C++/STL objects and functions.
- Unicode build of the demo application now outputs the hashes of both
the ANSI and Unicode representations of strings.
- Various other demo application improvements.
Version 2.0 - 2012-06-14
- Added 'limits.h' include.
- Renamed inclusion guard and macros for compliancy (names beginning
with an underscore are reserved).
Version 1.9 - 2011-11-10
- Added Unicode test vectors.
- Improved support for hashing files using the HashFile method that
are larger than 4 GB.
- Improved file hashing performance (by using a larger buffer).
- Disabled unnecessary compiler warnings.
- Internal variables are now private.
Version 1.8 - 2009-03-16
- Converted project files to Visual Studio 2008 format.
- Added Unicode support for HashFile utility method.
- Added support for hashing files using the HashFile method that are
larger than 2 GB.
- HashFile now returns an error code instead of copying an error
message into the output buffer.
- GetHash now returns an error code and validates the input parameter.
- Added ReportHashStl STL utility method.
- Added REPORT_HEX_SHORT reporting mode.
- Improved Linux compatibility of test program.
Version 1.7 - 2006-12-21
- Fixed buffer underrun warning that appeared when compiling with
Borland C Builder (thanks to Rex Bloom and Tim Gallagher for the
patch).
- Breaking change: ReportHash writes the final hash to the start
of the buffer, i.e. it's not appending it to the string anymore.
- Made some function parameters const.
- Added Visual Studio 2005 project files to demo project.
Version 1.6 - 2005-02-07 (thanks to Howard Kapustein for patches)
- You can set the endianness in your files, no need to modify the
header file of the CSHA1 class anymore.
- Aligned data support.
- Made support/compilation of the utility functions (ReportHash and
HashFile) optional (useful when bytes count, for example in embedded
environments).
Version 1.5 - 2005-01-01
- 64-bit compiler compatibility added.
- Made variable wiping optional (define SHA1_WIPE_VARIABLES).
- Removed unnecessary variable initializations.
- ROL32 improvement for the Microsoft compiler (using _rotl).
Version 1.4 - 2004-07-22
- CSHA1 now compiles fine with GCC 3.3 under Mac OS X (thanks to Larry
Hastings).
Version 1.3 - 2003-08-17
- Fixed a small memory bug and made a buffer array a class member to
ensure correct working when using multiple CSHA1 class instances at
one time.
Version 1.2 - 2002-11-16
- Borlands C++ compiler seems to have problems with string addition
using sprintf. Fixed the bug which caused the digest report function
not to work properly. CSHA1 is now Borland compatible.
Version 1.1 - 2002-10-11
- Removed two unnecessary header file includes and changed BOOL to
bool. Fixed some minor bugs in the web page contents.
Version 1.0 - 2002-06-20
- First official release.
================ Test Vectors ================
SHA1("abc" in ANSI) =
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
SHA1("abc" in Unicode LE) =
9F04F41A 84851416 2050E3D6 8C1A7ABB 441DC2B5
SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
in ANSI) =
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
SHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
in Unicode LE) =
51D7D876 9AC72C40 9C5B0E3F 69C60ADC 9A039014
SHA1(A million repetitions of "a" in ANSI) =
34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
SHA1(A million repetitions of "a" in Unicode LE) =
C4609560 A108A0C6 26AA7F2B 38A65566 739353C5
*/
#ifndef SHA1_H_A545E61D43E9404E8D736869AB3CBFE7
#define SHA1_H_A545E61D43E9404E8D736869AB3CBFE7
#if !defined(SHA1_UTILITY_FUNCTIONS) && !defined(SHA1_NO_UTILITY_FUNCTIONS)
#define SHA1_UTILITY_FUNCTIONS
#endif
#if !defined(SHA1_STL_FUNCTIONS) && !defined(SHA1_NO_STL_FUNCTIONS)
#define SHA1_STL_FUNCTIONS
#if !defined(SHA1_UTILITY_FUNCTIONS)
#error STL functions require SHA1_UTILITY_FUNCTIONS.
#endif
#endif
#include <memory.h>
#include <limits.h>
#ifdef SHA1_UTILITY_FUNCTIONS
#include <stdio.h>
#include <string.h>
#endif
#ifdef SHA1_STL_FUNCTIONS
#include <string>
#endif
#ifdef _MSC_VER
#include <stdlib.h>
#endif
#include "openmm/internal/windowsExport.h"
// You can define the endian mode in your files without modifying the SHA-1
// source files. Just #define SHA1_LITTLE_ENDIAN or #define SHA1_BIG_ENDIAN
// in your files, before including the SHA1.h header file. If you don't
// define anything, the class defaults to little endian.
#if !defined(SHA1_LITTLE_ENDIAN) && !defined(SHA1_BIG_ENDIAN)
#define SHA1_LITTLE_ENDIAN
#endif
// If you want variable wiping, #define SHA1_WIPE_VARIABLES, if not,
// #define SHA1_NO_WIPE_VARIABLES. If you don't define anything, it
// defaults to wiping.
#if !defined(SHA1_WIPE_VARIABLES) && !defined(SHA1_NO_WIPE_VARIABLES)
#define SHA1_WIPE_VARIABLES
#endif
#if defined(SHA1_HAS_TCHAR)
#include <tchar.h>
#else
#ifdef _MSC_VER
#include <tchar.h>
#else
#ifndef TCHAR
#define TCHAR char
#endif
#ifndef _T
#define _T(__x) (__x)
#define _tmain main
#define _tprintf printf
#define _getts gets
#define _tcslen strlen
#define _tfopen fopen
#define _tcscpy strcpy
#define _tcscat strcat
#define _sntprintf snprintf
#endif
#endif
#endif
///////////////////////////////////////////////////////////////////////////
// Define variable types
#ifndef UINT_8
#ifdef _MSC_VER // Compiling with Microsoft compiler
#define UINT_8 unsigned __int8
#else // !_MSC_VER
#define UINT_8 unsigned char
#endif // _MSC_VER
#endif
#ifndef UINT_32
#ifdef _MSC_VER // Compiling with Microsoft compiler
#define UINT_32 unsigned __int32
#else // !_MSC_VER
#if (ULONG_MAX == 0xFFFFFFFFUL)
#define UINT_32 unsigned long
#else
#define UINT_32 unsigned int
#endif
#endif // _MSC_VER
#endif // UINT_32
#ifndef INT_64
#ifdef _MSC_VER // Compiling with Microsoft compiler
#define INT_64 __int64
#else // !_MSC_VER
#define INT_64 long long
#endif // _MSC_VER
#endif // INT_64
#ifndef UINT_64
#ifdef _MSC_VER // Compiling with Microsoft compiler
#define UINT_64 unsigned __int64
#else // !_MSC_VER
#define UINT_64 unsigned long long
#endif // _MSC_VER
#endif // UINT_64
///////////////////////////////////////////////////////////////////////////
// Declare SHA-1 workspace
typedef union
{
UINT_8 c[64];
UINT_32 l[16];
} SHA1_WORKSPACE_BLOCK;
class OPENMM_EXPORT CSHA1
{
public:
#ifdef SHA1_UTILITY_FUNCTIONS
// Different formats for ReportHash(Stl)
enum REPORT_TYPE
{
REPORT_HEX = 0,
REPORT_DIGIT = 1,
REPORT_HEX_SHORT = 2
};
#endif
// Constructor and destructor
CSHA1();
#ifdef SHA1_WIPE_VARIABLES
~CSHA1();
#endif
void Reset();
// Hash in binary data and strings
void Update(const UINT_8* pbData, UINT_32 uLen);
#ifdef SHA1_UTILITY_FUNCTIONS
// Hash in file contents
bool HashFile(const TCHAR* tszFileName);
#endif
// Finalize hash; call it before using ReportHash(Stl)
void Final();
#ifdef SHA1_UTILITY_FUNCTIONS
bool ReportHash(TCHAR* tszReport, REPORT_TYPE rtReportType = REPORT_HEX) const;
#endif
#ifdef SHA1_STL_FUNCTIONS
bool ReportHashStl(std::basic_string<TCHAR>& strOut, REPORT_TYPE rtReportType =
REPORT_HEX) const;
#endif
// Get the raw message digest (20 bytes)
bool GetHash(UINT_8* pbDest20) const;
private:
// Private SHA-1 transformation
void Transform(UINT_32* pState, const UINT_8* pBuffer);
// Member variables
UINT_32 m_state[5];
UINT_32 m_count[2];
UINT_32 m_reserved0[1]; // Memory alignment padding
UINT_8 m_buffer[64];
UINT_8 m_digest[20];
UINT_32 m_reserved1[3]; // Memory alignment padding
UINT_8 m_workspace[64];
SHA1_WORKSPACE_BLOCK* m_block; // SHA1 pointer to the byte array above
};
#endif // SHA1_H_A545E61D43E9404E8D736869AB3CBFE7
/*
100% free public domain implementation of the SHA-1 algorithm
by Dominik Reichl <dominik.reichl@t-online.de>
Web: http://www.dominik-reichl.de/
See header file for version history and test vectors.
*/
// If compiling with MFC, you might want to add #include "StdAfx.h"
#define _CRT_SECURE_NO_WARNINGS
#include "SHA1.h"
#define SHA1_MAX_FILE_BUFFER (32 * 20 * 820)
// Rotate p_val32 by p_nBits bits to the left
#ifndef ROL32
#ifdef _MSC_VER
#define ROL32(p_val32,p_nBits) _rotl(p_val32,p_nBits)
#else
#define ROL32(p_val32,p_nBits) (((p_val32)<<(p_nBits))|((p_val32)>>(32-(p_nBits))))
#endif
#endif
#ifdef SHA1_LITTLE_ENDIAN
#define SHABLK0(i) (m_block->l[i] = \
(ROL32(m_block->l[i],24) & 0xFF00FF00) | (ROL32(m_block->l[i],8) & 0x00FF00FF))
#else
#define SHABLK0(i) (m_block->l[i])
#endif
#define SHABLK(i) (m_block->l[i&15] = ROL32(m_block->l[(i+13)&15] ^ \
m_block->l[(i+8)&15] ^ m_block->l[(i+2)&15] ^ m_block->l[i&15],1))
// SHA-1 rounds
#define S_R0(v,w,x,y,z,i) {z+=((w&(x^y))^y)+SHABLK0(i)+0x5A827999+ROL32(v,5);w=ROL32(w,30);}
#define S_R1(v,w,x,y,z,i) {z+=((w&(x^y))^y)+SHABLK(i)+0x5A827999+ROL32(v,5);w=ROL32(w,30);}
#define S_R2(v,w,x,y,z,i) {z+=(w^x^y)+SHABLK(i)+0x6ED9EBA1+ROL32(v,5);w=ROL32(w,30);}
#define S_R3(v,w,x,y,z,i) {z+=(((w|x)&y)|(w&x))+SHABLK(i)+0x8F1BBCDC+ROL32(v,5);w=ROL32(w,30);}
#define S_R4(v,w,x,y,z,i) {z+=(w^x^y)+SHABLK(i)+0xCA62C1D6+ROL32(v,5);w=ROL32(w,30);}
#pragma warning(push)
// Disable compiler warning 'Conditional expression is constant'
#pragma warning(disable: 4127)
CSHA1::CSHA1()
{
m_block = (SHA1_WORKSPACE_BLOCK*)m_workspace;
Reset();
}
#ifdef SHA1_WIPE_VARIABLES
CSHA1::~CSHA1()
{
Reset();
}
#endif
void CSHA1::Reset()
{
// SHA1 initialization constants
m_state[0] = 0x67452301;
m_state[1] = 0xEFCDAB89;
m_state[2] = 0x98BADCFE;
m_state[3] = 0x10325476;
m_state[4] = 0xC3D2E1F0;
m_count[0] = 0;
m_count[1] = 0;
}
void CSHA1::Transform(UINT_32* pState, const UINT_8* pBuffer)
{
UINT_32 a = pState[0], b = pState[1], c = pState[2], d = pState[3], e = pState[4];
memcpy(m_block, pBuffer, 64);
// 4 rounds of 20 operations each, loop unrolled
S_R0(a,b,c,d,e, 0); S_R0(e,a,b,c,d, 1); S_R0(d,e,a,b,c, 2); S_R0(c,d,e,a,b, 3);
S_R0(b,c,d,e,a, 4); S_R0(a,b,c,d,e, 5); S_R0(e,a,b,c,d, 6); S_R0(d,e,a,b,c, 7);
S_R0(c,d,e,a,b, 8); S_R0(b,c,d,e,a, 9); S_R0(a,b,c,d,e,10); S_R0(e,a,b,c,d,11);
S_R0(d,e,a,b,c,12); S_R0(c,d,e,a,b,13); S_R0(b,c,d,e,a,14); S_R0(a,b,c,d,e,15);
S_R1(e,a,b,c,d,16); S_R1(d,e,a,b,c,17); S_R1(c,d,e,a,b,18); S_R1(b,c,d,e,a,19);
S_R2(a,b,c,d,e,20); S_R2(e,a,b,c,d,21); S_R2(d,e,a,b,c,22); S_R2(c,d,e,a,b,23);
S_R2(b,c,d,e,a,24); S_R2(a,b,c,d,e,25); S_R2(e,a,b,c,d,26); S_R2(d,e,a,b,c,27);
S_R2(c,d,e,a,b,28); S_R2(b,c,d,e,a,29); S_R2(a,b,c,d,e,30); S_R2(e,a,b,c,d,31);
S_R2(d,e,a,b,c,32); S_R2(c,d,e,a,b,33); S_R2(b,c,d,e,a,34); S_R2(a,b,c,d,e,35);
S_R2(e,a,b,c,d,36); S_R2(d,e,a,b,c,37); S_R2(c,d,e,a,b,38); S_R2(b,c,d,e,a,39);
S_R3(a,b,c,d,e,40); S_R3(e,a,b,c,d,41); S_R3(d,e,a,b,c,42); S_R3(c,d,e,a,b,43);
S_R3(b,c,d,e,a,44); S_R3(a,b,c,d,e,45); S_R3(e,a,b,c,d,46); S_R3(d,e,a,b,c,47);
S_R3(c,d,e,a,b,48); S_R3(b,c,d,e,a,49); S_R3(a,b,c,d,e,50); S_R3(e,a,b,c,d,51);
S_R3(d,e,a,b,c,52); S_R3(c,d,e,a,b,53); S_R3(b,c,d,e,a,54); S_R3(a,b,c,d,e,55);
S_R3(e,a,b,c,d,56); S_R3(d,e,a,b,c,57); S_R3(c,d,e,a,b,58); S_R3(b,c,d,e,a,59);
S_R4(a,b,c,d,e,60); S_R4(e,a,b,c,d,61); S_R4(d,e,a,b,c,62); S_R4(c,d,e,a,b,63);
S_R4(b,c,d,e,a,64); S_R4(a,b,c,d,e,65); S_R4(e,a,b,c,d,66); S_R4(d,e,a,b,c,67);
S_R4(c,d,e,a,b,68); S_R4(b,c,d,e,a,69); S_R4(a,b,c,d,e,70); S_R4(e,a,b,c,d,71);
S_R4(d,e,a,b,c,72); S_R4(c,d,e,a,b,73); S_R4(b,c,d,e,a,74); S_R4(a,b,c,d,e,75);
S_R4(e,a,b,c,d,76); S_R4(d,e,a,b,c,77); S_R4(c,d,e,a,b,78); S_R4(b,c,d,e,a,79);
// Add the working vars back into state
pState[0] += a;
pState[1] += b;
pState[2] += c;
pState[3] += d;
pState[4] += e;
// Wipe variables
#ifdef SHA1_WIPE_VARIABLES
a = b = c = d = e = 0;
#endif
}
void CSHA1::Update(const UINT_8* pbData, UINT_32 uLen)
{
UINT_32 j = ((m_count[0] >> 3) & 0x3F);
if((m_count[0] += (uLen << 3)) < (uLen << 3))
++m_count[1]; // Overflow
m_count[1] += (uLen >> 29);
UINT_32 i;
if((j + uLen) > 63)
{
i = 64 - j;
memcpy(&m_buffer[j], pbData, i);
Transform(m_state, m_buffer);
for( ; (i + 63) < uLen; i += 64)
Transform(m_state, &pbData[i]);
j = 0;
}
else i = 0;
if((uLen - i) != 0)
memcpy(&m_buffer[j], &pbData[i], uLen - i);
}
#ifdef SHA1_UTILITY_FUNCTIONS
bool CSHA1::HashFile(const TCHAR* tszFileName)
{
if(tszFileName == NULL) return false;
FILE* fpIn = _tfopen(tszFileName, _T("rb"));
if(fpIn == NULL) return false;
UINT_8* pbData = new UINT_8[SHA1_MAX_FILE_BUFFER];
if(pbData == NULL) { fclose(fpIn); return false; }
bool bSuccess = true;
while(true)
{
const size_t uRead = fread(pbData, 1, SHA1_MAX_FILE_BUFFER, fpIn);
if(uRead > 0)
Update(pbData, static_cast<UINT_32>(uRead));
if(uRead < SHA1_MAX_FILE_BUFFER)
{
if(feof(fpIn) == 0) bSuccess = false;
break;
}
}
fclose(fpIn);
delete[] pbData;
return bSuccess;
}
#endif
void CSHA1::Final()
{
UINT_32 i;
UINT_8 pbFinalCount[8];
for(i = 0; i < 8; ++i)
pbFinalCount[i] = static_cast<UINT_8>((m_count[((i >= 4) ? 0 : 1)] >>
((3 - (i & 3)) * 8) ) & 0xFF); // Endian independent
Update((UINT_8*)"\200", 1);
while((m_count[0] & 504) != 448)
Update((UINT_8*)"\0", 1);
Update(pbFinalCount, 8); // Cause a Transform()
for(i = 0; i < 20; ++i)
m_digest[i] = static_cast<UINT_8>((m_state[i >> 2] >> ((3 -
(i & 3)) * 8)) & 0xFF);
// Wipe variables for security reasons
#ifdef SHA1_WIPE_VARIABLES
memset(m_buffer, 0, 64);
memset(m_state, 0, 20);
memset(m_count, 0, 8);
memset(pbFinalCount, 0, 8);
Transform(m_state, m_buffer);
#endif
}
#ifdef SHA1_UTILITY_FUNCTIONS
bool CSHA1::ReportHash(TCHAR* tszReport, REPORT_TYPE rtReportType) const
{
if(tszReport == NULL) return false;
TCHAR tszTemp[16];
if((rtReportType == REPORT_HEX) || (rtReportType == REPORT_HEX_SHORT))
{
_sntprintf(tszTemp, 15, _T("%02X"), m_digest[0]);
_tcscpy(tszReport, tszTemp);
const TCHAR* lpFmt = ((rtReportType == REPORT_HEX) ? _T(" %02X") : _T("%02X"));
for(size_t i = 1; i < 20; ++i)
{
_sntprintf(tszTemp, 15, lpFmt, m_digest[i]);
_tcscat(tszReport, tszTemp);
}
}
else if(rtReportType == REPORT_DIGIT)
{
_sntprintf(tszTemp, 15, _T("%u"), m_digest[0]);
_tcscpy(tszReport, tszTemp);
for(size_t i = 1; i < 20; ++i)
{
_sntprintf(tszTemp, 15, _T(" %u"), m_digest[i]);
_tcscat(tszReport, tszTemp);
}
}
else return false;
return true;
}
#endif
#ifdef SHA1_STL_FUNCTIONS
bool CSHA1::ReportHashStl(std::basic_string<TCHAR>& strOut, REPORT_TYPE rtReportType) const
{
TCHAR tszOut[84];
const bool bResult = ReportHash(tszOut, rtReportType);
if(bResult) strOut = tszOut;
return bResult;
}
#endif
bool CSHA1::GetHash(UINT_8* pbDest20) const
{
if(pbDest20 == NULL) return false;
memcpy(pbDest20, m_digest, 20);
return true;
}
#pragma warning(pop)
\ No newline at end of file
......@@ -279,8 +279,12 @@ const string& Platform::getDefaultPluginsDirectory() {
return directory;
}
// Some bizarre preprocessor magic required to convert a macro to a string...
#define STRING1(x) #x
#define STRING(x) STRING1(x)
const string& Platform::getOpenMMVersion() {
static const string version = "5.1";
static const string version = STRING(OPENMM_MAJOR_VERSION) "." STRING(OPENMM_MINOR_VERSION);
return version;
}
......
......@@ -80,6 +80,25 @@ namespace OpenMM {
* if the labels 1 and 2 are reversed. In contrast, if it depended on the difference sigma1-sigma2, the results would
* be undefined, because reversing the labels 1 and 2 would change the energy.
*
* CustomNonbondedForce can operate in two modes. By default, it computes the interaction of every particle in the System
* with every other particle. Alternatively, you can restrict it to only a subset of particle pairs. To do this, specify
* one or more "interaction groups". An interaction group consists of two sets of particles that should interact with
* each other. Every particle in the first set interacts with every particle in the second set. For example, you might use
* this feature to compute a solute-solvent interaction energy, while omitting all interactions between two solute atoms
* or two solvent atoms.
*
* To create an interaction group, call addInteractionGroup(). You may add as many interaction groups as you want.
* Be aware of the following:
*
* <ul>
* <li>Exclusions are still taken into account, so the interactions between excluded pairs are omitted.</li>
* <li>Likewise, a particle will never interact with itself, even if it appears in both sets of an interaction group.</li>
* <li>If a particle pair appears in two different interaction groups, its interaction will be computed twice. This is
* sometimes useful, but be aware of it so you do not accidentally create unwanted duplicate interactions.</li>
* <li>If you do not add any interaction groups to a CustomNonbondedForce, it operates in the default mode where every
* particle interacts with every other particle.</li>
* </ul>
*
* When using a cutoff, by default the interaction is sharply truncated at the cutoff distance.
* Optionally you can instead use a switching function to make the interaction smoothly go to zero over a finite
* distance range. To enable this, call setUseSwitchingFunction(). You must also call setSwitchingDistance()
......@@ -167,6 +186,12 @@ public:
int getNumFunctions() const {
return functions.size();
}
/**
* Get the number of interaction groups that have been defined.
*/
int getNumInteractionGroups() const {
return interactionGroups.size();
}
/**
* Get the algebraic expression that gives the interaction energy between two particles
*/
......@@ -363,10 +388,34 @@ public:
* @param max the value of the independent variable corresponding to the last element of values
*/
void setFunctionParameters(int index, const std::string& name, const std::vector<double>& values, double min, double max);
/**
* Add an interaction group. An interaction will be computed between every particle in set1 and every particle in set2.
*
* @param set1 the first set of particles forming the interaction group
* @param set2 the second set of particles forming the interaction group
* @return the index of the interaction group that was added
*/
int addInteractionGroup(const std::set<int>& set1, const std::set<int>& set2);
/**
* Get the parameters for an interaction group.
*
* @param index the index of the interaction group for which to get parameters
* @param set1 the first set of particles forming the interaction group
* @param set2 the second set of particles forming the interaction group
*/
void getInteractionGroupParameters(int index, std::set<int>& set1, std::set<int>& set2) const;
/**
* Set the parameters for an interaction group.
*
* @param index the index of the interaction group for which to set parameters
* @param set1 the first set of particles forming the interaction group
* @param set2 the second set of particles forming the interaction group
*/
void setInteractionGroupParameters(int index, const std::set<int>& set1, const std::set<int>& set2);
/**
* Update the per-particle parameters in a Context to match those stored in this Force object. This method provides
* an efficient method to update certain parameters in an existing Context without needing to reinitialize it.
* Simply call setParticleParameters() to modify this object's parameters, then call updateParametersInState()
* Simply call setParticleParameters() to modify this object's parameters, then call updateParametersInContext()
* to copy them over to the Context.
*
* This method has several limitations. The only information it updates is the values of per-particle parameters.
......@@ -383,6 +432,7 @@ private:
class GlobalParameterInfo;
class ExclusionInfo;
class FunctionInfo;
class InteractionGroupInfo;
NonbondedMethod nonbondedMethod;
double cutoffDistance, switchingDistance;
bool useSwitchingFunction, useLongRangeCorrection;
......@@ -392,6 +442,7 @@ private:
std::vector<ParticleInfo> particles;
std::vector<ExclusionInfo> exclusions;
std::vector<FunctionInfo> functions;
std::vector<InteractionGroupInfo> interactionGroups;
};
/**
......@@ -465,6 +516,20 @@ public:
}
};
/**
* This is an internal class used to record information about an interaction group.
* @private
*/
class CustomNonbondedForce::InteractionGroupInfo {
public:
std::set<int> set1, set2;
InteractionGroupInfo() {
}
InteractionGroupInfo(const std::set<int>& set1, const std::set<int>& set2) :
set1(set1), set2(set2) {
}
};
} // namespace OpenMM
#endif /*OPENMM_CUSTOMNONBONDEDFORCE_H_*/
......@@ -86,12 +86,12 @@ public:
*
* @param defaultPressure The default pressure acting on each axis (in bar)
* @param temperature the temperature at which the system is being maintained (in Kelvin)
* @param frequency the frequency at which Monte Carlo pressure changes should be attempted (in time steps)
* @param scaleX whether to allow the X dimension of the periodic box to change size
* @param scaleY whether to allow the Y dimension of the periodic box to change size
* @param scaleZ whether to allow the Z dimension of the periodic box to change size
* @param frequency the frequency at which Monte Carlo pressure changes should be attempted (in time steps)
*/
MonteCarloAnisotropicBarostat(const Vec3& defaultPressure, double temperature, int frequency = 25, bool scaleX = 1, bool scaleY = 1, bool scaleZ = 1);
MonteCarloAnisotropicBarostat(const Vec3& defaultPressure, double temperature, bool scaleX = true, bool scaleY = true, bool scaleZ = true, int frequency = 25);
/**
* Get the default pressure (in bar).
*
......
......@@ -9,7 +9,7 @@
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2008-2012 Stanford University and the Authors. *
* Portions copyright (c) 2008-2013 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
......@@ -250,9 +250,13 @@ public:
void integratorDeleted() {
integratorIsDeleted = true;
}
/**
* This is the routine that actually computes the list of molecules returned by getMolecules(). Normally
* you should never call it. It is exposed here because the same logic is useful to other classes too.
*/
static std::vector<std::vector<int> > findMolecules(int numParticles, std::vector<std::vector<int> >& particleBonds);
private:
friend class Context;
static void tagParticlesInMolecule(int particle, int molecule, std::vector<int>& particleMolecule, std::vector<std::vector<int> >& particleBonds);
Context& owner;
const System& system;
Integrator& integrator;
......
......@@ -6,7 +6,7 @@
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2008-2012 Stanford University and the Authors. *
* Portions copyright (c) 2008-2013 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
......@@ -288,26 +288,54 @@ const vector<vector<int> >& ContextImpl::getMolecules() const {
particleBonds[bonds[i].second].push_back(bonds[i].first);
}
// Now tag particles by which molecule they belong to.
// Now identify particles by which molecule they belong to.
molecules = findMolecules(numParticles, particleBonds);
return molecules;
}
vector<vector<int> > ContextImpl::findMolecules(int numParticles, vector<vector<int> >& particleBonds) {
// This is essentially a recursive algorithm, but it is reformulated as a loop to avoid
// stack overflows. It selects a particle, marks it as a new molecule, then recursively
// marks every particle bonded to it as also being in that molecule.
vector<int> particleMolecule(numParticles, -1);
int numMolecules = 0;
for (int i = 0; i < numParticles; i++)
if (particleMolecule[i] == -1)
tagParticlesInMolecule(i, numMolecules++, particleMolecule, particleBonds);
molecules.resize(numMolecules);
for (int i = 0; i < numParticles; i++)
molecules[particleMolecule[i]].push_back(i);
return molecules;
}
if (particleMolecule[i] == -1) {
// Start a new molecule.
vector<int> particleStack;
vector<int> neighborStack;
particleStack.push_back(i);
neighborStack.push_back(0);
int molecule = numMolecules++;
void ContextImpl::tagParticlesInMolecule(int particle, int molecule, vector<int>& particleMolecule, vector<vector<int> >& particleBonds) {
// Recursively tag particles as belonging to a particular molecule.
// Recursively tag all the bonded particles.
while (particleStack.size() > 0) {
int particle = particleStack.back();
particleMolecule[particle] = molecule;
for (int i = 0; i < (int) particleBonds[particle].size(); i++)
if (particleMolecule[particleBonds[particle][i]] == -1)
tagParticlesInMolecule(particleBonds[particle][i], molecule, particleMolecule, particleBonds);
int& neighbor = neighborStack.back();
while (neighbor < particleBonds[particle].size() && particleMolecule[particleBonds[particle][neighbor]] != -1)
neighbor++;
if (neighbor < particleBonds[particle].size()) {
particleStack.push_back(particleBonds[particle][neighbor]);
neighborStack.push_back(0);
}
else {
particleStack.pop_back();
neighborStack.pop_back();
}
}
}
// Build the final output vector.
vector<vector<int> > molecules(numMolecules);
for (int i = 0; i < numParticles; i++)
molecules[particleMolecule[i]].push_back(i);
return molecules;
}
static void writeString(ostream& stream, string str) {
......
......@@ -199,6 +199,23 @@ void CustomNonbondedForce::setFunctionParameters(int index, const std::string& n
functions[index].max = max;
}
int CustomNonbondedForce::addInteractionGroup(const std::set<int>& set1, const std::set<int>& set2) {
interactionGroups.push_back(InteractionGroupInfo(set1, set2));
return interactionGroups.size()-1;
}
void CustomNonbondedForce::getInteractionGroupParameters(int index, std::set<int>& set1, std::set<int>& set2) const {
ASSERT_VALID_INDEX(index, interactionGroups);
set1 = interactionGroups[index].set1;
set2 = interactionGroups[index].set2;
}
void CustomNonbondedForce::setInteractionGroupParameters(int index, const std::set<int>& set1, const std::set<int>& set2) {
ASSERT_VALID_INDEX(index, interactionGroups);
interactionGroups[index].set1 = set1;
interactionGroups[index].set2 = set2;
}
ForceImpl* CustomNonbondedForce::createImpl() const {
return new CustomNonbondedForceImpl(*this);
}
......
......@@ -42,14 +42,10 @@
#include "lepton/Parser.h"
#include <cmath>
#include <sstream>
#include <utility>
using namespace OpenMM;
using std::map;
using std::pair;
using std::vector;
using std::set;
using std::string;
using std::stringstream;
using namespace std;
CustomNonbondedForceImpl::CustomNonbondedForceImpl(const CustomNonbondedForce& owner) : owner(owner) {
}
......@@ -176,20 +172,6 @@ double CustomNonbondedForceImpl::calcLongRangeCorrection(const CustomNonbondedFo
if (force.getNonbondedMethod() == CustomNonbondedForce::NoCutoff || force.getNonbondedMethod() == CustomNonbondedForce::CutoffNonPeriodic)
return 0.0;
// Identify all particle classes (defined by parameters), and count the number of
// particles in each class.
map<vector<double>, int> classCounts;
for (int i = 0; i < force.getNumParticles(); i++) {
vector<double> parameters;
force.getParticleParameters(i, parameters);
map<vector<double>, int>::iterator entry = classCounts.find(parameters);
if (entry == classCounts.end())
classCounts[parameters] = 1;
else
entry->second++;
}
// Parse the energy expression.
map<string, Lepton::CustomFunction*> functions;
......@@ -202,19 +184,68 @@ double CustomNonbondedForceImpl::calcLongRangeCorrection(const CustomNonbondedFo
}
Lepton::ExpressionProgram expression = Lepton::Parser::parse(force.getEnergyFunction(), functions).optimize().createProgram();
// Loop over all pairs of classes to compute the coefficient.
// Identify all particle classes (defined by parameters), and record the class of each particle.
double sum = 0;
for (map<vector<double>, int>::const_iterator entry = classCounts.begin(); entry != classCounts.end(); ++entry) {
int count = (entry->second*(entry->second+1))/2;
sum += count*integrateInteraction(expression, entry->first, entry->first, force, context);
int numParticles = force.getNumParticles();
vector<vector<double> > classes;
map<vector<double>, int> classIndex;
vector<int> atomClass(numParticles);
for (int i = 0; i < numParticles; i++) {
vector<double> parameters;
force.getParticleParameters(i, parameters);
if (classIndex.find(parameters) == classIndex.end()) {
classIndex[parameters] = classes.size();
classes.push_back(parameters);
}
for (map<vector<double>, int>::const_iterator class1 = classCounts.begin(); class1 != classCounts.end(); ++class1)
for (map<vector<double>, int>::const_iterator class2 = classCounts.begin(); class2 != class1; ++class2) {
int count = class1->second*class2->second;
sum += count*integrateInteraction(expression, class1->first, class2->first, force, context);
atomClass[i] = classIndex[parameters];
}
int numParticles = force.getNumParticles();
int numClasses = classes.size();
// Count the total number of particle pairs for each pair of classes.
map<pair<int, int>, int> interactionCount;
if (force.getNumInteractionGroups() == 0) {
// Count the particles of each class.
vector<int> classCounts(numClasses, 0);
for (int i = 0; i < numParticles; i++)
classCounts[atomClass[i]]++;
for (int i = 0; i < numClasses; i++) {
interactionCount[make_pair(i, i)] = (classCounts[i]*(classCounts[i]+1))/2;
for (int j = i+1; j < numClasses; j++)
interactionCount[make_pair(i, j)] = classCounts[i]*classCounts[j];
}
}
else {
// Initialize the counts to 0.
for (int i = 0; i < numClasses; i++) {
for (int j = i; j < numClasses; j++)
interactionCount[make_pair(i, j)] = 0;
}
// Loop over interaction groups and count the interactions in each one.
for (int group = 0; group < force.getNumInteractionGroups(); group++) {
set<int> set1, set2;
force.getInteractionGroupParameters(group, set1, set2);
for (set<int>::const_iterator a1 = set1.begin(); a1 != set1.end(); ++a1)
for (set<int>::const_iterator a2 = set2.begin(); a2 != set2.end(); ++a2) {
if (*a1 >= *a2 && set1.find(*a2) != set1.end() && set2.find(*a1) != set2.end())
continue;
int class1 = atomClass[*a1];
int class2 = atomClass[*a2];
interactionCount[make_pair(min(class1, class2), max(class1, class2))]++;
}
}
}
// Loop over all pairs of classes to compute the coefficient.
double sum = 0;
for (int i = 0; i < numClasses; i++)
for (int j = i; j < numClasses; j++)
sum += interactionCount[make_pair(i, j)]*integrateInteraction(expression, classes[i], classes[j], force, context);
int numInteractions = (numParticles*(numParticles+1))/2;
sum /= numInteractions;
return 2*M_PI*numParticles*numParticles*sum;
......
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