Beispiel #1
0
class SplitPDB(object):
    """
    Split the models of a PDB file into new PDB file, where a model corresponds to a new PDB file
    """

    def __init__(self, opts=None):
        """
        @type self: koala.SplitPDB.SplitPDB
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts
        self.path_runs = PathRuns()

    def run_SplitPDB(self):
        """
        Get the PDB input files and run the splitting
        @type self: koala.SplitPDB.SplitPDB
        """
        try:
            self.path_runs.set_path_execute()
            self.path_runs.set_execution_directory()

            link_name = os.path.join(self.opts.outputdir, os.path.basename(self.opts.pdbName))
            if not os.path.exists(link_name):
                os.symlink(self.opts.inputPDB, link_name)
                os.system("cp %s %s" % (link_name, self.path_runs.get_path_execution()))

            pdbs = parse_pdb(
                    self.path_runs.get_path_execution(),
                    os.path.join(self.path_runs.get_path_execution(), self.opts.pdbName))

            path_output, file_output = os.path.split(self.opts.output)

            send_multiple_outputs(
                    self.path_runs.get_path_execution(),
                    pdbs, self.opts.galaxydir,
                    self.opts.outputID)

            if self.opts.createCompressFile == "True":
                if compress_files(pdbs, self.path_runs.get_path_execution(), self.opts.toolname):
                    path_output, file_output = os.path.split(self.opts.outputZip)
                    send_output_results(
                            path_output,
                            file_output,
                            os.path.join(
                                self.path_runs.get_path_execution(), '%s.zip' % self.opts.toolname))

        except Exception, e:
            show_error_message(str(e))
Beispiel #2
0
 def __init__(self, opts=None):
     """
     @type self: koala.SplitPDB.SplitPDB
     @type opts: OptionParser parameters
     """
     assert opts is not None
     self.opts = opts
     self.path_runs = PathRuns()
Beispiel #3
0
 def __init__(self, opts=None):
     """
     @type self: koala.CheckPDBStructure.CheckPDBStructure
     @type opts: OptionParser parameters
     """
     assert opts is not None
     self.opts = opts
     self.path_runs = PathRuns()
 def __init__(self, opts=None):
     """
     @type self: koala.BuildConformation2PG.BuildConformation2PG
     @type opts: OptionParser parameters
     """
     assert opts is not None
     self.opts = opts
     self.path_runs = PathRuns()
     self.framework = Params("2PG")
 def __init__(self, opts=None):
     """
     @type self: koala.ProtPredEDA.ProtPredEDA
     @type opts: ArgsParse parameters
     """
     assert opts is not None
     self.opts = opts
     self.time_execution = TimeJobExecution()
     self.path_runs = PathRuns()
     self.framework = Params('ProtPred-EDA', 'rboa')
 def __init__(self, opts=None):
     """
     @type self: koala.SortByFront.SortByFront
     @type opts: OptionParser parameters
     """
     assert opts is not None
     self.opts = opts
     self.time_execution = TimeJobExecution()
     self.path_runs = PathRuns()
     self.framework = Params('2PG')
Beispiel #7
0
 def __init__(self, opts=None):
     """
     @type self: koala.BuildPopulationMEAMT.BuildPopulationMEAMT
     @type opts: OptionParser parameters
     """
     assert opts is not None
     self.opts = opts
     self.time_execution = TimeJobExecution()
     self.path_runs = PathRuns()
     self.framework = Params('MEAMT')
Beispiel #8
0
    def __init__(self, opts=None):
        """
        @type self: koala.NSGAII2PG.NSGAII2PG
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts

        self.time_execution = TimeJobExecution()
        self.path_runs = PathRuns()
        self.framework = Params("2PG")
