Saving Systems to XML Files

The XMLSerializer class can be used to save many kinds of objects to XML files: Systems, Integrators, States, and Forces. Saving and loading State objects is most easily done by calling saveState() and loadState() on the Simulation. For other objects, you need to invoke XMLSerializer directly.

Here are some reasons you might want to save a System to a file.

  • Creating it with a class such as ForceField or CharmmPsfFile might be slow. If you plan to run many simulations of the same System, writing it to a file and reloading it for future simulations will save time.

  • Saving it to a file helps reproducibility. It preserves a record of exactly what you simulated. Otherwise, you might forget what arguments you passed to createSystem() and be unsure how to reproduce your earlier work.

  • It can be used to communicate the exact system description. You might have one script that builds the System and a different one that simulates it. Or one person might be responsible for building it and a different person responsible for running the simulation.

  • You can use Python tools like ForceField to build the System, then load it into a simulation code written in C++.

Let’s start by creating a System.

[1]:
from openmm.app import *
from openmm import *

pdb = PDBFile('ala_ala_ala.pdb')
forcefield = ForceField('amber14-all.xml')
system = forcefield.createSystem(pdb.topology)

The following lines save it to a file on disk.

[2]:
with open('system.xml', 'w') as output:
    output.write(XmlSerializer.serialize(system))

Reloading the file and creating a new System is just as easy.

[3]:
with open('system.xml') as input:
    system2 = XmlSerializer.deserialize(input.read())

Loading a serialized System in C++ is very similar:

ifstream input("system.xml");
System* system = XmlSerializer::deserialize<System>(input);