class AllTreesWindow(Window):
    def __init__(self, title, colorScheme, topologies_to_counts, rooted=False, outGroup=False): class DonutPlotWindow(Window):
    def __init__(self, title, labels, sizes, donutColors): class ScatterPlotWindow(Window):
    def __init__(self, title, windowsToTopologies, colors, heights): class PGTSTWindow(Window):
    def __init__(self, windowsToPGTST, title, xLabel='', yLabel=''): class RobinsonFouldsWindow(Window):
    def __init__(self, title1, data1, title2=None, data2=None, xLabel='Windows', yLabel='RF Distance'): class HeatMapWindow(Window):
    def __init__(self, title, sitesToInformative):
    def initCanvas(self): class BootstrapContractionWindow(Window):
    def __init__(self, seq1, seq2, confidenceThreshold, xLabel='', yLabel=''): class DStatisticWindow(Window):
    def __init__(self, dWindows, title='Windows to D Statistic', xLabel='Window Indices', yLabel='D Statistic values'): class MSRobinsonFouldsWindow(Window):
    def __init__(self, title, data, xLabel1='', yLabel1='', groupLabels1=()): class MSPercentMatchingWindow(Window):
    def __init__(self, title1, data1, xLabel1='', yLabel1='', groupLabels1=()): class MSTMRCAWindow(Window):
    def __init__(self, data, labels): class WindowsToInfSitesWindow(Window):
    def __init__(self, title, data, xLabel='Windows', yLabel='% Informative Sites'): class LStatisticWindow(Window):
    def __init__(self, lWindows, sigArray):     def _fromUtf8(s):
    def _translate(context, text, disambig):
    def _translate(context, text, disambig):
    def setupUi(self, PhylogeneticVisualization):
    def retranslateUi(self, PhylogeneticVisualization):