Beispiel #9
0
class CheckPDBStructure(object):
    """
    Check PDB structure according to GROMACS.
    This scripts uses the pdb2gmx to verify the PDB files.
    """
    path_execute = None
    check_pdb_log = 'check-pdb-log.txt'

    os.environ["GMX_MAXBACKUP"] = "-1"

    def __init__(self, opts=None):
        """
        @type self: koala.CheckPDBStructure.CheckPDBStructure
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts
        self.path_runs = PathRuns()

    def log_by_pdb2gmx(self, pdbfile, stderr=None, stdout=None):
        """
        Write the log file with the stderr from pdb2gmx
        @type self: koala.CheckPDBStructure.CheckPDBStructure
        @type pdbfile: file
        @type stderr: string
        @type stdout: string
        """
        try:
            f_log = open(
                os.path.join(self.path_runs.get_path_execution(), self.check_pdb_log), "a+")
            pdbfile = os.path.split(pdbfile)[1]
            outline = "STARTING LOG OF " + pdbfile + "\n"
            f_log.write(outline)
            outline = stderr + "\n"
            f_log.write(outline)
            outline = "FINISHED LOG OF " + pdbfile + "\n\n\n"
            f_log.write(outline)
            f_log.close()
        except Exception, e:
            show_error_message(str(e))
Beispiel #10
0
class MergePDB(object):
    """
    Merge a set of PDB files into models on a single PDB file
    """

    methods = []
    ignoreoutfiles = ['.pdb']

    def __init__(self, opts=None):
        """
        @type self: koala.MergePDB.MergePDB
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts
        self.path_runs = PathRuns()

    def run_MergePDB(self):
        """
        Get the input PDB files and run to merge
        @type self: koala.MergePDB.MergePDB
        """

        self.path_runs.set_path_execute()
        self.path_runs.set_execution_directory()

        if self.opts.compressedFile == '1':
            if zipfile.is_zipfile(opts.inputPDBs):
                extract_zip_file(opts.inputPDBs, self.path_runs.get_path_execution())
            else:
                try:
                    inF = gzip.GzipFile(opts.inputPDBs, 'rb')
                    f = inF.read()
                    inF.close()
                    if f:
                        extract_gz_file(opts.inputPDBs, self.path_runs.get_path_execution())
                except Exception, e:
                    raise Exception("The input file could not be read.\n%s" % e)
        else:
