# Path: PyContact/gui/Plotters.py
# class SimplePlotter(MplPlotter):
#     """Simple plotter, used in the SASA view."""
#     def plot(self, x, y):
#         self.axes.plot(x, y)
#         self.axes.set_xlabel("x")
#         self.axes.set_ylabel("f(x)")
#         # self.axes.xaxis.set_label_position('top')
# 
#     def saveFigure(self, path, outputFormat):
#         self.fig.savefig(path + "." + outputFormat, format=outputFormat)
# 
#     def clearFigure(self):
#         self.fig.clf()
# 
# Path: PyContact/core/multi_trajectory.py
# def chunks(seq, num):
#     """splits the list seq in num (almost) equally sized chunks."""
#     avg = len(seq) / float(num)
#     out = []
#     last = 0.0
# 
#     while last < len(seq):
#         out.append(seq[int(last):int(last + avg)])
#         last += avg
# 
#     return out
# 
# Path: PyContact/core/Biochemistry.py
# def vdwRadius(atomType):
#     """Returns the van der Waals-radius matching the given atom type. Default value is 1.5 A."""
#     return vdwRadii.get(atomType, 1.5)
# 
# Path: PyContact/gui/Dialogues.py
# class TopoTrajLoaderDialog(QDialog):
#     """Dialog to load the topology and trajectory file."""
#     def __init__(self, parent=None):
#         super(TopoTrajLoaderDialog, self).__init__(parent)
#         self.setWindowTitle("Load Data")
#         self.psf = ""
#         self.dcd = ""
# 
#         grid = QGridLayout(self)
# 
#         buttonPsf = QPushButton("Topology")
#         buttonPsf.clicked.connect(self.pick_psf)
# 
#         buttonDcd = QPushButton("Trajectory")
#         buttonDcd.clicked.connect(self.pick_dcd)
# 
#         helpButton = HelpButton()
# 
#         grid.addWidget(buttonPsf, 0, 0)
#         grid.addWidget(buttonDcd, 0, 1)
#         buttons = QDialogButtonBox(
#             QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
#             Qt.Horizontal, self)
#         buttons.accepted.connect(self.accept)
#         buttons.rejected.connect(self.reject)
#         grid.addWidget(buttons, 1, 0)
#         grid.addWidget(helpButton, 2, 0)
# 
#     def pick_psf(self):
#         """Pick the topology file."""
#         psfname = QFileDialog.getOpenFileNames(self, "Open topology")
#         for file in psfname[0]:
#             self.psf = file
#             break
# 
#     def pick_dcd(self):
#         """Pick the trajectory file."""
#         dcdname = QFileDialog.getOpenFileNames(self, "Open trajectory")
#         for file in dcdname[0]:
#             self.dcd = file
#             break
# 
#     def configuration(self):
#         """Returns the chosen configuration."""
#         config = [self.psf, self.dcd]
#         return config
# 
#     @staticmethod
#     def getConfig(parent=None):
#         """Static method to create the dialog and return (date, time, accepted)."""
#         dialog = TopoTrajLoaderDialog(parent)
#         result = dialog.exec_()
#         config = dialog.configuration()
#         return config, result == QDialog.Accepted
# 
# Path: PyContact/gui/ErrorBox.py
# class ErrorBox(QMessageBox):
#     """Creates an Error dialog which displays the corresponding error message 'msg'."""
#     def __init__(self, msg):
#         super(ErrorBox, self).__init__()
#         self.msg = msg
#         self.setIcon(QMessageBox.Warning)
#         self.setText(self.msg)
#         self.setWindowTitle("Error")
#         self.setStandardButtons(QMessageBox.Ok)
# 
# Path: PyContact/gui/ErrorMessages.py
# class ErrorMessages():
#     """Error message shortcuts for the ErrorBox dialog."""
# 
#     NOEXPDATA = "No data to export."
# 
#     NODATA_PROMPTLOAD = "No data loaded. Click on \"Files -> Import Trajectory Data\" and load your MD trajectory."
# 
#     NOSCORES_PROMPTANALYSIS = "No data loaded. Click on \"Files -> Import Trajectory Data\" " \
#                               "and load your MD trajectory."
# 
#     CHOOSEFILE = "Please choose a topology and trajectory file!"
# 
#     RESID_REQUIRED = "Please analyze the trajectory with the resid box checked for both atom selections!"
# 
#     NOCONTACTS = "No data loaded or no filtered contacts available."
# 
#     FILE_NOT_FOUND = "Attempt to load trajectory failed. File does not exist."