class Ui_PhylogeneticVisualization(object): class RAxMLOperations(QtCore.QThread):
    def __init__(self, parent=None):
        super(RAxMLOperations, self).__init__(parent)

    def taxon_names_getter(self, phylip):
        """
        Creates a list of taxon names from the inputted file
        Input:
        phylip --- a file inputted by the user
        Output:
        taxon_names --- a list of taxon names from the inputted phylip file
        """

        # Initialize a list for the taxa
        taxon_names = []

        with open(phylip) as f:
            # Create a list of each line in the file
            lines = f.readlines()

        # Iterate over each line after the first one
        for line in lines[1:]:
            # Add each sequence to a list
            taxon = line.split()[0]
            taxon_names.append(taxon)

        return taxon_names

    def raxml_species_tree(self, phylip, rooted=False, outgroup=None, customRax=False, customRaxCommand='', output_directory="RAxML_SpeciesTree"):
        """
        Runs RAxML on input PHYLIP file to create a species
        tree.

        Inputs:
        phylip -- a file inputted by the user.

        Returns:
        A species tree folder.
        """

        # Delete the folder and remake it if it already exists
        if os.path.exists(output_directory):
            shutil.rmtree(output_directory)
        os.makedirs(output_directory)
        self.emit(QtCore.SIGNAL('SPECIES_TREE_PER'), 10)

        if customRax:
            # run RAxML & wait until command line is finished running
            p = subprocess.Popen(customRaxCommand + " -s {0} -n txt".format(phylip), shell=True)
            p.wait()
        else:
            # run RAxML & wait until command line is finished running
            p = subprocess.Popen("raxmlHPC -f a -x12345 -p 12345 -# 2 -m GTRGAMMA -s {0} -n txt".format(phylip), shell=True)
            p.wait()

        self.emit(QtCore.SIGNAL('SPECIES_TREE_PER'), 60)

        # Regular expression for identifying floats
        float_pattern = "([+-]?\\d*\\.\\d+)(?![-+0-9\\.])"

        # Create a separate file with the topology of the best tree
        with open("RAxML_bestTree.txt") as f:
            # Read newick string from file
            topology = f.readline()
            # Delete float branch lengths, ":" and "\n" from newick string
            topology = ((re.sub(float_pattern, '', topology)).replace(":", "")).replace("\n", "")
            file = open("Topology_bestTree.txt", "w")
            file.write(topology)
            file.close()
        self.emit(QtCore.SIGNAL('SPECIES_TREE_PER'), 80)

        # If rooting is desired root the appropriate files
        if rooted:
            self.rooter("RAxML_bestTree.txt", outgroup)
            # self.rooter("RAxML_result.txt", outgroup)

        # windows
        if platform == "win32":
            # Move RAxML output files into their own destination folder - Windows
            os.rename("RAxML_bestTree.txt", output_directory + "\RAxML_ST_bestTree.txt")
            os.rename("RAxML_bipartitions.txt", output_directory + "\RAxML_ST_bipartitions.txt")
            os.rename("RAxML_bipartitionsBranchLabels.txt", output_directory + "\RAxML_ST_bipartitionsBranchLabels.txt")
            os.rename("RAxML_bootstrap.txt", output_directory + "\RAxML_ST_bootstrap.txt")
            os.rename("RAxML_info.txt", output_directory + "\RAxML_ST_info.txt")
            os.rename("topology_bestTree.txt", output_directory + "\Topology_ST_bestTree.txt")

        # mac
        elif platform == "darwin":
            # Move RAxML output files into their own destination folder - Mac
            os.rename("RAxML_bestTree.txt", output_directory + "/RAxML_ST_bestTree.txt")
            os.rename("RAxML_bipartitions.txt", output_directory + "/RAxML_ST_bipartitions.txt")
            os.rename("RAxML_bipartitionsBranchLabels.txt", output_directory + "/RAxML_ST_bipartitionsBranchLabels.txt")
            os.rename("RAxML_bootstrap.txt", output_directory + "/RAxML_ST_bootstrap.txt")
            os.rename("RAxML_info.txt", output_directory + "/RAxML_ST_info.txt")
            os.rename("topology_bestTree.txt", output_directory + "/Topology_ST_bestTree.txt")

        if platform == 'win32':
            with open('RAxML_SpeciesTree\RAxML_ST_bestTree.txt', 'r') as f:
                self.speciesTree = f.read().replace('\n', '')
        elif platform == 'darwin':
            with open('RAxML_SpeciesTree/RAxML_ST_bestTree.txt', 'r') as f:
                self.speciesTree = f.read().replace('\n', '')

        self.emit(QtCore.SIGNAL('SPECIES_TREE_PER'), 100)
        self.emit(QtCore.SIGNAL('SPECIES_TREE_COMPLETE'), 'Species Tree Generated', "'Show Details...' to view the species tree newick.", self.speciesTree)
        self.emit(QtCore.SIGNAL('SPECIES_TREE_COMPLETE_RETURN_ST'), self.speciesTree)
        print self.speciesTree

    def rooter(self, newick_file, outgroup):
        """
        Rewrites tree newick strings to be rooted
        Inputs:
        newick_file --- the file containing the newick string
        outgroup --- the outgroup to root at
        """

        # Create the tree object and root it
        tree = Phylo.read(newick_file, "newick")
        tree.rooted = True
        tree.root_with_outgroup(outgroup)

        # Write the newick string over the previous one
        Phylo.write(tree, newick_file, "newick")

    def window_splitter(self, filename, window_size, step_size):
        """
        Creates smaller PHYLIP files based on a window size inputted into
        the GUI.

        Inputs:
        filename --- name of the PHYLIP file to be used
        window_size --- the number of nucleotides to include in each window
        step_size --- the number of nucleotides between the beginning of each window

        Output:
        Smaller "window" files showing sections of the genome in PHYLIP format.
        """

        output_folder = "windows"

        # Delete the folder and remake it
        if os.path.exists(output_folder):
            shutil.rmtree(output_folder)

        os.makedirs(output_folder)

        # Create a list for the output files
        output_files = []

        with open(filename) as f:
            # First line contains the number and length of the sequences
            line = f.readline()
            line = line.split()

            number_of_sequences = int(line[0])
            length_of_sequences = int(line[1])

            # Initialize a pointer for the beginning of each window
            i = 0
            # Initialize a count for the total number of windows
            num_windows = 0

            window_size = min(length_of_sequences, window_size)

            # Determine the total number of windows needed
            while (i + window_size - 1 < length_of_sequences):
                i += step_size
                num_windows += 1

            # Create a file for each window and add it to the list
            for i in range(num_windows):
                output_files.append(open(output_folder + "/window" + str(i) + ".phylip", "w"))
                output_files[i].close()

            # Write the number and length of the sequences to each file
            for i in range(num_windows):
                file = open(output_files[i].name, "a")
                file.write(" " + str(number_of_sequences) + " ")
                file.write(str(window_size) + "\n")
                file.close()

            # Subsequent lines contain taxon and sequence separated by a space
            for i in range(number_of_sequences):
                line = f.readline()
                line = line.split()

                taxon = line[0]
                sequence = line[1]

                for j in range(num_windows):
                    l = j * step_size
                    file = open(output_files[j].name, "a")
                    file.write(taxon + " ")
                    window = ""
                    for k in range(window_size):
                        window += sequence[l + k]

                    # Writes file to folder
                    file.write(window + "\n")
                    file.close()

    def raxml_windows(self, numBootstraps, model, rooted=False, outgroup=None, window_directory='windows', output_directory='RAxML_Files'):
        """
        Runs RAxML on files in the directory containing files from
        window_splitter().

        Inputs:
        numBootstraps --- the number of bootstraps to use
        model --- the type of model to use in RAxML
        """

        topology_output_directory = "Topologies"

        # Delete the folder and remake it if it already exists
        if os.path.exists(output_directory):
            shutil.rmtree(output_directory)

        os.makedirs(output_directory)

        # Delete the folder and remake it if it already exists
        if os.path.exists(topology_output_directory):
            shutil.rmtree(topology_output_directory)

        os.makedirs(topology_output_directory)

        percent_complete = 0

        # Iterate over each folder in the given directory in numerical order
        for filename in natsorted(os.listdir(window_directory)):

            # If file is a phylip file run RAxML on it
            if filename.endswith(".phylip"):

                file_number = filename.replace("window", "")
                file_number = file_number.replace(".phylip", "")

                input_file = os.path.join(window_directory, filename)

                # Run RAxML
                # NOT custom raxml
                if not self.isCustomRaxmlCommand:
                    if self.bootstrap:
                        p = subprocess.Popen("raxmlHPC -f a -x12345 -p 12345 -# {2} -m {3} -s {0} -n {1}".format(input_file, file_number, numBootstraps, model), shell=True)
                    else:
                        p = subprocess.Popen("raxmlHPC -d -p 12345 -m {2} -s {0} -n {1}".format(input_file, file_number, model), shell=True)
                # custom raxml
                else:
                    p = subprocess.Popen(self.customRaxmlCommand + " -s {0} -n {1}".format(input_file, file_number), shell=True)

                # Wait until command line is finished running
                p.wait()

                # Regular expression for identifying floats
                float_pattern = "([+-]?\\d*\\.\\d+)(?![-+0-9\\.])"

                # Create a separate file with the topology of the best tree
                with open("RAxML_bestTree." + file_number) as f:
                    # Read newick string from file
                    topology = f.readline()

                    # Delete float branch lengths, ":" and "\n" from newick string
                    topology = ((re.sub(float_pattern, '', topology)).replace(":", "")).replace("\n", "")

                    # Otherwise write the topology newick string to a file
                    # else:
                    if platform == 'win32':
                        file = open(topology_output_directory + "\Topology_bestTree." + file_number, "w")
                        file.write(topology)
                        file.close()
                    elif platform == 'darwin':
                        file = open(topology_output_directory + "/Topology_bestTree." + file_number, "w")
                        file.write(topology)
                        file.close()

                if self.bootstrap:

                    # If rooting is desired root the appropriate files
                    if rooted:
                        self.rooter("RAxML_bestTree." + file_number, outgroup)
                        self.rooter("RAxML_bipartitions." + file_number, outgroup)
                        self.rooter("RAxML_bipartitionsBranchLabels." + file_number, outgroup)

                    if platform == "win32":
                        # Move RAxML output files into their own destination folder - Windows
                        os.rename("RAxML_bestTree." + file_number, output_directory + "\RAxML_bestTree." + file_number)
                        os.rename("RAxML_bipartitions." + file_number, output_directory + "\RAxML_bipartitions." + file_number)
                        os.rename("RAxML_bipartitionsBranchLabels." + file_number, output_directory + "\RAxML_bipartitionsBranchLabels." + file_number)
                        os.rename("RAxML_bootstrap." + file_number, output_directory + "\RAxML_bootstrap." + file_number)
                        os.rename("RAxML_info." + file_number, output_directory + "\RAxML_info." + file_number)
                        # os.rename("topology_bestTree." + file_number, topology_output_directory + "\Topology_bestTree." + file_number)

                    elif platform == "darwin":
                        # Move RAxML output files into their own destination folder - Mac
                        os.rename("RAxML_bestTree." + file_number, output_directory + "/RAxML_bestTree." + file_number)
                        os.rename("RAxML_bipartitions." + file_number, output_directory + "/RAxML_bipartitions." + file_number)
                        os.rename("RAxML_bipartitionsBranchLabels." + file_number, output_directory + "/RAxML_bipartitionsBranchLabels." + file_number)
                        os.rename("RAxML_bootstrap." + file_number, output_directory + "/RAxML_bootstrap." + file_number)
                        os.rename("RAxML_info." + file_number, output_directory + "/RAxML_info." + file_number)
                        # os.rename("topology_bestTree." + file_number, topology_output_directory + "/Topology_bestTree." + file_number)

                else:

                    # If rooting is desired root the appropriate files
                    if rooted:
                        self.rooter("RAxML_bestTree." + file_number, outgroup)
                        self.rooter("RAxML_result." + file_number, outgroup)

                    if platform == "win32":
                        # Move RAxML output files into their own destination folder - Windows
                        os.rename("RAxML_bestTree." + file_number, output_directory + "\RAxML_bestTree." + file_number)
                        os.rename("RAxML_log." + file_number, output_directory + "\RAxML_log." + file_number)
                        os.rename("RAxML_randomTree." + file_number, output_directory + "\RAxML_randomTree." + file_number)
                        os.rename("RAxML_result." + file_number, output_directory + "\RAxML_result." + file_number)
                        os.rename("RAxML_info." + file_number, output_directory + "\RAxML_info." + file_number)
                        # os.rename("topology_bestTree." + file_number, topology_output_directory + "\Topology_bestTree." + file_number)

                    elif platform == "darwin":
                        # Move RAxML output files into their own destination folder - Mac
                        os.rename("RAxML_bestTree." + file_number, output_directory + "/RAxML_bestTree." + file_number)
                        os.rename("RAxML_log." + file_number, output_directory + "/RAxML_log." + file_number)
                        os.rename("RAxML_randomTree." + file_number, output_directory + "/RAxML_randomTree." + file_number)
                        os.rename("RAxML_result." + file_number, output_directory + "/RAxML_result." + file_number)
                        os.rename("RAxML_info." + file_number, output_directory + "/RAxML_info." + file_number)
                        # os.rename("topology_bestTree." + file_number, topology_output_directory + "/Topology_bestTree." + file_number)

                percent_complete += 80 / len(os.listdir(window_directory))
                self.emit(QtCore.SIGNAL('RAX_PER'), percent_complete)

    def run(self):
        try:
            self.window_splitter(self.inputFilename, self.windowSize, self.windowOffset)
        except IOError:
            self.emit(QtCore.SIGNAL('INVALID_ALIGNMENT_FILE'), self.inputFilename)
            return

        self.raxml_windows(self.numBootstraps, self.model, rooted=self.rooted, outgroup=self.outGroup)
        self.emit(QtCore.SIGNAL('RAX_COMPLETE'), None)

        print 'Alignment:', self.inputFilename
        print 'Window Size:', self.windowSize
        print 'Window Offset:', self.windowOffset
        print '# Bootstraps:', self.numBootstraps class TopologyPlotter(QtCore.QThread):
    def __init__(self, parent=None):
    def topology_counter(self, rooted=False, outgroup=None):
    def top_freqs(self, num, topologies_to_counts):
    def top_topologies(self, num, topologies):
    def windows_to_newick(self, top_topologies_to_counts, unique_topologies_to_newicks, rooted=False, outgroup=None):
    def topology_colors(self, wins_to_tops, tops_list):
    def donut_colors(self, top_topologies, tops_to_colors):
    def topology_donut(self, labels, sizes, donut_colors):
    def topology_scatter(self, wins_to_tops, scatter_colors, ylist):
    def topology_colorizer(self, color_scheme, rooted=False, outgroup=False):
    def top_topology_visualization(self):
    def generateCircleGraph(self, file, windows_to_top_topologies, topologies_to_colors, window_size, window_offset, sites_to_informative):
    def run(self): class StatisticsCalculations(QtCore.QThread):
    def __init__(self, output_directory='RAxML_Files', parent=None):
    def newick_reformat(self, newick):
    def calculate_p_of_gt_given_st(self, species_tree, gene_tree):
    def calculate_windows_to_p_gtst(self, species_tree):
    def calculate_robinson_foulds(self, species_tree, gene_tree, weighted):
    def calculate_windows_to_rf(self, species_tree, weighted):
    def stat_scatter(self, stat_map, name, title, xlabel, ylabel):
    def figureBarPlot(self, data, name, title, labelHeights=False, legend=False, legendNames=(), xTicks=False, groupLabels=()):
    def barPlot(self, data, name, title, xLabel, yLabel, labelHeights=False, legend=False, legendNames=(), xTicks=False, groupLabels=()):
        def autoLabel(rects, ax):
    def groupedBarPlot(self, data, name, title, xLabel, yLabel, labelHeights=False, legend=False, legendNames=(), xTicks=False, groupLabels=()):
        def autoLabel(rects, ax):
    def calculate_d(self, alignment, window_size, window_offset, taxon1, taxon2, taxon3, taxon4):
    def run(self):
                P1, P2, P3, O = site[taxon1_idx], site[taxon2_idx], site[taxon3_idx], site[taxon4_idx]
                    ABBA = 1
                    BABA = 0
                    ABBA = 0
                    BABA = 1
                    ABBA = 0
                    BABA = 0
            P1, P2, P3, O = site[taxon1_idx], site[taxon2_idx], site[taxon3_idx], site[taxon4_idx]
                ABBA = 1
                BABA = 0
                ABBA = 0
                BABA = 1
                ABBA = 0
                BABA = 0 class FileConverter(QtCore.QThread):
    def __init__(self, parent=None):
    def fileConverter(self, input_file, input_type, output_type, output_file):
    def run(self): class InformativeSites(QtCore.QThread):
    def __init__(self, parent=None):
    def is_site_informative(self, site):
    def calculate_informativeness(self, window_directory, window_offset, percentage, alignment=False): class BootstrapContraction(QtCore.QThread):
    def __init__(self, parent=None):
    def contraction_threshold(self, tree_file, confidence_threshold):
    def internal_nodes_after_contraction(self, confidence_threshold):
    def double_line_graph_generator(self, list1, list2, xlabel, ylabel, name, confidence_threshold): class MsComparison(QtCore.QThread):
    def __init__(self, msToRax=True, output_directory='RAxML_Files', parent=None):
    def sites_to_newick_ms(self, input_file):
    def sites_to_newick_rax(self, rax_dir, window_size, window_offset):
    def rax_to_ms(self, sites_to_newick):
    def sitesToRobinsonFouldsDistance(self, sites_to_newick_1,  sites_to_newick_2):
    def run(self): class Plotter(QtCore.QThread):
    def __init__(self, parent=None):
    def topologyDonut(self, title, labels, sizes, donut_colors, subplotPosition=111):
    def topologyScatter(self, title, wins_to_tops, scatter_colors, y, subplotPosition=111):
    def sorted_scatter(self, lWindows, sigArray, title, xlab, ylab, subplotPosition=111):
    def stat_scatter(self, dataMap, title, xLabel, yLabel, subplotPosition=111):
    def barPlot(self, title, data, xLabel='', yLabel='', groupLabels=(), heightLabels=False, subplotPosition=111):
    def heatMap(self, title, mapping, subplotPosition=111):
    def treeImage(self, newick, rooted=False, outgroup=False):
    def topologyColorizer(self, title, newicksToColors, topologies_to_counts, rooted=False, outgroup=False):
    def doubleLineGraph(self, list1, list2, confidenceThreshold, xLabel='', yLabel=''):
    def nlineGraph(self, dataSet, title, xLabel='', yLabel='', subplotPosition=111, groupLabels1=()):
    def lineGraph(self, data, title, xLabel='', yLabel='', subplotPosition=111):
    def tmrca_graph(self, sites_to_newick_mappings, labels, topology_only=False, subplotPosition=111):
    def generateCircleGraph(self, file, windows_to_top_topologies, topologies_to_colors, window_size, window_offset, sites_to_informative):
    def run(self): class CalculateGeneralizedDStatisticClass(QtCore.QThread):
    def __init__(self, parent=None):
        super(CalculateGeneralizedDStatisticClass, self).__init__(parent)

    def calculate_generalized(self, alignments, species_tree=None, reticulations=None, outgroup=None, window_size=100000000000,
                          window_offset=100000000000, verbose=False, alpha=0.01, use_inv=False, useDir=False,
                 directory="", statistic=False, save=False,  f="DGenStatistic_", plot=False, meta=False, useAlreadyGeneratedStat=True):

        self.emit(QtCore.SIGNAL('GEN_D_10'))

        if(useAlreadyGeneratedStat == False): #generate a dgen stat
            # run the java jar lines goes here

            # FOR REFERENCE, THE ARGS AND JAVA COMMAND
            # String treeString = args[0];
            # String networkString = args[1];
            # String outGroupName = args[2];
            # String saveStatHere = args[3];
            # int numberOfRandomRuns = Integer.parseInt(args[4]);
            # GenerateDgenStatistic(treeString, networkString, outGroupName, saveStatHere, numberOfRandomRuns);

            # Get the global path name to the jar file
            dir_path = os.path.dirname(os.path.realpath(__file__))
            jarPath = os.path.join(dir_path, "DGEN2.jar")

            # Run PhyloNet dgen maker jar file
            numberRandomRuns = 100
            networkString = Create_Network_Helper(species_tree, reticulations, 0.9)
            #species tree and network string need 's to work properly
            species_tree = "'"+species_tree+"'"
            networkString = "'"+networkString+"'"
            jarRunOutput = subprocess.Popen("java -jar {0} {1} {2} {3} {4} {5}".format(jarPath, species_tree, networkString, outgroup, statistic, numberRandomRuns), stdout=subprocess.PIPE,
                                 shell=True)

            # Read output and convert to float
            #pgtst = float(p.stdout.readline())


        self.emit(QtCore.SIGNAL('GEN_D_50'))

        #and then always run the statistic on data (just doing it this way for now to save time. could be chagned later to be slightly more user friendly. but also all users should want to analyze data probably)
        #run the dstat. making temp variables just to keep clear on what is named what (cuz i am changing some things around without messing with some of the code rewriting)
        runInVerboseMode = use_inv
        saveResultsHere = f
        resultsString = run_saved_dgen(statistic, alignments, window_size=window_size, window_offset=window_offset, verbose=runInVerboseMode, alpha=alpha)

        #line here to save results string to file saveResultsHere (do i want to do this or just output to screen?
        # If users want to save the statistic and speed up future runs
        if len(saveResultsHere) > 0:
            num = 0
            file_name = saveResultsHere + ".txt"
            while os.path.exists(file_name):
                file_name = "DGenResults_{0}.txt".format(num)
                num += 1

            with open(file_name, "w") as text_file:
                #output_str = "Taxa: {0}\n".format(taxa)
                #text_file.write(output_str)
                #output_str = "Statistic: {0}\n".format(generate_statistic_string((increase_resized, decrease_resized)))
                #text_file.write(output_str)
                text_file.write(resultsString)
                text_file.close()

        #put a line to either print results or to save em to a file. printing to screen done here
        #self.emit(QtCore.SIGNAL('GEN_D_COMPLETE'))
        self.emit(QtCore.SIGNAL('GEN_D_100'))
        self.emit(QtCore.SIGNAL('DGEN2_FINISHED'), resultsString)

        debugHere = 0

        #run_saved_dgen(?,
        #               ['/Users/leo/rice/res/data/cichlid/alignment/cichlid6tax.phylip-sequential.txt'],
        #               verbose=True, plot='/Users/leo/rice/res/data/dgen/tmp/figC/plot_figCVerbose', meta='Dgen')

        # OLD WAY
        # alignments_to_d_resized, alignments_to_windows_to_d, standard_o, verbose_o = CalculateGeneralizedDStatistic.calculate_generalized\
        #     (alignments, species_tree, reticulations, outgroup, window_size, window_offset, verbose, alpha, use_inv,
        #                                                     useDir, directory, statistic, save, f, plot, meta)

        # self.emit(QtCore.SIGNAL("L_FINISHED"), alignments_to_d_resized, alignments_to_windows_to_d, standard_o, verbose_o)

    def run(self):
        """
            Starts PyQt Thread. Called with "start()".
        """
        # try:
        #     self.window_splitter(self.inputFilename, self.windowSize, self.windowOffset)
        # except IOError:
        #     self.emit(QtCore.SIGNAL('INVALID_ALIGNMENT_FILE'), self.inputFilename)
        #     return

        self.calculate_generalized(self.alignments,
                                   species_tree=self.species_tree,
                                   reticulations=self.r,
                                   outgroup=self.o,
                                   window_size=self.window_size,
                                   window_offset=self.window_offset,
                                   verbose=self.verbose,
                                   alpha=self.alpha,
                                   use_inv=self.use_inv,
                                   useDir=self.useDir,
                                   directory=self.directory,
                                   statistic=self.statistic,
                                   save=self.save,
                                   f=self.save_location,
                                   plot=self.plot,
                                   meta=self.meta,
                                   useAlreadyGeneratedStat=self.useAlreadyGeneratedStat)

        #self.emit(QtCore.SIGNAL('GEN_D_COMPLETE'), None) class RunSW(QtCore.QThread):
    def __init__(self, parent=None):
        super(RunSW, self).__init__(parent)

    def run_sw_jar(self, sequence_path, sequence_length, window_size=100000000000,
                          window_offset=100000000000):


        self.emit(QtCore.SIGNAL('SW_UPDATE'),
                  "Running Smooth Winds....")

        # run the java jar lines goes here

        # FOR REFERENCE, THE ARGS AND JAVA COMMAND
        # String seq path = args[0];
        # String seq length = args[1];
        # String window size = args[2];
        # String window offset = args[3];

        # Get the global path name to the jar file
        dir_path = os.path.dirname(os.path.realpath(__file__))
        jarPath = os.path.join(dir_path, "SmoothWinds.jar")

        # Run SW jar file

        #UNCOMMENT ME TO RUN JAR
        jarRunOutput = subprocess.Popen("java -jar {0} {1} {2} {3} {4}".format(jarPath, sequence_path, sequence_length, window_size, window_offset), stdout=subprocess.PIPE,
                             shell=True)

        # Read output and convert to float
        #pgtst = float(p.stdout.readline())
        #waitTilJarIsDoneRunning = p.stdout.readline()
        jarRunOutput.wait()


        self.emit(QtCore.SIGNAL('SW_UPDATE'), "Run Complete. Output stored in SmoothWinds folder created in the same directory as the fasta file.")

        debugHere = 0


    def run(self):
        """
            Starts PyQt Thread. Called with "start()".
        """
        # try:
        #     self.window_splitter(self.inputFilename, self.windowSize, self.windowOffset)
        # except IOError:
        #     self.emit(QtCore.SIGNAL('INVALID_ALIGNMENT_FILE'), self.inputFilename)
        #     return

        self.run_sw_jar(sequence_path=self.sequencePathText, sequence_length=self.sequenceLengthFloat, window_size=self.windowSizeFloat,window_offset=self.windowOffsetFloat)

        #self.run_sw_jar(sequence_path=self.sequence_path,
        #                   sequence_length=self.sequence_length,
        #                   window_size=self.window_size,
        #                   window_offset=self.window_offset)

        #self.emit(QtCore.SIGNAL('GEN_D_COMPLETE'), None)