Beispiel #11
0
class Random2PG(object):
    """
    Execute the 2PG Random evolutionary algorithm.
    """

    progname = "2PG Random"
    opts = None
    sequence = None
    initTime = 0
    endTime = 0
    ignoreoutfiles = ['.pdb']

    os.environ["GMX_MAXBACKUP"] = "-1"

    def __init__(self, opts=None):
        """
        @type self: koala.Random2PG.Random2PG
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts

        self.time_execution = TimeJobExecution()
        self.path_runs = PathRuns()
        self.framework = Params('2PG')

    def makeHtml(self):
        """ Create an HTML file content to list all the artifacts found in the html_dir
        @type self: koala.Random2PG.Random2PG
        """
        try:
            galhtmlprefix = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
            <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta name="generator" content="Galaxy %s tool output" />
            <title></title>
            <link rel="stylesheet" href="/static/koala.css" type="text/css" />
            <link rel="stylesheet" href="/static/style/base.css" type="text/css" />
            <script type="text/javascript"
            src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
            <script src="http://code.highcharts.com/highcharts.js"></script>
            <script src="http://code.highcharts.com/highcharts-more.js"></script>
            <script src="http://code.highcharts.com/modules/exporting.js"></script>
            </head>
            <body>
            <div class="toolFormBody">"""
            galhtmlpostfix = """</div></body></html>\n"""

            flist = os.listdir(self.opts.htmlfiledir)
            flist.sort()
            html = []
            html.append(galhtmlprefix % self.progname)
            html.append('<div class="sucessmessage">')
            html.append('<br>')
            html.append('<h1 align="center">2PG Random Ab Initio Algorithm results</h1><br></div>')

            html.append('<br>')
            html.append('<div class="sectionmessage">')
            html.append('<br>Submitted Primary Sequence.<br><br></div>')
            html.append('<div class="code">')
            html.append('Length: %s<br>' % len(self.sequence))
            html.append('%s<br></div>' % self.sequence)

            fhtml = []
            fitFiles = []
            outputfiles = []
            compressedFile = []
            imageFiles = []
            if len(flist) > 0:
                for rownum, fname in enumerate(flist):
                    dname, e = os.path.splitext(fname)
                    sfsize = get_file_size(fname, self.opts.htmlfiledir)

                    if e.lower() == ".fit":
                        fitFiles.append(fname)
                    elif e.lower() == ".png":
                        imageFiles.append(fname)
                    elif e.lower() in ".zip, .gz":
                        compressedFile.append(fname)
                    elif not e.lower() in self.ignoreoutfiles:
                        outputfiles.append(fname)

            # Arquivos fit
            for fit in fitFiles:
                sfsize = get_file_size(fit, self.opts.htmlfiledir)
                fhtml.append('<tr>')
                fhtml.append('<td><a href="%s">%s</a></td>' % (fit, fit))
                fhtml.append('<td>%s</td>' % (sfsize))
                fhtml.append('</tr>')

            if len(fhtml) > 0:
                html.append('<br>')
                html.append('<div class="sectionmessage">')
                html.append('<br>Download Calculated values of selected Objectives.<br><br></div>')
                fhtml.insert(
                    0,
                    '<div class="filetables"><table border="1"><tr><th>File</th>'
                    '<th>Size</th></tr>\n')
                fhtml.append('</table></div><br>')
                html += fhtml

            fhtml = []

            # images (e depois models)
            listaArquivosPdb = list_directory(
                        self.path_runs.get_path_execution(),
                        'randomSolution-M*.pdb')

            if len(listaArquivosPdb) <= 20:
                size = int(len(listaArquivosPdb) / 5)
                rest = len(listaArquivosPdb) % 5
            else:
                size = 4  # vai mostrar no máximo 20 imagens
                rest = 0
            idx = 0  # controla indice das imagens e dos metodos
            start = 0
            end = 5  # limite de colunas para uma linha

            if size < 1:
                n = len(listaArquivosPdb)
                fhtml.append('<tr>')
                idx_linha = idx
                for i in range(0, n):
                    pdbName, ext = os.path.splitext(listaArquivosPdb[idx])
                    fhtml.append(
                        '<td><a href="%s.png"><img src="%s.png" '
                        'title="Click to see %s.png bigger" width="130"/></a></td>'
                        % (pdbName, pdbName, pdbName))
                    idx += 1
                idx = idx_linha
                fhtml.append('</tr><tr>')
                for i in range(0, n):
                    fhtml.append(
                        '<td><a href="%s">%s</a></td>' % (
                                listaArquivosPdb[idx], listaArquivosPdb[idx]))
                    idx += 1
                idx = idx_linha
                fhtml.append('</tr><tr>')
                for i in range(0, n):
                    sfsize = get_file_size(
                            listaArquivosPdb[idx],
                            self.opts.htmlfiledir)
                    fhtml.append('<td>%s</td>' % (sfsize))
                    idx += 1
                idx = idx_linha
                fhtml.append('</tr>')
            else:
                for img in range(0, size):
                    fhtml.append('<tr>')
                    idx_linha = idx
                    for i in range(start, end):
                        pdbName, ext = os.path.splitext(listaArquivosPdb[idx])
                        fhtml.append(
                            '<td><a href="%s.png"><img src="%s.png" '
                            'title="Click to see %s.png bigger" width="130"/></a></td>'
                            % (pdbName, pdbName, pdbName))
                        idx += 1
                    idx = idx_linha
                    fhtml.append('</tr><tr>')
                    for i in range(start, end):
                        fhtml.append(
                            '<td><a href="%s">%s</a></td>' % (
                                    listaArquivosPdb[idx], listaArquivosPdb[idx]))
                        idx += 1
                    idx = idx_linha
                    fhtml.append('</tr><tr>')
                    for i in range(start, end):
                        sfsize = get_file_size(
                                listaArquivosPdb[idx],
                                self.opts.htmlfiledir)
                        fhtml.append('<td>%s</td>' % (sfsize))
                        idx += 1
                    fhtml.append('</tr>')

                fhtml.append('<tr>')
                idx_linha = idx
                for i in range(0, rest):
                    pdbName, ext = os.path.splitext(listaArquivosPdb[idx])
                    fhtml.append(
                        '<td><a href="%s.png"><img src="%s.png" '
                        'title="Click to see %s.png bigger" width="130"/></a></td>'
                        % (pdbName, pdbName, pdbName))
                    idx += 1
                idx = idx_linha
                fhtml.append('</tr><tr>')
                for i in range(0, rest):
                    fhtml.append(
                        '<td><a href="%s">%s</a></td>' % (
                                listaArquivosPdb[idx], listaArquivosPdb[idx]))
                    idx += 1
                idx = idx_linha
                fhtml.append('</tr><tr>')
                for i in range(0, rest):
                    sfsize = get_file_size(
                            listaArquivosPdb[idx],
                            self.opts.htmlfiledir)
                    fhtml.append('<td>%s</td>' % (sfsize))
                    idx += 1
                idx = idx_linha
                fhtml.append('</tr>')

            if len(fhtml) > 0:
                html.append('<br>')
                html.append('<div class="sectionmessage">')
                html.append('<br>Best Tertiary Structures<br>')
                html.append('<br></div>')

                if(self.opts.useJmol == 'true'):
                    html.append('<div class="active-jmol">')
                    html.append('<br>')
                    html.append(
                        '<a href=/datasets/%s/display/%s.htm>Activate JMol</a>' % (
                            self.opts.datasetID, self.opts.datasetID))
                    html.append('<br></div>')

                model = ''
                if size < 1:
                    for i in range(0, len(listaArquivosPdb)):
                        model += '<th>Model</th>'
                else:
                    model = '<th>Model</th>'\
                        '<th>Model</th>'\
                        '<th>Model</th>'\
                        '<th>Model</th>'\
                        '<th>Model</th>'
                fhtml.insert(
                    0,
                    '<div class="filetables"><table border="1">'
                    '<tr>' +
                    model +
                    '</tr>\n')
                fhtml.append('</table></div><br/>')
                html += fhtml

            fhtml = []

            # Outros arquivos de output
            for output in outputfiles:
                sfsize = get_file_size(output, self.opts.htmlfiledir)
                fhtml.append('<tr>')
                fhtml.append('<td><a href="%s">%s</a></td>' % (output, output))
                fhtml.append('<td>%s</td>' % (sfsize))
                fhtml.append('</tr>')

            if len(fhtml) > 0:
                html.append('<br>')
                html.append('<div class="sectionmessage">')
                html.append('<br>Download the output files:<br><br></div>')
                fhtml.insert(
                    0,
                    '<div class="filetables"><table border="1"><tr><th>Output File</th>'
                    '<th>Size</th></tr>\n')
                fhtml.append('</table></div><br>')
                html += fhtml

            fhtml = []

            # arquivo zipado
            for output in compressedFile:
                sfsize = get_file_size(output, self.opts.htmlfiledir)
                fhtml.append('<tr>')
                fhtml.append('<td><a href="%s">%s</a></td>' % (output, output))
                fhtml.append('<td>%s</td>' % (sfsize))
                fhtml.append('</tr>')

            if len(fhtml) > 0:
                html.append('<br>')
                html.append('<div class="sectionmessage">')
                html.append('<br>Compressed file with all the output files<br><br></div>')
                fhtml.insert(
                    0,
                    '<div class="filetables"><table border="1"><tr><th>File</th>'
                    '<th>Size</th></tr>\n')
                fhtml.append('</table></div><br>')
                html += fhtml

            self.time_execution.set_job_end(datetime.datetime.now())
            self.endTime = datetime.datetime.now()

            dif = self.time_execution.calculate_time_execution()

            html.append('<div>Time execution:<br>')
            html.append('Start: %s<br>' %
                        self.time_execution.get_job_start().strftime("%d/%m/%Y %H:%M:%S"))
            html.append('End: %s<br>' %
                        self.time_execution.get_job_end().strftime("%d/%m/%Y %H:%M:%S"))
            html.append('Total time: ~%dh:%dm:%ds' % (dif[0], dif[1], dif[2]))
            html.append('</div>')

            html.append('<hr>')
            html.append('<div>Citation<br>')
            html.append('Please, cite the used algorithm in this tool:<br><br>')
            html.append('')
            html.append('<br></div>')

            html.append(galhtmlpostfix)
            htmlf = file(self.opts.filehtml, 'w')
            htmlf.write('\n'.join(html))
            htmlf.write('\n')
            htmlf.close()

        except Exception, e:
            show_error_message("Error on makeHtml:\n%s" % str(e))