import sip
import time
import os
import MDAnalysis
import numpy as np
import multiprocessing
from PyQt5.QtWidgets import QWidget, QProgressBar, QApplication, QFileDialog
from .Plotters import SimplePlotter
from .sasa_gui import *
from ..core.multi_trajectory import chunks
from ..core.Biochemistry import vdwRadius
from ..core.LogPool import *
from ..cy_modules import cy_gridsearch
from .Dialogues import TopoTrajLoaderDialog
from .ErrorBox import ErrorBox
from .ErrorMessages import ErrorMessages
        loadedData = self.topoloader.getConfig()
        self.psf = loadedData[0][0]
        self.dcd = loadedData[0][1]

    def clearData(self):
        """Clears the whole view and sets it to the initial state."""
        self.psf = ""
        self.dcd = ""
        self.allSasas = []
        self.totalFramesToProcess = 0
        self.sasaProgressBar.setProperty("value", 0)
        sip.delete(self.previewPlot)
        self.previewPlot = SimplePlotter(None, width=4, height=2, dpi=70)
        self.graphGridLayout.addWidget(self.previewPlot)
        self.sasaSelection1TextField.setText("")
        self.sasaSelection2TextField.setText("")
        self.sasaRestrictionTextField.setText("")


    def savePlot(self):
        """Saves the generated SASA plot over all frames."""
        fileName = QFileDialog.getSaveFileName(self, 'Export Path')
        if len(fileName[0]) > 0:
            path, file_extension = os.path.splitext(fileName[0])
            if file_extension == "":
                file_extension = ".png"
            file_extension = file_extension[1:]
            try:
                self.previewPlot.saveFigure(path, file_extension)
            except ValueError:

