Commit c232858c authored by peastman's avatar peastman
Browse files

CheckpointReporter does a safe save

parent ea9714c1
...@@ -6,7 +6,7 @@ Simbios, the NIH National Center for Physics-Based Simulation of ...@@ -6,7 +6,7 @@ Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structures at Stanford, funded under the NIH Roadmap for Biological Structures at Stanford, funded under the NIH Roadmap for
Medical Research, grant U54 GM072970. See https://simtk.org. Medical Research, grant U54 GM072970. See https://simtk.org.
Portions copyright (c) 2014 Stanford University and the Authors. Portions copyright (c) 2014-2016 Stanford University and the Authors.
Authors: Robert McGibbon Authors: Robert McGibbon
Contributors: Contributors:
...@@ -33,6 +33,9 @@ __author__ = "Robert McGibbon" ...@@ -33,6 +33,9 @@ __author__ = "Robert McGibbon"
__version__ = "1.0" __version__ = "1.0"
import simtk.openmm as mm import simtk.openmm as mm
import os
import os.path
__all__ = ['CheckpointReporter'] __all__ = ['CheckpointReporter']
...@@ -80,13 +83,7 @@ class CheckpointReporter(object): ...@@ -80,13 +83,7 @@ class CheckpointReporter(object):
""" """
self._reportInterval = reportInterval self._reportInterval = reportInterval
if isinstance(file, str): self._file = file
self._own_handle = True
self._filename = file
self._out = None
else:
self._out = file
self._own_handle = False
def describeNextReport(self, simulation): def describeNextReport(self, simulation):
"""Get information about the next report this object will generate. """Get information about the next report this object will generate.
...@@ -117,15 +114,24 @@ class CheckpointReporter(object): ...@@ -117,15 +114,24 @@ class CheckpointReporter(object):
state : State state : State
The current state of the simulation The current state of the simulation
""" """
if self._out is None: if isinstance(self._file, str):
self._out = open(self._filename, 'w+b', 0) # Do a safe save.
self._out.seek(0)
chk = simulation.context.createCheckpoint() tempFilename1 = self._file+".backup1"
self._out.write(chk) tempFilename2 = self._file+".backup2"
self._out.truncate() with open(tempFilename1, 'w+b', 0) as out:
self._out.flush() out.write(simulation.context.createCheckpoint())
exists = os.path.exists(self._file)
def __del__(self): if exists:
if self._own_handle and self._out is not None: os.rename(self._file, tempFilename2)
self._out.close() os.rename(tempFilename1, self._file)
if exists:
os.remove(tempFilename2)
else:
# Replace the contents of the file.
self._file.seek(0)
chk = simulation.context.createCheckpoint()
self._file.write(chk)
self._file.truncate()
self._file.flush()
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