class SortByFront(object):
    """
    Execute the 2PG Sort By Front Dominance algorithm to classify the PSP methods in Pareto fronts
    """

    methods = []
    ignoreoutfiles = ['.pdb', '.png']
    initTime = 0
    endTime = 0
    progname = "SortByFront"

    os.environ["GMX_MAXBACKUP"] = "-1"

    def __init__(self, opts=None):
        """
        @type self: koala.SortByFront.SortByFront
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts
        self.time_execution = TimeJobExecution()
        self.path_runs = PathRuns()
        self.framework = Params('2PG')

    def buildHighchart(self):
        """
        Create a Highchart chart with the algorithm result
        @type self: koala.SortByFront.SortByFront
        """

        try:
            # Load files
            files = list_directory(self.path_runs.get_path_execution(), '*.xvg')

            methods = self.methods

            # Objectivies
            obj1 = ""
            obj2 = ""

            x = [[]]*len(files)
            y = [[]]*len(files)

            for i, f in enumerate(files):
                f = os.path.join(self.path_runs.get_path_execution(), f)
                arq = open(f, "r")

                # Loading File
                x[i] = []
                y[i] = []
                for line in arq:
                    if line.find("#") == -1:
                        x[i].append(float(line.split("\t")[0].strip()))
                        y[i].append(float(line.split("\t")[1]))
                    else:
                        col = line.split("\t")
                        if len(col) > 1:
                            obj1 = col[0].replace('#', ' ')
                            obj2 = col[2]
                arq.close()

            chart = Highchart(renderTo="container2")
            chart.title("Pareto Fronts")
            chart.subtitle(
                "A graph with %s and %s objectivies showing at most four fronts, "
                "but the first as line and the others as scatter"
                % (obj1, obj2))

            graph_options = {
                "xAxis": {
                    "minPadding": 0.05,
                    "maxPadding": 0.1,
                    "title": {
                        'offset': 30,
                        'text': obj1,
                        'rotation': 0,
                    },
                },

                "yAxis": {
                    "minPadding": 0.05,
                    "maxPadding": 0.1,
                    "title": {
                        'offset': 50,
                        'text': obj2,
                        'rotation': -90,
                    },
                },

                "tooltip": {
                    "shared": True,
                    "useHTML": False,
                    # "valueDecimals": 3,
                },

            }

            data = []
            it = {}
            i_file = 0
            context = Context(prec=3, rounding=ROUND_UP)

            if(len(x) > 5):
                fronts = 4
            else:
                fronts = len(x)

            for i in range(fronts):  # no máximo as duas primeiras fronteiras
                data = []
                z = x[i]
                for ii, w in enumerate(z):
                    if(i == 0):
                        it["name"] = methods[i_file]
                        i_file += 1
                    else:
                        it["name"] = "front%d" % i
                    if(not math.isinf(z[ii])):
                        it["x"] = (context.create_decimal_from_float(z[ii])).quantize(
                            Decimal('.2'),
                            rounding=ROUND_UP)
                    else:
                        it["x"] = "0.0"
                    if(not math.isinf(y[i][ii])):
                        it["y"] = (context.create_decimal_from_float(y[i][ii])).quantize(
                            Decimal('.2'),
                            rounding=ROUND_UP)
                    else:
                        it["y"] = "0.0"
                    data.append(it)
                    it = {}

                if(i == 0):
                    chart.add_data_set(data, name="front%d" % i, index=i, marker={"enabled": True})
                else:
                    chart.add_data_set(data, series_type="scatter", name="front%d" % i, index=i)

            chart.set_options(graph_options)
            return chart.generate()

        except Exception, e:
            show_error_message("Error on building highcharts.\n%s" % e)
Beispiel #13
0
class BuildPopulationMEAMT(object):
    """
    Execute the MEAMT Build Population algorithm.
    """

    sequence = None
    path_execute = None
    os.environ["GMX_MAXBACKUP"] = "-1"

    def __init__(self, opts=None):
        """
        @type self: koala.BuildPopulationMEAMT.BuildPopulationMEAMT
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts
        self.time_execution = TimeJobExecution()
        self.path_runs = PathRuns()
        self.framework = Params('MEAMT')

    def main(self):
        """
        Create the MEAMT Build Population configuration file and begin
        the execution to create a initial population.

        @type self: koala.BuildPopulationMEAMT.BuildPopulationMEAMT
        """
        try:
            self.path_runs.set_path_execute()
            self.path_runs.set_execution_directory()

            print 'create dirs'

            self.sequence = create_local_fasta_file(
                    self.path_runs.get_path_execution(),
                    self.opts.fromFasta,
                    self.opts.inputFasta,
                    self.opts.toolname,
                    self.framework)

            print 'create fasta'

            copy_necessary_files(
                self.path_runs.get_path_execute(),
                self.path_runs.get_path_execution(),
                self.framework.get_framework())

            print 'copy files'

            self.framework.set_command(
                self.path_runs.get_path_execution(),
                'aemt-pop-up2')

            print 'set command'

            size = int(self.opts.sizePopulation) / 15

            cl = [
                self.framework.get_command(),
                str(0),
                self.opts.sizePopulation,
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(size),
                str(0),
                str(0),
                self.opts.VanderWaalsWeight,
                self.opts.ChargeWeight,
                str(0),
                str(0),
                str(0),
                str(0),
                str(0),
                self.opts.SolvWeight,
                self.opts.HbondWeight,
                os.path.join(self.path_runs.get_path_execution(), "fasta.txt"),
                os.path.join(self.path_runs.get_path_execution(), "result.txt"),
                os.path.join(self.path_runs.get_path_execution(), "pop_meamt.txt"),
                os.path.join(self.path_runs.get_path_execution(), "protein.pdb"),
                os.path.join(self.path_runs.get_path_execution(), "saida1.txt"),
                os.path.join(self.path_runs.get_path_execution(), "angles.txt"),
                str(0),
                os.path.join(self.path_runs.get_path_execution(), "meat.txt"),
                '&']

            print cl

            retProcess = subprocess.Popen(cl, 0, None, None, None, False)
            retProcess.wait()

            path_output, file_output = os.path.split(self.opts.output)

            result, html = get_result_files(
                self.path_runs.get_path_execution(), self.opts.toolname)

            send_output_results(path_output, file_output, result)

        except Exception, e:
            show_error_message(str(e))
