# Path: twod_materials/friction/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
#     QUEUE = config_vars['queue_system'].lower()
#     QUEUE = 'slurm'
#     QUEUE = 'pbs'
# def run_gamma_calculations(submit=True, step_size=0.5):
# def run_normal_force_calculations(basin_and_saddle_dirs,
#                                   spacings=np.arange(1.5, 4.25, 0.25),
#                                   submit=True):
# 
# Path: twod_materials/friction/analysis.py
# def plot_gamma_surface(fmt='pdf'):
#     """
#     Collect the energies from a grid of static energy
#     calculations to plot the Gamma surface between two layers of the 2D
#     material.
# 
#     Args:
#         fmt (str): matplotlib format style. Check the matplotlib
#             docs for options.
#     """
# 
#     os.chdir('friction/lateral')
# 
#     static_dirs = [
#         d.split('x') for d in os.listdir(os.getcwd()) if 'x' in d and
#         len(d) == 3
#     ]
# 
#     n_divs_x = max([int(d[0]) for d in static_dirs])
#     n_divs_y = max([int(d[1]) for d in static_dirs])
# 
#     lattice = Structure.from_file('POSCAR').lattice
#     area = np.cross(lattice._matrix[0], lattice._matrix[1])[2]
# 
#     ax = plt.figure(figsize=(n_divs_x * 1.2, n_divs_y * 1.2)).gca()
# 
#     ax.set_xlim(0, n_divs_x + 1)
#     ax.set_ylim(0, n_divs_y + 1)
# 
#     ENERGY_ARRAY = []
# 
#     X_VALUES = range(n_divs_x + 1)
#     Y_VALUES = range(n_divs_y + 1)
# 
#     not_converged = []
#     for x in X_VALUES:
#         ENERGY_ARRAY.append([])
#         for y in Y_VALUES:
#             dir = '{}x{}'.format(x, y)
#             os.chdir(dir)
#             try:
#                 energy = Vasprun('vasprun.xml').final_energy / area
#                 ENERGY_ARRAY[x].append(energy)
#             except:
#                 not_converged.append('{}x{}'.format(x, y))
#                 ENERGY_ARRAY[x].append(0)
#             os.chdir('../')
#         ENERGY_ARRAY[x].append(ENERGY_ARRAY[x][0])
# 
#     ENERGY_ARRAY.append([])
#     #ENERGY_ARRAY[n_divs_x] = ENERGY_ARRAY[0]
# 
#     if not_converged:
#         warnings.warn('{} did not converge.'.format(not_converged))
#         for coords in not_converged:
#             ENERGY_ARRAY[
#                 int(coords.split('x')[0])][int(coords.split('x')[1])] = energy
# 
#     minima = []
#     maxima = []
#     for x in X_VALUES:
#         minima.append(min(ENERGY_ARRAY[x]))
#         maxima.append(max(ENERGY_ARRAY[x]))
# 
#     abs_minimum = min(minima)
#     abs_maximum = max(maxima)
# 
#     for x in range(n_divs_x + 1):
#         for y in range(n_divs_y + 1):
# 
#             # Plot all energies relative to the global minimum.
#             scaled_energy = ENERGY_ARRAY[x][y] - abs_minimum
#             if '{}x{}'.format(x, y) in not_converged:
#                 color_code = 'w'
#             else:
#                 color_code = plt.cm.jet(
#                     scaled_energy / (abs_maximum - abs_minimum)
#                     )
# 
#             ax.add_patch(plt.Rectangle((x, y), width=1, height=1,
#                                        facecolor=color_code,
#                                        linewidth=0))
# 
#     # Get rid of annoying ticks.
#     ax.axes.get_yaxis().set_ticks([])
#     ax.axes.get_xaxis().set_ticks([])
# 
#     os.chdir('../../')
# 
#     plt.savefig('gamma_surface.{}'.format(fmt), transparent=True)
#     plt.close()
# 
# Path: twod_materials/utils.py
# def is_converged(directory):
#     """
#     Check if a relaxation has converged.
# 
#     Args:
#         directory (str): path to directory to check.
# 
#     Returns:
#         boolean. Whether or not the job is converged.
#     """
# 
#     try:
#         if Vasprun('{}/vasprun.xml'.format(directory)).converged:
#             return True
#         else:
#             return False
# 
#     except:
#         return False


from twod_materials.friction.startup import run_friction_calculations
from twod_materials.friction.analysis import plot_gamma_surface
from twod_materials.utils import is_converged
import os
import time


INTERVAL = 360  # Seconds between convergence checks

directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
               and dir not in ['all_competitors']]

if __name__ == '__main__':

    converged = {}

    for directory in directories:
        os.chdir(directory)
        converged[directory] = False
        run_friction_calculations()
        os.chdir('../')

    loop = True

    while loop:
        time.sleep(INTERVAL)

        loop = False

        for directory in directories:
            os.chdir(directory)
            converged[directory] = True
            for subdirectory in [
                    dir for dir in os.listdir(os.getcwd())
                    if os.path.isdir(dir)]:

