import pylab
import subprocess
from NL.ComputerScienceUtilities import Platform
from NL.ComputerScienceUtilities.Exceptions import NLIOError
from ATKBasePaths import resourcesBasePath


# Utility to locate the path of the plumed executable.
def plumedPath():
    """
    """
    if Platform.isWindows():
        return os.path.join(resourcesBasePath(), 'bin', 'plumed', 'plumed.exe')
    else:
        return os.path.join(resourcesBasePath(), 'libexec', 'plumed')

# Set the names of the hills file.
hills_name = 'HILLS'

# Set the filename to store the free energy profile.
free_energy_name = 'free_energy.dat'

# Call the plumed standalone executable.
command = [
    plumedPath(),
    '--standalone-executable',
    'sum_hills',
    '--hills',
    hills_name,
    '--outfile',
    free_energy_name,
]
subprocess.call(command)

# Check that the file has been created.
if not os.path.exists(free_energy_name):
    raise NLIOError('The free energy file %s does not exist' % free_energy_name)

# Load the free energy profile.
fe_data = numpy.loadtxt(free_energy_name)

# If you didn't specify any units when running in the metadynamics input script,
# the energy will be in kJ/mol
# fe_data[:, 1] = fe_data[:, 1]*kiloJoulePerMol/eV

# Plot.
pylab.plot(fe_data[:, 0], fe_data[:, 1])
pylab.xlabel('CV 1', fontsize=16)
pylab.ylabel('F (eV)', fontsize=16)

# Show the plot.
pylab.show()

# If you are running on a remote machine you maybe do not want to show the
# plot, but save the plot to a file.
pylab.savefig("Free_energy.png" )