class RenameAtoms(object):
    """
    Rename the missing atoms of a PDB file according to GROMACS
    """

    path_execute = None
    os.environ["GMX_MAXBACKUP"] = "-1"

    def __init__(self, opts=None):
        """
        @type self: koala.RenameAtoms.RenameAtoms
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts
        self.path_runs = PathRuns()

    def rename_atoms_structure(self, pdbfile, gmx_path, forcefield):
        """
        Create a subprocess to rename the atoms of the PDB input file using pdb2gmx
        @type self: koala.RenameAtoms.RenameAtoms
        @type pdbfile: file
        @type gmx_path: string
        @type forcefield: string
        """
        delete_check_files(self.path_runs.get_path_execution())

        program = os.path.join(gmx_path, "pdb2gmx")
        process = Popen(
            [program, "-f", pdbfile, "-o", pdbfile, "-p", "check.top", "-water", "none", "-ff", forcefield],
            stdout=PIPE,
            stderr=PIPE,
        )
        stdout, stderr = process.communicate()
        process.wait()

        delete_check_files(self.path_runs.get_path_execution())

    def run_RenameAtoms(self):
        """
        Get the PDB file and run the renaming
        @type self: koala.CheckPDBStructure.CheckPDBStructure
        """
        try:
            self.path_runs.set_path_execute()
            self.path_runs.set_execution_directory()

            self.opts.pdbName = self.opts.pdbName.replace(" ", "-").replace("(", "").replace(")", "")

            link_name = os.path.join(self.opts.outputdir, os.path.basename(self.opts.pdbName))
            if not os.path.exists(link_name):
                os.symlink(self.opts.inputPDB, link_name)
                os.system("cp %s %s" % (link_name, self.path_runs.get_path_execution()))

            self.rename_atoms_structure(
                os.path.join(self.path_runs.get_path_execution(), self.opts.pdbName),
                get_path_gromacs(),
                self.opts.forceField,
            )

            path_output, file_output = os.path.split(self.opts.output)

            send_output_results(
                path_output, file_output, os.path.join(self.path_runs.get_path_execution(), self.opts.pdbName)
            )

        except Exception, e:
            show_error_message(str(e))
class DominanceRanking(object):
    """
    Calculate the Dominance Ranking of Protein Structure Prediction methods
    """

    path_execute = None
    methods = []
    headers = []
    ordered_headers = None
    data = []
    ignoreoutfiles = ['.pdb']
    initTime = 0
    endTime = 0
    combinations = None
    progname = "DominanceRanking"

    os.environ["GMX_MAXBACKUP"] = "-1"

    def __init__(self, opts=None):
        """
        @type self: koala.DominanceRanking.DominanceRanking
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts

        self.time_execution = TimeJobExecution()
        self.path_runs = PathRuns()
        self.framework = Params('2PG')

    def build_Highchart(self, objectivies, container="container"):
        """
        Create a Highchart chart with the algorithm result
        @type self: koala.DominanceRanking.DominanceRanking
        @type objectivies: string
        @type container: string
        """
        try:
            # Load files
            objs = objectivies.split(",")
            files = list_directory(
                self.path_runs.get_path_execution(), '*%s_%s*.xvg' % (objs[0], objs[1]))
            images = self.methods

            x = [[]]*len(files)
            y = [[]]*len(files)

            for i, f in enumerate(files):
                f = os.path.join(self.path_runs.get_path_execution(), f)
                arq = open(f, "r")

                # Loading File
                x[i] = []
                y[i] = []
                for line in arq:
                    if line.find("#") == -1:
                        x[i].append(float(line.split("\t")[0].strip()))
                        y[i].append(float(line.split("\t")[1]))
                arq.close()

            chart = Highchart(renderTo=container)
            chart.title("Pareto Fronts")
            chart.subtitle("A graph with %s and %s objectivies" % (objs[0], objs[1]))

            graph_options = {
                "xAxis": {
                    "minPadding": 0.05,
                    "maxPadding": 0.1,
                    "title": {
                        'offset': 30,
                        'text': objs[0],
                        'rotation': 0,
                    },
                },

                "yAxis": {
                    "minPadding": 0.05,
                    "maxPadding": 0.1,
                    "title": {
                        'offset': 50,
                        'text': objs[1],
                        'rotation': -90,
                    },
                },

                "tooltip": {
                    "shared": True,
                    "useHTML": False,
                    "valueDecimals": 3,
                },
            }

            data = []
            it = {}
            i_file = 0
            context = Context(prec=3, rounding=ROUND_UP)

            if(len(x) >= 4):
                fronts = 4
            else:
                # fronts = 2
                fronts = len(x)

            for i in range(fronts):
                data = []
                z = x[i]
                for ii, w in enumerate(z):
                    if(i_file < len(images)):
                        it["name"] = images[i_file]
                        i_file += 1
                    else:
                        it["name"] = "front%d" % i
                    it["x"] = (context.create_decimal_from_float(z[ii])).quantize(
                            Decimal('.1'),
                            rounding=ROUND_UP)
                    it["y"] = (context.create_decimal_from_float(y[i][ii])).quantize(
                            Decimal('.1'),
                            rounding=ROUND_UP)
                    data.append(it)
                    it = {}

                if(i == 0):
                    chart.add_data_set(data, name="front%d" % i, index=i, marker={"enabled": True})
                else:
                    chart.add_data_set(data, series_type="scatter", name="front%d" % i, index=i)

            chart.set_options(graph_options)
            return chart.generate()

        except Exception, e:
            show_error_message("Error while building the Highchart:\n%s" % e)