import sip, sys, os, re, webbrowser
from PyQt4 import QtGui, QtCore
from functools import partial
from raxmlOutputWindows import allTreesWindow, donutPlotWindow, scatterPlotWindow, pgtstWindow, robinsonFouldsWindow, heatMapWindow, bootstrapContractionWindow, dStatisticWindow, msRobinsonFouldsWindow, msPercentMatchingWindow, msTMRCAWindow, windowsToInfSitesWindow, lStatisticWindow
from module import gui_layout as gui
from module import RAxMLOperations as ro
from module import topologyPlots as tp
from module import statisticCalculations as sc
from module import fileConverterController as fc
from module import informativeSites as infSites
from module import bootstrapContraction as bc
from module import msComparison as ms
from module import plotter as p
from module import CalculateGeneralizedDStatisticClass as gd
from module import RunSW as sw
        self.msFileUploadMasterVL.addLayout(HL)

        btn.clicked.connect(lambda: self.getFileName(entry))
        btn2.clicked.connect(lambda: self.removeFileEntry(HL, entry, btn, btn2))

    def removeFileEntry(self, HL, entry, btn, btn2):
        HL.deleteLater()
        entry.deleteLater()
        btn.deleteLater()
        btn2.deleteLater()
        if entry.objectName() in self.additionalFileEntryNames:
            self.additionalFileEntryNames.remove(entry.objectName())
        if entry in self.additionalAlignmentEntries:
            self.additionalAlignmentEntries.remove(entry)
            # self.resize(self.width(), self.height() - 30)

    # **************************** CONVERTER PAGE ****************************#

    def convertFile(self):
        try:
            self.fileToBeConverted = self.checkEntryPopulated(self.fileConverterEntry, errorTitle='No Input File Selected', errorMessage='Please choose an input file.')
            self.convertedFileDirectory = self.checkEntryPopulated(self.outputFileConverterEntry, errorTitle='No Output File Selected', errorMessage='Please choose an output file.')
        except ValueError, (ErrorTitle, ErrorMessage, ErrorDescription):
            self.message(ErrorTitle, ErrorMessage, ErrorDescription)
            return

        self.convertedFileName = self.convertedFileDirectory + '/convertedFile.' + self.outputFormatComboBox.currentText().lower() + '.txt'

        self.fileConverter.inputFileName = self.fileToBeConverted
        self.fileConverter.outputFileName = self.convertedFileName
        self.fileConverter.inputFormat = self.inputFormatComboBox.currentText().lower()
        self.fileConverter.outputFormat = self.outputFormatComboBox.currentText().lower()
        self.fileConverter.start()

    # **************************** RAXML PAGE ****************************#

    def generateSpeciesTree(self):
        try:
            # get values from gui -- ensure that no fields are blank
            self.raxmlOperations.inputFilename = self.checkEntryPopulated(self.inputFileEntry, errorTitle='Missing Alignment', errorMessage='Please select an alignment.')
            self.raxmlOperations.windowSize = self.checkEntryInRange(self.windowSizeEntry, min=0, inclusive=False, errorTitle='Invalid Window Size', errorMessage='Window size needs to be a positive integer.')
            self.raxmlOperations.windowOffset = self.checkEntryInRange(self.windowOffsetEntry, min=0, inclusive=False, errorTitle='Invalid Window Offset', errorMessage='Window offset needs to be a positive integer.')
            self.raxmlOperations.speciesTreeRooted = self.checkboxSpeciesTreeRooted.isChecked()
            self.raxmlOperations.speciesTreeOutGroup = self.speciesTreeComboBox.currentText()
            self.raxmlOperations.speciesTreeUseCustomRax = self.checkboxSpeciesTreeUseCustomRax.isChecked()

            # if using custom rax -- make sure that the user doesn't use the -s or -n flags
            self.raxmlOperations.speciesTreeCustomRaxmlCommand = ''
            if self.checkboxSpeciesTreeUseCustomRax.isChecked():
                self.raxmlOperations.speciesTreeCustomRaxmlCommand = self.checkEntryPopulated(self.speciesTreeRaxmlCommandEntry, errorTitle='No RAxML Command', errorMessage='Please enter a custom raxml command or uncheck the box.')
                if re.search('([\-][n])|([\-][s])', self.speciesTreeRaxmlCommandEntry.text()):
                    raise ValueError('Invalid RAxML Command', 'Please do not specify the -s or -n flags.', 'the -s and -n flags will be handled internally based on the alignment you input.')

        except ValueError, (ErrorTitle, ErrorMessage, ErrorDescription):
            self.message(str(ErrorTitle), str(ErrorMessage), str(ErrorDescription))
            return

        self.raxmlOperations.raxml_species_tree(self.raxmlOperations.inputFilename, rooted=self.raxmlOperations.speciesTreeRooted, outgroup=self.raxmlOperations.speciesTreeOutGroup, customRax=self.raxmlOperations.speciesTreeUseCustomRax, customRaxCommand=self.raxmlOperations.speciesTreeCustomRaxmlCommand)

    def requestedFigures(self):
        requestedFigures = set()

        if self.checkboxAllTrees.isChecked():
            requestedFigures.add('Top Topologies Tree Visualization')
        if self.checkboxScatterPlot.isChecked():
            requestedFigures.add('Windows to Top Topologies Scatter Plot')
        if self.checkboxDonutPlot.isChecked():
            requestedFigures.add('Top Topology Frequency Donut Plot')
        if self.checkboxWindowsToInfSites.isChecked():
            requestedFigures.add('Windows to Informative Sites Line Graph')
        if self.checkboxHeatMap.isChecked():
            requestedFigures.add('Informative Sites Heat Map')
        if self.checkboxRobinsonFoulds.isChecked():
            requestedFigures.add('Robinson Foulds')
        if self.checkboxPGTST.isChecked():
            requestedFigures.add('p(GT | ST))')

        return requestedFigures

    def generateHeatmap(self):
        self.updatedDisplayWindows()

    def generateFigures(self):
        if self.runComplete:
            if self.raxmlInputErrorHandling():
                self.figuresToBeRegenerated = self.prevGeneratedFigures.intersection(self.requestedFigures())
                if len(self.figuresToBeRegenerated) > 0:
                    # execute window
                    regen = self.question("Regenerate Figures?", "You have selected figures which have previously been generated. All selected figures will be generated. Are you sure you want to proceed?")

                    # if the user selected the 'ok' button
                    if regen == QtGui.QMessageBox.Yes:
                        # start raxml operations thread
                        self.updatedDisplayWindows()
                        # if raxml hasn't been run before just run it
                else:
                    self.updatedDisplayWindows()

    def updatedDisplayWindows(self):
        # run commands that are shared by all functions
        if self.getNumberChecked() > 0:
            num = self.topTopologies
            topologies_to_counts, unique_topologies_to_newicks = self.topologyPlotter.topology_counter(rooted=self.rooted, outgroup=self.outgroupComboBox.currentText())
            self.numberOfUniqueTopologiesLabel.setText(str(len(topologies_to_counts)))
            if num > len(topologies_to_counts):
                num = len(topologies_to_counts)
            self.topologyPlotter.num = num
            list_of_top_counts, labels, sizes = self.topologyPlotter.top_freqs(num, topologies_to_counts)
            top_topologies_to_counts = self.topologyPlotter.top_topologies(num, topologies_to_counts)
            windows_to_top_topologies, top_topologies_list = self.topologyPlotter.windows_to_newick(top_topologies_to_counts, unique_topologies_to_newicks, rooted=self.rooted, outgroup=self.outgroupComboBox.currentText())  # all trees, scatter, circle, donut
            topologies_to_colors, scatter_colors, ylist = self.topologyPlotter.topology_colors(windows_to_top_topologies, top_topologies_list)  # scatter, circle, (donut?)

        # generate robinson foulds and pgtst graphs
        if self.checkboxRobinsonFoulds.isChecked():
            self.prevGeneratedFigures.add('Robinson Foulds')
            if self.checkboxWeighted.isChecked():
                windows_to_w_rf, windows_to_uw_rf = self.statisticsCalculations.calculate_windows_to_rf(self.speciesTree, self.checkboxWeighted.isChecked())
                self.robinsonFouldsWindow = robinsonFouldsWindow.RobinsonFouldsWindow('Weighted Robinson Foulds Distance', windows_to_w_rf, 'Unweighted Robinson Foulds Distance', windows_to_uw_rf)
            else:
                windows_to_uw_rf = self.statisticsCalculations.calculate_windows_to_rf(self.speciesTree, self.checkboxWeighted.isChecked())

                self.robinsonFouldsWindow = robinsonFouldsWindow.RobinsonFouldsWindow('Unweighted Robinson Foulds Distance', windows_to_uw_rf)