This paper has a good explanation of how to calculate virial components in a convenient way in a molecular dynamics simulation.
The definition of the virial is
V = Sum i=1..N [ r_i .outer. F_i ] V_ab = Sum i=1..N [ r_ia F_ib ]
where r_i is the position of atom i and F_i the force acting on it. .outer. represents the outer product of two vectors.
It can be hard to evaluate the virial directly according to this definition because of periodic boundary conditions, so it’s useful to consider the contributions made by various terms in the potential.
The two-body contribution to the virial is
V_2 = R_ij .outer. F_i
The three-body contribution can be written in three different ways
V_3 = R_ik .outer. F_i + R_jk .outer. F_j V_3 = R_ij .outer. F_i + R_kj .outer. F_k V_3 = -(R_ij .outer. F_j + R_ik .outer. F_k)
where R_ij = r_i - r_j is the vector from atom i to atom j, and F_i is the force on atom i, and ‘.outer.’ represents the vector outer product.