# Path: PyContact/gui/Plotters.py
# class SimplePlotter(MplPlotter):
#     """Simple plotter, used in the SASA view."""
#     def plot(self, x, y):
#         self.axes.plot(x, y)
#         self.axes.set_xlabel("x")
#         self.axes.set_ylabel("f(x)")
#         # self.axes.xaxis.set_label_position('top')
# 
#     def saveFigure(self, path, outputFormat):
#         self.fig.savefig(path + "." + outputFormat, format=outputFormat)
# 
#     def clearFigure(self):
#         self.fig.clf()
# 
# Path: PyContact/core/multi_trajectory.py
# def chunks(seq, num):
#     """splits the list seq in num (almost) equally sized chunks."""
#     avg = len(seq) / float(num)
#     out = []
#     last = 0.0
# 
#     while last < len(seq):
#         out.append(seq[int(last):int(last + avg)])
#         last += avg
# 
#     return out
# 
# Path: PyContact/core/Biochemistry.py
# def vdwRadius(atomType):
#     """Returns the van der Waals-radius matching the given atom type. Default value is 1.5 A."""
#     return vdwRadii.get(atomType, 1.5)
# 
# Path: PyContact/gui/Dialogues.py
# class TopoTrajLoaderDialog(QDialog):
#     """Dialog to load the topology and trajectory file."""
#     def __init__(self, parent=None):
#         super(TopoTrajLoaderDialog, self).__init__(parent)
#         self.setWindowTitle("Load Data")
#         self.psf = ""
#         self.dcd = ""
# 
#         grid = QGridLayout(self)
# 
#         buttonPsf = QPushButton("Topology")
#         buttonPsf.clicked.connect(self.pick_psf)
# 
#         buttonDcd = QPushButton("Trajectory")
#         buttonDcd.clicked.connect(self.pick_dcd)
# 
#         helpButton = HelpButton()
# 
#         grid.addWidget(buttonPsf, 0, 0)
#         grid.addWidget(buttonDcd, 0, 1)
#         buttons = QDialogButtonBox(
#             QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
#             Qt.Horizontal, self)
#         buttons.accepted.connect(self.accept)
#         buttons.rejected.connect(self.reject)
#         grid.addWidget(buttons, 1, 0)
#         grid.addWidget(helpButton, 2, 0)
# 
#     def pick_psf(self):
#         """Pick the topology file."""
#         psfname = QFileDialog.getOpenFileNames(self, "Open topology")
#         for file in psfname[0]:
#             self.psf = file
#             break
# 
#     def pick_dcd(self):
#         """Pick the trajectory file."""
#         dcdname = QFileDialog.getOpenFileNames(self, "Open trajectory")
#         for file in dcdname[0]:
#             self.dcd = file
#             break
# 
#     def configuration(self):
#         """Returns the chosen configuration."""
#         config = [self.psf, self.dcd]
#         return config
# 
#     @staticmethod
#     def getConfig(parent=None):
#         """Static method to create the dialog and return (date, time, accepted)."""
#         dialog = TopoTrajLoaderDialog(parent)
#         result = dialog.exec_()
#         config = dialog.configuration()
#         return config, result == QDialog.Accepted
# 
# Path: PyContact/gui/ErrorBox.py
# class ErrorBox(QMessageBox):
#     """Creates an Error dialog which displays the corresponding error message 'msg'."""
#     def __init__(self, msg):
#         super(ErrorBox, self).__init__()
#         self.msg = msg
#         self.setIcon(QMessageBox.Warning)
#         self.setText(self.msg)
#         self.setWindowTitle("Error")
#         self.setStandardButtons(QMessageBox.Ok)
# 
# Path: PyContact/gui/ErrorMessages.py
# class ErrorMessages():
#     """Error message shortcuts for the ErrorBox dialog."""
# 
#     NOEXPDATA = "No data to export."
# 
#     NODATA_PROMPTLOAD = "No data loaded. Click on \"Files -> Import Trajectory Data\" and load your MD trajectory."
# 
#     NOSCORES_PROMPTANALYSIS = "No data loaded. Click on \"Files -> Import Trajectory Data\" " \
#                               "and load your MD trajectory."
# 
#     CHOOSEFILE = "Please choose a topology and trajectory file!"
# 
#     RESID_REQUIRED = "Please analyze the trajectory with the resid box checked for both atom selections!"
# 
#     NOCONTACTS = "No data loaded or no filtered contacts available."
# 
#     FILE_NOT_FOUND = "Attempt to load trajectory failed. File does not exist."


# Path: PyContact/gui/SasaWidgets.py
import sip
import time
import os
import MDAnalysis
import numpy as np
import multiprocessing
from PyQt5.QtWidgets import QWidget, QProgressBar, QApplication, QFileDialog
from .Plotters import SimplePlotter
from .sasa_gui import *
from ..core.multi_trajectory import chunks
from ..core.Biochemistry import vdwRadius
from ..core.LogPool import *
from ..cy_modules import cy_gridsearch
from .Dialogues import TopoTrajLoaderDialog
from .ErrorBox import ErrorBox
from .ErrorMessages import ErrorMessages

        loadedData = self.topoloader.getConfig()
        self.psf = loadedData[0][0]
        self.dcd = loadedData[0][1]

    def clearData(self):
        """Clears the whole view and sets it to the initial state."""
        self.psf = ""
        self.dcd = ""
        self.allSasas = []
        self.totalFramesToProcess = 0
        self.sasaProgressBar.setProperty("value", 0)
        sip.delete(self.previewPlot)
        self.previewPlot = SimplePlotter(None, width=4, height=2, dpi=70)
        self.graphGridLayout.addWidget(self.previewPlot)
        self.sasaSelection1TextField.setText("")
        self.sasaSelection2TextField.setText("")
        self.sasaRestrictionTextField.setText("")


    def savePlot(self):
        """Saves the generated SASA plot over all frames."""
        fileName = QFileDialog.getSaveFileName(self, 'Export Path')
        if len(fileName[0]) > 0:
            path, file_extension = os.path.splitext(fileName[0])
            if file_extension == "":
                file_extension = ".png"
            file_extension = file_extension[1:]
            try:
                self.previewPlot.saveFigure(path, file_extension)
            except ValueError:

                box = ErrorBox("File format " + file_extension + " is not supported.\nPlease choose from eps, pdf, pgf,"