# Path: twod_materials/friction/startup.py
# PACKAGE_PATH = twod_materials.__file__.replace('__init__.pyc', '')
# PACKAGE_PATH = PACKAGE_PATH.replace('__init__.py', '')
# PACKAGE_PATH = '/'.join(PACKAGE_PATH.split('/')[:-2])
# VASP = config_vars['normal_binary']
# VASP_2D = config_vars['twod_binary']
# VDW_KERNEL = config_vars['vdw_kernel']
#     QUEUE = config_vars['queue_system'].lower()
#     QUEUE = 'slurm'
#     QUEUE = 'pbs'
# def run_gamma_calculations(submit=True, step_size=0.5):
# def run_normal_force_calculations(basin_and_saddle_dirs,
#                                   spacings=np.arange(1.5, 4.25, 0.25),
#                                   submit=True):
# 
# Path: twod_materials/friction/analysis.py
# def plot_gamma_surface(fmt='pdf'):
#     """
#     Collect the energies from a grid of static energy
#     calculations to plot the Gamma surface between two layers of the 2D
#     material.
# 
#     Args:
#         fmt (str): matplotlib format style. Check the matplotlib
#             docs for options.
#     """
# 
#     os.chdir('friction/lateral')
# 
#     static_dirs = [
#         d.split('x') for d in os.listdir(os.getcwd()) if 'x' in d and
#         len(d) == 3
#     ]
# 
#     n_divs_x = max([int(d[0]) for d in static_dirs])
#     n_divs_y = max([int(d[1]) for d in static_dirs])
# 
#     lattice = Structure.from_file('POSCAR').lattice
#     area = np.cross(lattice._matrix[0], lattice._matrix[1])[2]
# 
#     ax = plt.figure(figsize=(n_divs_x * 1.2, n_divs_y * 1.2)).gca()
# 
#     ax.set_xlim(0, n_divs_x + 1)
#     ax.set_ylim(0, n_divs_y + 1)
# 
#     ENERGY_ARRAY = []
# 
#     X_VALUES = range(n_divs_x + 1)
#     Y_VALUES = range(n_divs_y + 1)
# 
#     not_converged = []
#     for x in X_VALUES:
#         ENERGY_ARRAY.append([])
#         for y in Y_VALUES:
#             dir = '{}x{}'.format(x, y)
#             os.chdir(dir)
#             try:
#                 energy = Vasprun('vasprun.xml').final_energy / area
#                 ENERGY_ARRAY[x].append(energy)
#             except:
#                 not_converged.append('{}x{}'.format(x, y))
#                 ENERGY_ARRAY[x].append(0)
#             os.chdir('../')
#         ENERGY_ARRAY[x].append(ENERGY_ARRAY[x][0])
# 
#     ENERGY_ARRAY.append([])
#     #ENERGY_ARRAY[n_divs_x] = ENERGY_ARRAY[0]
# 
#     if not_converged:
#         warnings.warn('{} did not converge.'.format(not_converged))
#         for coords in not_converged:
#             ENERGY_ARRAY[
#                 int(coords.split('x')[0])][int(coords.split('x')[1])] = energy
# 
#     minima = []
#     maxima = []
#     for x in X_VALUES:
#         minima.append(min(ENERGY_ARRAY[x]))
#         maxima.append(max(ENERGY_ARRAY[x]))
# 
#     abs_minimum = min(minima)
#     abs_maximum = max(maxima)
# 
#     for x in range(n_divs_x + 1):
#         for y in range(n_divs_y + 1):
# 
#             # Plot all energies relative to the global minimum.
#             scaled_energy = ENERGY_ARRAY[x][y] - abs_minimum
#             if '{}x{}'.format(x, y) in not_converged:
#                 color_code = 'w'
#             else:
#                 color_code = plt.cm.jet(
#                     scaled_energy / (abs_maximum - abs_minimum)
#                     )
# 
#             ax.add_patch(plt.Rectangle((x, y), width=1, height=1,
#                                        facecolor=color_code,
#                                        linewidth=0))
# 
#     # Get rid of annoying ticks.
#     ax.axes.get_yaxis().set_ticks([])
#     ax.axes.get_xaxis().set_ticks([])
# 
#     os.chdir('../../')
# 
#     plt.savefig('gamma_surface.{}'.format(fmt), transparent=True)
#     plt.close()
# 
# Path: twod_materials/utils.py
# def is_converged(directory):
#     """
#     Check if a relaxation has converged.
# 
#     Args:
#         directory (str): path to directory to check.
# 
#     Returns:
#         boolean. Whether or not the job is converged.
#     """
# 
#     try:
#         if Vasprun('{}/vasprun.xml'.format(directory)).converged:
#             return True
#         else:
#             return False
# 
#     except:
#         return False


# Path: examples/gamma_surface.py
from twod_materials.friction.startup import run_friction_calculations
from twod_materials.friction.analysis import plot_gamma_surface
from twod_materials.utils import is_converged
import os
import time



INTERVAL = 360  # Seconds between convergence checks

directories = [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)
               and dir not in ['all_competitors']]

if __name__ == '__main__':

    converged = {}

    for directory in directories:
        os.chdir(directory)
        converged[directory] = False
        run_friction_calculations()
        os.chdir('../')

    loop = True

    while loop:
        time.sleep(INTERVAL)

        loop = False

        for directory in directories:
            os.chdir(directory)
            converged[directory] = True
            for subdirectory in [
                    dir for dir in os.listdir(os.getcwd())
                    if os.path.isdir(dir)]:

                if not is_converged(subdirectory):