# Updating virial in IForceProvider

**URL:** <https://gromacs.bioexcel.eu/t/updating-virial-in-iforceprovider/7343>\
**Category:** Developers discussions\
**Created:** [October 6, 2023, 3:58pm UTC](https://gromacs.bioexcel.eu/t/updating-virial-in-iforceprovider/7343 "2023-10-06T15:58:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![aalhossary](https://dub1.discourse-cdn.com/flex017/user_avatar/gromacs.bioexcel.eu/aalhossary/32/2045_2.png) [@aalhossary](https://gromacs.bioexcel.eu/u/aalhossary)\
**Post date:** [October 6, 2023, 3:58pm UTC](https://gromacs.bioexcel.eu/t/updating-virial-in-iforceprovider/7343/1 "2023-10-06T15:58:25Z")

</div>

The `IForceProvider::calculateForces` has a `gmx::ForceProviderOutput` as a parameter where I should update the forces of relevant atoms.

Well. We have to update the `forceProviderOutput` object `ForceWithVirial`, when the `computeVirial_` is `true`.

How to calculate the virial? Is there a sample code for that calculation?

---

<div class="post-metadata">

**Author:** ![hess](https://dub1.discourse-cdn.com/flex017/user_avatar/gromacs.bioexcel.eu/hess/32/416_2.png) [@hess](https://gromacs.bioexcel.eu/u/hess)\
**Post date:** [October 9, 2023, 7:21am UTC](https://gromacs.bioexcel.eu/t/updating-virial-in-iforceprovider/7343/2 "2023-10-09T07:21:34Z")

</div>

The virial is formula (28) on this page:  
[https://manual.gromacs.org/current/reference-manual/algorithms/molecular-dynamics.html#compute-forces](https://manual.gromacs.org/current/reference-manual/algorithms/molecular-dynamics.html#compute-forces)

That is what you need to compute and to add to the virial matrix.

---

<div class="post-metadata">

**Author:** ![Hub](https://dub1.discourse-cdn.com/flex017/user_avatar/gromacs.bioexcel.eu/hub/32/634_2.png) [@Hub](https://gromacs.bioexcel.eu/u/Hub)\
**Post date:** [October 9, 2023, 8:31am UTC](https://gromacs.bioexcel.eu/t/updating-virial-in-iforceprovider/7343/3 "2023-10-09T08:31:05Z")

</div>

Hi,

One way is to increment the forces of the relevant atoms with `forceProviderOutput->forceWithVirial_.force_`.  
Then, compute the virial contribution of those atoms and forces with a local variable `matrix vir`.  
Then, add this matrix `vir` to the global virial through `forceProviderOutput->forceWithVirial_.addVirialContribution(vir);` which takes into account the boolean `computeVirial_`.
