Binding the engine#

A first binding made one C++ function callable from Python. The engine needs more: Python must create C++ objects, such as a Geometry or an LJPotential, call their functions, and hand them to other C++ objects. This chapter reads the engine’s real bridge, src/bindings/molsim_bindings.cpp, and follows the home page’s sim.run() from Python down into C++.

It uses the classes of the C++ module: an object such as geometry is one value of the class Geometry (Classes), and the potentials are plugs in the Potential socket (The plug).

The layers#

The script on the home page passes through four layers (Fig. 21). The top two are Python; the module _molsim is the pybind11 bridge; the engine below it is C++.

../_images/pybind_layers.svg

Fig. 21 The layers between the home-page script and the engine. Each layer calls the one below it.#

The bridge: molsim_bindings.cpp#

The engine’s binding file starts like ljmodule.cpp, with two extra headers:

#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <pybind11/stl.h>
PYBIND11_MODULE(_molsim, module) {
    module.doc() = "MolSimWorkbench C++ bindings";

The module is named _molsim; the leading underscore is a Python convention for “internal: use it through something else”, here through molsimworkbench.py. Instead of m.def for a function, the file mostly uses py::class_, which makes a C++ class available as a Python class (object-oriented code). The Geometry binding shows the pattern:

    py::class_<Geometry>(module, "Geometry")
        .def(py::init<>())
        .def("addAtom", &Geometry::addAtom)
        .def("getNumberOfAtoms", &Geometry::getNumberOfAtoms)
        .def("getAtoms", &Geometry::getAtoms, py::return_value_policy::copy)
        .def("getPositions", &Geometry::getPositions, py::return_value_policy::copy)
        .def("getAtomType", &Geometry::getAtomType, py::return_value_policy::copy)
        .def("getCoordinates", &Geometry::getCoordinates, py::return_value_policy::copy)
        .def("setCoordinates", &Geometry::setCoordinates)
        .def("setBoxDimensions", &Geometry::setBoxDimensions)
        .def("getBoxDimensions", &Geometry::getBoxDimensions, py::return_value_policy::copy);
  • py::class_<Geometry>(module, "Geometry") creates a Python class named Geometry that stands for the C++ class Geometry.

  • .def(py::init<>()) lets Python create one: _molsim.Geometry() runs the C++ constructor, the function that sets up a new object.

  • Each .def("name", &Geometry::name) makes one C++ member function callable from Python, exactly like m.def did for lj_energy. py::return_value_policy::copy tells pybind11 to give Python its own copy of the returned value (return value policies).

Some functions take or return a list of numbers, such as a position with three coordinates. The last header, pybind11/stl.h, converts C++ containers such as std::vector and std::array to and from Python lists, copying them on every crossing (STL containers). The middle one, pybind11/functional.h, is for the browser and comes up on the next page.

Building a pair from Python#

With these classes, Python can build the two-atom system of the C++ module by hand, one engine object at a time:

Listing 30 pair_by_hand.py#
sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
from molsimworkbench import _molsim

lj = _molsim.LJPotential()
lj.addAtomParameters("LJ", 1.0, 1.0)      # atom type, epsilon, sigma
lj.setCutoff(2.5)

geometry = _molsim.Geometry()
geometry.addAtom("LJ", [0.0, 0.0, 0.0])
geometry.addAtom("LJ", [1.5, 0.0, 0.0])

forces = _molsim.ForceCalculator()
forces.addPotential(lj)

print("energy:", forces.calculateEnergy(geometry))
print("forces:", forces.calculateForces(geometry))
$ python3 pair_by_hand.py
energy: -0.32033659427857464
forces: [[1.1580288310461555, 0.0, 0.0], [-1.1580288310461555, 0.0, 0.0]]

The energy is U(1.5) again: the engine’s LJ code gives the same value as lj_energy in its first 16 digits. The forces come back as a Python list of lists, converted by stl.h from the C++ std::vector<std::array<double, 3>>. They are equal and opposite: at 1.5σ the atoms attract, so the first atom is pulled toward +x and the second toward −x.

Two lines need a closer look. geometry.addAtom("LJ", [0.0, 0.0, 0.0]) passes a Python list where the C++ function expects a std::array<double, 3>; stl.h converts it. And forces.addPotential(lj) hands a Python-created object to a C++ object, which keeps it. That second one is the subject of the next section.

Who owns the potential#

ForceCalculator keeps its energy functions in a list of std::shared_ptr<Potential>. Recall from The plug that a std::shared_ptr counts its owners: the object it points to is deleted only when the last shared_ptr to it is gone. The binding declares the same kind of owner for the potentials:

    py::class_<Potential, std::shared_ptr<Potential>>(module, "Potential");

    py::class_<LJPotential, Potential, std::shared_ptr<LJPotential>>(module, "LJPotential")

The second template argument is the holder type: how pybind11 owns the C++ object behind a Python object. Without it, the holder is a std::unique_ptr, a single owner, and the C++ object is deleted when Python drops its last reference (smart pointers). With std::shared_ptr, the Python object and the ForceCalculator share ownership (Fig. 22).

../_images/pybind_shared.svg

Fig. 22 After forces.addPotential(lj), one LJPotential has two owners.#

This script deletes Python’s name for the potential after adding it, and then uses it through the ForceCalculator:

Listing 31 shared_owner.py#
forces = _molsim.ForceCalculator()
lj = _molsim.LJPotential()
lj.addAtomParameters("LJ", 1.0, 1.0)
lj.setCutoff(2.5)
forces.addPotential(lj)
del lj                                     # Python's name is gone ...

geometry = _molsim.Geometry()
geometry.addAtom("LJ", [0.0, 0.0, 0.0])
geometry.addAtom("LJ", [1.5, 0.0, 0.0])
print("energy:", forces.calculateEnergy(geometry))   # ... the potential is not

try:
    forces.addPotential(5)
except TypeError as error:
    print("TypeError:", error)
$ python3 shared_owner.py
energy: -0.32033659427857464
TypeError: addPotential(): incompatible function arguments. The following argument types are supported:
    1. (self: _molsim.ForceCalculator, arg0: _molsim.Potential) -> None

Invoked with: <_molsim.ForceCalculator object at 0x10379e730>, 5

The energy is still computed after del lj, because the ForceCalculator still owns the potential. The last lines show the type check from the first chapter at work on a class: addPotential accepts any Potential, such as an LJPotential, and refuses the number 5. self is the object the function is called on, here forces.

How Python finds _molsim#

_molsim is built by CMake, not by a hand-typed command. CMakeLists.txt calls pybind11’s CMake function pybind11_add_module with the name _molsim and the source src/bindings/molsim_bindings.cpp, then links the engine’s libraries into it. The function adds a library target to build from the listed sources and sets the Python-specific compiler and linker options, the ones typed by hand in the first chapter (building with CMake). The result lands in build/, as build/_molsim.cpython-312-darwin.so on this Mac.

Python does not look in build/ by itself. molsimworkbench.py adds it:

def _load_bindings():
    try:
        import _molsim
        return _molsim
    except ImportError:
        project_root = Path(__file__).resolve().parent
        build_dir = project_root / "build"
        candidates = [
            build_dir,
            build_dir / "Debug",
            build_dir / "Release",
            build_dir / "RelWithDebInfo",
            build_dir / "MinSizeRel",
        ]
        for candidate in candidates:
            if candidate.exists():
                candidate_path = str(candidate)
                if candidate_path not in sys.path:
                    sys.path.insert(0, candidate_path)
        import _molsim
        return _molsim

_load_bindings first tries a plain import _molsim. If that fails, it adds build/ and the folders that some build tools put inside it (Debug, Release, …) to sys.path, the list of folders Python searches when importing, and tries again. The sys.path.insert(0, ...) line at the top of each example in this chapter does the same for molsimworkbench.py itself, which lives at the top of the repository.

Following sim.run()#

System.from_yaml reads the configuration and builds the engine objects, calling C++ through _molsim at every step:

    @classmethod
    def from_yaml(cls, config_path, trajectory_output="water_trajectory.xyz", trajectory_every=1,
                  integrator=None, thermostat=None):
        """Build a system from a YAML config.

        `integrator` ("velocity_verlet", "leapfrog") and `thermostat`
        ("velocity_rescale", "berendsen", "langevin", "none") override the
        names in the YAML. Either may also be a plug object, such as
        `_molsim.LangevinThermostat(friction=2.0, seed=1)`.
        """
        parser = _molsim.YAMLParser()
        config = parser.parseSimulationConfig(str(config_path))
        if isinstance(integrator, str):
            config.simulationParams.integrator = integrator
        if isinstance(thermostat, str):
            config.simulationParams.thermostat = thermostat

        # Handle geometry based on system mode
        if config.systemMode == "lj_particle_box":
            # LJ bulk box: build geometry using LJParticleBoxBuilder
            geometry = _molsim.LJParticleBoxBuilder.createCubicLattice(config.ljBoxConfig)
            # Update simulation box dimensions
            box_dims = geometry.getBoxDimensions()
            config.simulationParams.box = _molsim.SimulationBox(box_dims[0], box_dims[1], box_dims[2])
            config.simulationParams.usePBC = True
        else:
            # Explicit geometry file mode
            geometry = parser.parseGeometry(config.geometryFile)
        
        force_calculator = _molsim.ForceCalculator()
        for potential_file in config.potentialConfigFiles:
            force_calculator.addPotential(parser.parsePotential(potential_file))

        dynamics = _molsim.MolecularDynamics()
        dynamics.setGeometry(geometry)
        dynamics.setForceCalculator(force_calculator)
        dynamics.setSimulationParameters(config.simulationParams)
        if integrator is not None and not isinstance(integrator, str):
            dynamics.setIntegrator(integrator)
        if thermostat is not None and not isinstance(thermostat, str):
            dynamics.setThermostat(thermostat)
        dynamics.setTrajectoryOutput(str(trajectory_output), _molsim.TrajectoryFormat.XYZ, trajectory_every)

        return cls(dynamics)

Each _molsim. name is a class from the binding file: the YAML reader, the lattice builder, the ForceCalculator and its potentials, and the MolecularDynamics driver. System.run then hands control to C++:

    def run(self):
        self._dynamics.initialize()
        self._dynamics.runSimulation()
        return self._dynamics.getCurrentEnergy()

runSimulation is a single call from Python, and the whole loop of A simple molecular dynamics loop runs inside it, in C++: 2500 steps of forces, Velocity-Verlet and thermostat, with no Python in between. This is why the Python layer costs almost nothing here: it crosses the bridge a handful of times to set things up, then once to run. The home page’s “Behind sim.run()” call stack is this path.

The home-page script, with three lines added to show what it built, run from the top folder of the repository, where data/ is:

Listing 32 run_system.py#
import molsimworkbench
from molsimworkbench import System

print("bindings loaded from:", Path(molsimworkbench._molsim.__file__).name)
sim = System.from_yaml("data/lj_play_simulation.yaml",
                       trajectory_output="traj.xyz")
print("type of sim._dynamics:", type(sim._dynamics))
energy = sim.run()
print("final energy:", round(energy, 2))
$ python3 website/pybind11/examples/ch02/run_system.py
bindings loaded from: _molsim.cpython-312-darwin.so
...
Trajectory output set to traj.xyz (XYZ format), writing every 1 steps.
type of sim._dynamics: <class '_molsim.MolecularDynamics'>
...
Step 2490, Potential Energy: -265.692, Kinetic Energy: 187.5, Total Energy: -78.1925, Temperature: 1
final energy: -79.82

(Each ... stands for lines that the C++ engine prints while it reads the files and runs.) The command-line program run_simulation, given the same configuration, prints Final energy: -79.817 and writes a trajectory that is identical byte for byte (cmp finds no difference): the Python layer adds no physics of its own.

$ build/run_simulation data/lj_play_simulation.yaml cli.xyz
...
Final energy: -79.817
$ cmp traj.xyz cli.xyz

When the layers disagree#

That last check has not always passed. The command-line program and System.from_yaml each assemble the engine objects themselves, so they can drift apart. In this version of the code, from_yaml gained one line:

config.simulationParams.usePBC = True

The command-line program had always switched on periodic boundaries for the LJ box; from_yaml did not, so Python runs simulated the atoms without a periodic box, and their trajectories differed from the command line’s. The fix is the line above, and the check that caught it is the one in the previous section: run both on the same configuration and compare the results. Whenever Python and C++ build the same thing separately, they need a test that compares them.

Check yourself#

1. Why does shared_owner.py still compute an energy after del lj?

The ForceCalculator holds its own std::shared_ptr to the potential. del lj drops Python’s owner only; the object is deleted when its last owner lets go, and the ForceCalculator has not.

2. The forces in pair_by_hand.py come back as a Python list of lists. Which line of molsim_bindings.cpp makes that possible?

#include <pybind11/stl.h>. It converts the C++ std::vector<std::array<double, 3>> into a Python list of lists, copying it.

3. You run a script from a folder where molsimworkbench.py cannot find build/. What happens, and what would you check first?

The import of _molsim fails with an ImportError (ModuleNotFoundError). Check that the project has been built, so that build/_molsim*.so exists, and that molsimworkbench.py is the one at the top of the repository, next to build/.

4. sim.run() simulates 2500 steps. How many times does that call cross from Python into C++?

Three: initialize, runSimulation and getCurrentEnergy. All 2500 steps run inside the one runSimulation call, in C++.

Next#

On your computer, this path needs Python and the compiled module, yet the Run buttons on these pages need neither. The same module, in your browser shows what runs them: the bottom three of these layers, with two JavaScript layers on top in place of your script.