class BuildConformation2PG(object):
    """
    Execute the 2PG Build Conformation algorithm.
    """

    os.environ["GMX_MAXBACKUP"] = "-1"

    def __init__(self, opts=None):
        """
        @type self: koala.BuildConformation2PG.BuildConformation2PG
        @type opts: OptionParser parameters
        """
        assert opts is not None
        self.opts = opts
        self.path_runs = PathRuns()
        self.framework = Params("2PG")

    def run_Build_Conformation(self):
        """
        Create the 2PG Build Conformation configuration file and begin
        the execution to create a initial population.

        @type self: koala.BuildConformation2PG.BuildConformation2PG
        """
        try:
            self.path_runs.set_path_execute()
            self.path_runs.set_execution_directory()

            self.sequence = create_local_fasta_file(
                self.path_runs.get_path_execution(),
                self.opts.fromFasta,
                self.opts.inputFasta,
                self.opts.toolname,
                self.framework,
            )

            copy_necessary_files(
                self.path_runs.get_path_execute(), self.path_runs.get_path_execution(), self.framework.get_framework()
            )

            self.framework.set_parameter("gromacs_energy_min", self.opts.gromacsEnergyMin)
            self.framework.set_parameter("SizePopulation", self.opts.sizePopulation)
            self.framework.set_parameter("force_field", self.opts.forceField)
            self.framework.set_parameter("rotamer_library", self.opts.rotamerLibrary)

            if self.opts.forceField == "amber99sb-ildn":
                self.framework.set_parameter("c_terminal_charge", self.opts.cTerminal)
                self.framework.set_parameter("n_terminal_charge", self.opts.nTerminal)

            self.framework.set_parameter(
                "SequenceAminoAcidsPathFileName", self.path_runs.get_path_execution() + "fasta.txt"
            )
            self.framework.set_parameter("Local_Execute", self.path_runs.get_path_execution())
            self.framework.set_parameter("Path_Gromacs_Programs", get_path_gromacs())
            self.framework.set_parameter("NativeProtein", "%s1VII.pdb" % self.path_runs.get_path_execution())
            self.framework.set_parameter("Database", "%sDatabase/" % get_path_algorithms("2pg_build_conformation"))

            create_configuration_file(self.path_runs.get_path_execution(), self.framework)

            self.framework.set_command(self.path_runs.get_path_execution(), "protpred-Gromacs_pop_initial")

            config = "configuration.conf"

            cl = [self.framework.get_command(), config, "&"]

            retProcess = subprocess.Popen(cl, 0, stdout=None, stderr=subprocess.STDOUT, shell=False)
            retCode = retProcess.wait()
            if retCode != 0:
                show_error_message("The 2PG framework finished wrong.\nContact the system administrator.")

            path_output, file_output = os.path.split(self.opts.output)

            result, html = get_result_files(self.path_runs.get_path_execution(), self.opts.toolname)

            send_output_results(path_output, file_output, result)

        except Exception, e:
            show_error_message(str(e))