Exemplo n.º 1
0
class PooWindow(QtGui.QMainWindow):
    def __init__(self):
        super(PooWindow, self).__init__()
        self.initVars()
        self.initUI()
        self.initConnections()

    def initVars(self):
        """Initialises variables by reading from config files."""
        self.var = {}
        self.loadConfig()
        self.loadRobots()
        self.loadMarkerData()
        self.loadMarkerNotes()
        self.loadColours()
        self.loadValidated()

    def initUI(self):
        """Sets up the GUI."""
        self.setWindowTitle("Poo")
        self.menubar = PooMenuBar()
        self.setMenuBar(self.menubar)
        self.statusBar()
        self.tabs = PooTabs()
        self.setCentralWidget(self.tabs)
        self.showMaximized()

    def initConnections(self):
        """Initialises connections."""
        self.menubar.testAction.triggered.connect(self.test)

        self.menubar.clearTableAction.triggered.connect(self.clearTable)
        self.menubar.openAction.triggered.connect(self.openDialog)
        self.menubar.saveAction.triggered.connect(self.saveDialog)
        self.menubar.setProjectNameAction.triggered.connect(self.setProjectName)
        self.menubar.reloadConfigAction.triggered.connect(self.loadConfig)
        self.menubar.loadMarkerDataAction.triggered.connect(self.loadMarkerData)
        self.menubar.loadMarkerNotesAction.triggered.connect(self.loadMarkerNotes)
        self.menubar.loadColoursAction.triggered.connect(self.loadColours)
        self.menubar.brassicaWizardAction.triggered.connect(self.brassicaWizard)
        self.menubar.ryegrassWizardAction.triggered.connect(self.ryegrassWizard)
        self.menubar.kiwifruitWizardAction.triggered.connect(self.kiwifruitWizard)
        self.menubar.appleWizardAction.triggered.connect(self.appleWizard)
        self.menubar.exitAction.triggered.connect(self.close)

        self.menubar.createSamplesAction.triggered.connect(self.createSamples)
        self.menubar.createPlatesAction.triggered.connect(self.onCreatePlates)
        self.menubar.createSamplesFromKeaAction.triggered.connect(self.createSamplesFromKea)
        self.menubar.createSamplesFromKeaPopColumnsAction.triggered.connect(self.createSamplesFromKeaPopColumns)
        self.menubar.createSamplesFromEbridaAction.triggered.connect(self.createSamplesFromEbrida)
        self.menubar.createSamplesFromEbridaNoKeaAction.triggered.connect(self.createSamplesFromEbridaNoKea)
        self.menubar.importKeaSampleBatchAction.triggered.connect(self.importKeaSampleBatch)
        self.menubar.importEbridaSampleBatchAction.triggered.connect(self.importEbridaSampleBatch)
        self.menubar.importEbridaSampleBatchNoKeaAction.triggered.connect(self.importEbridaSampleBatchNoKea)
        self.menubar.importPlatesRecordsSpreadsheetAction.triggered.connect(self.importPlatesRecordsSpreadsheet)
        self.menubar.setCropAction.triggered.connect(self.setCrop)
        self.menubar.setPopulationToAllAction.triggered.connect(self.setPopulationToAll)
        self.menubar.setPopulationFromPlateAction.triggered.connect(self.setPopulationFromPlate)
        self.menubar.setPopulationFromKeaAction.triggered.connect(self.setPopulationFromKea)

        self.menubar.addScreenAction.triggered.connect(self.addScreen)
        self.menubar.renameScreenAction.triggered.connect(self.renameScreen)
        self.menubar.setMarkerAction.triggered.connect(self.setMarker)
        self.menubar.handLoadPlatesAction.triggered.connect(self.handLoadPlates)
        self.menubar.robotLoadPlatesAction.triggered.connect(self.robotLoadPlates)
        self.menubar.importLCPlatesAction.triggered.connect(self.importLCPlates)
        self.menubar.importLCExperimentsAction.triggered.connect(self.importLCExperiments)
        self.menubar.importABIExperimentsAction.triggered.connect(self.importABIExperiments)
        self.menubar.cherryPickNURobotAction.triggered.connect(self.cherryPickNURobot)
        self.menubar.cherryPickNUCRobotAction.triggered.connect(self.cherryPickNUCRobot)
        self.menubar.cherryPickNUHandAction.triggered.connect(self.cherryPickNUHand)
        self.menubar.reinsertNUPlatesAction.triggered.connect(self.reinsertNUPlates)
        self.menubar.reinsertNUExperimentsAction.triggered.connect(self.reinsertNUExperiments)
        self.menubar.negativiseUnknownsAction.triggered.connect(self.negativiseUnknowns)
        self.menubar.negativiseNonExistsAction.triggered.connect(self.negativiseNonExists)
        self.menubar.editCallsAction.triggered.connect(self.editCalls)
        self.menubar.addResultGroupAction.triggered.connect(self.addResultGroup)
        self.menubar.enterExperimentDatesAction.triggered.connect(self.enterExperimentDates)
        self.menubar.viewPlateStatsAction.triggered.connect(self.viewPlateStats)
        self.menubar.viewPopulationStatsAction.triggered.connect(self.viewPopulationStats)
        self.menubar.setIncludeAllAction.triggered.connect(self.setIncludeAll)
        self.menubar.setIncludeNoneAction.triggered.connect(self.setIncludeNone)
        self.menubar.setIncludeByResultAction.triggered.connect(self.setIncludeByResult)
        self.menubar.setIncludeByGroupAction.triggered.connect(self.setIncludeByGroup)
        self.menubar.setIncludeByPlateAction.triggered.connect(self.setIncludeByPlate)
        self.menubar.setIncludeByPopulationAction.triggered.connect(self.setIncludeByPopulation)
        self.menubar.setIncludeByPopulationAndGroupAction.triggered.connect(self.setIncludeByPopulationAndGroup)
        self.menubar.setIncludeForTwoOfEachResultByPopAction.triggered.connect(self.setIncludeForTwoOfEachResultByPop)
        self.menubar.setExcludeNoSampleAction.triggered.connect(self.setExcludeNoSample)

        self.menubar.outputAllAction.triggered.connect(self.outputAll)
        self.menubar.outputNoneAction.triggered.connect(self.outputNone)
        self.menubar.setOutputByPlateAction.triggered.connect(self.setOutputByPlate)
        self.menubar.setOutputByPopulationAction.triggered.connect(self.setOutputByPopulation)
        self.menubar.outputExcludeNoResultAction.triggered.connect(self.outputExcludeNoResult)
        self.menubar.outputExcludeNoSampleAction.triggered.connect(self.outputExcludeNoSample)
        self.menubar.outputExcludeNegativeFailGrindsAction.triggered.connect(self.outputExcludeNegativeFailGrinds)
        self.menubar.outputEbridaHarvestSheetsAction.triggered.connect(self.outputEbridaHarvestSheets)
        self.menubar.outputColouredPlatesAction.triggered.connect(self.outputColouredPlates)
        self.menubar.outputColouredPlatesKeaAction.triggered.connect(self.outputColouredPlatesKea)
        self.menubar.outputForKeaProcessAction.triggered.connect(self.outputForKeaProcess)
        self.menubar.outputForEbridaAction.triggered.connect(self.outputForEbrida)
        self.menubar.outputCustomPlatesAction.triggered.connect(self.outputCustomPlates)
        self.menubar.outputColouredPlatesAllAction.triggered.connect(self.outputColouredPlatesAll)
        self.menubar.outputColouredPlatesKeaAllAction.triggered.connect(self.outputColouredPlatesKeaAll)
        self.menubar.outputCustomPlatesAllAction.triggered.connect(self.outputCustomPlatesAll)

        self.tabs.tabCloseRequested.connect(self.tabs.removeTab)

    ########################################################################
    ##	Private Methods
    ########################################################################
    def __setProjectName(self, name=None):
        if name:
            self.var["project"] = name
        else:
            self.var["project"] = self.tabs.makeProjectName()

    def __getPlatesRecords(self, index):
        """Opens the Slipstream Plates Records spreadsheet and adds information
		to the sampleTable, keaTable, and ebridaTable."""
        title = "Locate Plates Records spreadsheet..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        platesRecords = PlatesRecordsTable(fileName)
        plateNames = platesRecords.getPlateNames()
        plateNames = plateNames.set_index(index)
        nonExists = platesRecords.getFails("Exists")
        badGrinds = platesRecords.getFails("Grind")
        self.tabs.updateSourceTables(index, plateNames)
        self.tabs.sampleTable.addFails(nonExists)
        self.tabs.sampleTable.addFails(badGrinds)

    ########################################################################
    ##	File Menu Actions
    ########################################################################
    def test(self):
        """Runs whatever commands I need to setup a test."""
        ## Open
        fileName = "/home/mcv/Genotyping Project Records/Testing/16-0978-1004-test.xls"
        excelFile = pd.ExcelFile(fileName)
        self.clearTable()
        try:
            project = excelFile.parse("Project")
            newVars = project.set_index("variable")["value"]
            self.var.update(newVars)
            self.tabs.openSaved(excelFile)
        except:
            pass  # Error message?

            # self.tabs.getAllResultsTable()

            ## Choose screen
        self.tabs.setCurrentIndex(2)
        # self.cherryPickNUCRobot()

        self.setIncludeForTwoOfEachResultByPop()

        ## Output

    # 		fileName					= '/home/mcv/Genotyping Project Records/Testing/16-0684-0685-sheets-all'
    # 		if fileName != '':
    # 			results					= self.tabs.getAllResultsTable()
    # 			results					= ResultsTable(results)
    # 			labels					= results.getLabels()
    # 			labels,ok				= GetPlateLabels.run(labels)
    # 			if ok:
    # 				results.setLabels(labels)
    # 				workBook			= Workbook()
    # 				addAllResultsTable(workBook,results,True,self.markerdata,self.colours)
    # 				addMarkerSheets(workBook,results,True,self.markerdata,self.markernotes,self.colours,self.var['images'],self.validated)
    # 				addPlateSheets(workBook,results,True,self.markerdata,self.colours)
    # 				workBook.save(fileName+'.xlsx')

    ########################################################################
    def clearTable(self):
        """Destroys all data and starts again."""
        del self.tabs
        self.initVars()
        self.tabs = PooTabs()
        self.setCentralWidget(self.tabs)

    def openDialog(self):
        """Opens a project saved as an .xls file."""
        title = "Open a saved project file..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        excelFile = pd.ExcelFile(fileName)
        self.clearTable()
        try:
            project = excelFile.parse("Project")
            newVars = project.set_index("variable")["value"]
            self.var.update(newVars)
            self.tabs.openSaved(excelFile)
        except:
            pass  # Error message?

    def saveDialog(self):
        """Saves the project as an .xls file."""
        title = "Save project as..."
        projectName = self.var.get("project", self.tabs.makeProjectName())
        defaultName = os.path.join(self.var["path"], projectName)
        fileName, f = QtGui.QFileDialog.getSaveFileName(self, title, defaultName)
        fileName = fileName.split(".")[0]
        if fileName != "":
            writer = pd.ExcelWriter(fileName + ".xls")
            variables = pd.DataFrame(self.var.items(), columns=["variable", "value"])
            variables.to_excel(writer, "Project", index=False)
            writer = self.tabs.toWriter(writer)
            writer.save()

    ########################################################################
    def setProjectName(self):
        """Opens a dialog, gets a project name, and stores it in self.var."""
        project, ok = GetProjectName.run()
        if ok:
            self.__setProjectName(project)

    def loadConfig(self):
        """Opens the config file (config.txt in working directory) and
		updates self.var dictionary."""
        with open("config/config.txt", "r") as conf:
            for line in conf.readlines():
                if line.strip() == "" or line[0] == "#":
                    pass
                else:
                    line = line.split("=")
                    var = line[0].strip()
                    val = line[1].strip()
                    self.var[var] = val

    def loadMarkerData(self):
        """Reads the markers file (stored in self.var) and creates a marker
		table."""
        fileName = self.var["markerdata"]
        coloursName = self.var["colours"]
        self.markerdata = MarkerTable(fileName)

    def loadMarkerNotes(self):
        """Reads the markernotes file (stored in self.var) and creates a
		table of marker notes."""
        fileName = self.var["markernotes"]
        self.markernotes = MarkerNotesTable(fileName)

    def loadRobots(self):
        """Reads the robots file (stored in self.var) and creates a robot
		well conversion table."""
        fileName = self.var["robots"]
        self.robots = RobotTable(fileName)

    def loadColours(self):
        """Reads the colours file (stored in self.var) and creates a colour
		table."""
        fileName = self.var["colours"]
        self.colours = pd.read_table(fileName)
        self.colours = self.colours.set_index("Colour")

    def loadValidated(self):
        """Reads the validated file (stored in self.var) and creates a
		validated table."""
        fileName = self.var["validated"]
        self.validated = ValidatedTable(fileName)

    ########################################################################
    def brassicaWizard(self):
        """Imports and sets variables for a Brassica project."""
        self.createPlates()
        self.var["crop"] = "Brassica"
        self.setPopulationToAll()
        self.addScreen()
        self.tabs.setCurrentIndex(1)
        self.importLCPlates()
        self.addResultGroup()

    def ryegrassWizard(self):
        """Imports and sets variables for a Ryegrass project."""
        self.createPlates()
        self.var["crop"] = "Ryegrass"
        self.setPopulationToAll()
        self.addScreen()
        self.tabs.setCurrentIndex(1)
        self.importLCPlates()
        self.addResultGroup()

    def kiwifruitWizard(self):
        """Imports and sets variables for a Kiwifruit project."""
        self.createSamplesFromEbrida()
        self.var["crop"] = "Kiwifruit"
        self.addScreen()
        self.tabs.setCurrentIndex(3)
        self.importLCPlates()
        self.addResultGroup()

    def appleWizard(self):
        """Imports and sets variables for an Apple project."""
        self.createSamplesFromKea()
        self.var["crop"] = "Apple"
        self.addScreen()
        self.tabs.setCurrentIndex(2)
        self.importLCPlates()
        self.addResultGroup()

    ########################################################################
    ##	Project Menu Actions
    ########################################################################
    def onCreatePlates(self):
        """Function called when 'Create Plates is chosen from the menu."""
        self.createPlates()
        self.setCrop()

    def createPlates(self):
        """Creates a set of consecutively numbered full plates."""
        samples, ok = CreatePlates.run()
        samples = SampleBatchTable(samples)
        if ok:
            self.tabs.appendSamples(samples.table)
            self.__getPlatesRecords("Plate ID")

    def createSamples(self):
        """Creates a given number of samples with no names or plant names."""
        samples, ok = CreateSamples.run()
        samples = SampleBatchTable(samples)
        if ok:
            self.tabs.appendSamples(samples.table)
            self.__getPlatesRecords("Plate ID")
            self.setCrop()

    def createSamplesFromKea(self):
        """Opens a Kea Sample Batch Excel file and the Slipstream Plates
		Records spreadsheet and adds entries to the	sampleTable and keaTable."""
        title = "Open Kea Sample Batch file..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        keaSampleBatchName, ok = GetSampleBatchName.run(fileName)
        if ok:
            keaSampleBatch = KeaSampleBatchTable(fileName, keaSampleBatchName)
            self.tabs.addKeaTable()
            self.tabs.appendSamples(keaSampleBatch.table)
            self.__getPlatesRecords("Plate Kea")
            self.setCrop()

    def createSamplesFromKeaPopColumns(self):
        """Opens a Kea Sample Batch Excel file with Population as a column
		and the Slipstream Plates Records spreadsheet and adds entries to
		the	sampleTable and keaTable."""
        title = "Open Kea Sample Batch file..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        keaSampleBatchName, ok = GetSampleBatchName.run(fileName)
        if ok:
            keaSampleBatch = KeaSampleBatchPopColumnsTable(fileName, keaSampleBatchName)
            self.tabs.addKeaTable()
            self.tabs.appendSamples(keaSampleBatch.table)
            self.__getPlatesRecords("Plate Kea")
            self.setCrop()

    def createSamplesFromEbrida(self):
        """Opens an Ebrida File, a Kea Sample Batch file, and the Slipstream
		Plates Records Spreadsheet and adds entries to the sampleTable,
		keaTable, and ebridaTable."""
        title = "Open Ebrida Sample batch file..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        ebridaSampleBatch = EbridaSampleBatchTable(fileName)
        title = "Open Kea Sample Batch file..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        sampleBatchName, ok = GetSampleBatchName.run(fileName)
        if ok:
            keaSampleBatch = KeaSampleBatchTable(fileName, sampleBatchName)
            sampleBatch = KeaEbridaSampleBatchTable(keaSampleBatch, ebridaSampleBatch)
            self.tabs.addKeaTable()
            self.tabs.addEbridaTable()
            self.tabs.appendSamples(sampleBatch.table)
            self.__getPlatesRecords("Plate Kea")
            self.setCrop()

    def createSamplesFromEbridaNoKea(self):
        """Opens an Ebrida File and the Slipstream Plates Records 
		Spreadsheet and adds entries to the sampleTable and ebridaTable.
		Created for when the Kea Create Samples from Ebrida function
		wasn't working."""
        title = "Open Ebrida Sample batch file..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        ebridaSampleBatch = EbridaSampleBatchTable(fileName)
        plates, ok = GetPlatesList.run()
        if ok:
            samples, ok = GetNonSamples.run(plates)
            if ok:
                ebridaSampleBatch.addPlateAndWell(samples)
                self.tabs.addEbridaTable()
                self.tabs.appendSamples(ebridaSampleBatch.table)
                self.__getPlatesRecords("Plate ID")
                self.setCrop()

    ########################################################################
    def importKeaSampleBatch(self):
        """Opens a Kea Sample Batch file and updates the Kea table with
		the information therein. A Kea table is created if one does not
		already exist."""
        title = "Open Kea Sample Batch file..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        keaSampleBatchName, ok = GetSampleBatchName.run(fileName)
        if ok:
            keaData = KeaSampleBatchTable(fileName, keaSampleBatchName)
            self.tabs.updateKeaData(keaData.table)

    def importEbridaSampleBatch(self):
        """Opens an Ebrida File and updates the Ebrida table with the
		information therein. An Ebrida table is created if one does not
		already exist."""
        if self.tabs.keaTable:
            title = "Open Ebrida Sample Batch file..."
            fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
            ebridaData = EbridaSampleBatchTable(fileName)
            self.tabs.updateEbridaData(ebridaData)
        else:
            dialog = QtGui.QMessageBox.information(
                self, message["getKeaFirst"][0], message["getKeaFirst"][1], QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok
            )

    def importEbridaSampleBatchNoKea(self):
        """Opens an Ebrida File and updates the Ebrida table with the
		information therein. An Ebrida table is created if one does not
		already exist. This is for Ebrida data with no associated Kea data."""
        title = "Open Ebrida Sample Batch file..."
        fileName, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        ebridaData = EbridaSampleBatchTable(fileName)
        ebridaData.createPlateNameColumn()
        missingSamplesPerPlate = ebridaData.getMissingSamplesPerPlate()
        samples, ok = GetEbridaSamples.run(missingSamplesPerPlate)
        ebridaData.addWells(samples)
        self.tabs.updateEbridaDataNoKea(ebridaData)

    def importPlatesRecordsSpreadsheet(self):
        """Opens the Slipstream Plates Records spreadsheet and updates
		the Sample table, the Kea table, and the Ebrida table with the
		information therein, if they exist."""
        self.__getPlatesRecords("Plate ID")

    ########################################################################
    def setCrop(self):
        """Sets the crop for the project, which determines which markers
		are available."""
        crops = self.markerdata.getCropsList()
        crop, ok = SetCrop.run(crops)
        if ok:
            self.var["crop"] = crop

    ########################################################################
    def setPopulationToAll(self):
        """Sets the Population column for the project to All."""
        self.tabs.setPopulation("All")

    def setPopulationFromPlate(self):
        """Sets the Population column for the project to Plate ID."""
        self.tabs.setPopulation("Plate ID")

    def setPopulationFromKea(self):
        """Sets the Population column for the project to Kea population."""
        self.tabs.setPopulation("Kea")

    ########################################################################
    ##	Screen Menu Actions
    ########################################################################
    def addScreen(self):
        """Takes the Included samples from the current tab and creates a
		new Screen tab."""
        markers = self.markerdata.getMarkerListForCrop(self.var["crop"])
        plateNames, includeAll, oldPlates, newMarker, controls, ok = NewScreen.run(markers)
        if ok:
            self.tabs.addScreen(plateNames, includeAll, oldPlates, newMarker, controls)

    def renameScreen(self):
        """Renames the current round of screening to the value entered in
		the dialog."""
        screen, ok = RenameScreen.run()
        if ok:
            self.tabs.renameScreen(screen)

    def setMarker(self):
        """Sets the marker for the currently active round of screening."""
        markers = self.markerdata.getMarkerListForCrop(self.var["crop"])
        marker, ok = SetMarker.run(markers)
        if ok:
            self.tabs.setCurrentMarker(marker)

    ########################################################################
    def handLoadPlates(self):
        """Generates Excel sheets containing cherrypicking mappings for
		setting up the current round of screening."""
        title = "Hand cherrypick file..."
        fileName, f = QtGui.QFileDialog.getSaveFileName(self, title)
        fileName = fileName.split(".")[0] + ".xls"
        samples = self.tabs.getSamplesForLoading()
        CherryTable.forHand(samples, fileName)

    def robotLoadPlates(self):
        """Generates Biomek FX readable .csv files containing cherrypicking
		mappings for setting up the current round of screening."""
        title = "Choose folder for output..."
        directory = QtGui.QFileDialog.getExistingDirectory(self, title, self.var["path"])
        samples = self.tabs.getSamplesForLoading()
        CherryTable.forRobot(samples, directory)

    ########################################################################
    def importLCPlates(self):
        """Imports Lightcyler generated .txt TSV files containing HRM or
		Taqman results for the round of screening on the active tab. Each
		file should contain one plate."""
        title = "Import LC plate file(s)..."
        filter_mask = "Lightcycler text files (*.txt)"
        lightFileNames, f = QtGui.QFileDialog.getOpenFileNames(self, title, self.var["path"], filter_mask)
        fileDataLists, ok = ImportLCPlates.run(lightFileNames, self.robots)
        if ok:
            lc = LCTable.fromFDL(fileDataLists, self.robots)
            self.tabs.importLC(lc)

    def importLCExperiments(self):
        """Imports Lightcycler generated .txt TSV files containing HRM
		results for the round of screening on the active tab. Each file
		should contain one experiment."""
        title = "Import LC experiment file(s)..."
        filter_mask = "Lightcycler text files (*.txt)"
        lightFileNames, f = QtGui.QFileDialog.getOpenFileNames(self, title, self.var["path"], filter_mask)
        fileDataLists, ok = ImportLCExperiments.run(lightFileNames, self.robots.getRobotList())
        if ok:
            lc = LCTable.fromEDL(fileDataLists, self.robots)
            self.tabs.importLC(lc)

    def importABIExperiments(self):
        """Imports ABI generated .XLS text files containing results from
		the round of screening on the active tab. Each file should contain
		one experiment."""
        title = "Import ABI bin table file(s)..."
        filter_mask = "ABI text files (*.XLS)"
        ABIFileNames, f = QtGui.QFileDialog.getOpenFileNames(self, title, self.var["path"], filter_mask)
        fileDataLists, ok = ImportABIExperiments.run(ABIFileNames)
        if ok:
            abi = ABITable.fromFDL(fileDataLists)
            self.tabs.importLC(abi)

    ########################################################################
    def cherryPickNURobot(self):
        """Cherrypicks the Negatives and Unknowns and creates robot files."""
        title = "Choose folder for output..."
        directory = QtGui.QFileDialog.getExistingDirectory(self, title, self.var["path"])
        controls, ok = SetControls.run(4)
        if ok:
            samples = self.tabs.getNegativeUnknowns(controls)
            CherryTable.forRobot(samples, directory)

    def cherryPickNUCRobot(self):
        """Cherrypicks the Negatives, Unknowns, and contaminants, and creates
		robot loading files."""
        title = "Choose folder for output..."
        directory = QtGui.QFileDialog.getExistingDirectory(self, title, self.var["path"])
        contaminants = self.tabs.getPotentialContaminants()
        contaminants, ok = ChooseContaminants.run(contaminants)
        if ok:
            controls, ok = SetControls.run(4)
            if ok:
                samples = self.tabs.getNegativeUnknownContaminants(controls, contaminants)
                CherryTable.forRobot(samples, directory)

    def cherryPickNUHand(self):
        """Cherrypicks the Negatives and Unknowns and creates hand files."""
        title = "Hand cherrypick N/U file..."
        fileName, f = QtGui.QFileDialog.getSaveFileName(self, title)
        fileName = fileName.split(".")[0] + ".xls"
        controls, ok = SetControls.run(4)
        if ok:
            samples = self.tabs.getNegativesUnknowns()
            CherryTable.forHand(samples, fileName)

    def reinsertNUPlates(self):
        """Inserts results for rerun Negatives and Unknowns using the
		generated cherrypicking .xls file and the LC .txt plate files."""
        title = "Choose cherrypicking file..."
        cpFile, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        title = "Choose lightcycler files..."
        filter_mask = "Lightcycler text files (*.txt)"
        lightFileNames, f = QtGui.QFileDialog.getOpenFileNames(self, title, self.var["path"], filter_mask)
        fileDataLists, ok = ImportLCPlates.run(lightFileNames, self.robots)
        if ok:
            lc = LCTable.fromFDLCPFile(fileDataLists, self.robots, cpFile)
            self.tabs.importLC(lc)

    def reinsertNUExperiments(self):
        """Inserts results for rerun Negatives and Unknowns using the
		generated cherrypicking .xls file and the LC .txt experiment files."""
        title = "Choose cherrypicking file..."
        cpFile, f = QtGui.QFileDialog.getOpenFileName(self, title, self.var["path"])
        title = "Choose lightcycler files..."
        filter_mask = "Lightcycler text files (*.txt)"
        lightFileNames, f = QtGui.QFileDialog.getOpenFileNames(self, title, self.var["path"], filter_mask)
        fileDataLists, ok = ImportLCExperiments.run(lightFileNames, self.robots.getRobotList())
        if ok:
            lc = LCTable.fromEDLCPFile(fileDataLists, self.robots, cpFile)
            self.tabs.importLC(lc)

    ########################################################################
    def negativiseUnknowns(self):
        """Sets all Unknown results in the Calls menu to Negative."""
        calls = {"Unknown": "Negative"}
        self.tabs.replace("Call", calls)

    def negativiseNonExists(self):
        """Sets all Non-existing samples in the Samples table to Negative
		for the current round of screening."""
        nonExists = self.tabs.getNonExists()
        nonExists["Result"] = "Negative"
        nonExists["Group"] = "Negative"
        self.tabs.currentWidget().update(["Plate ID", "Well"], nonExists)

    def editCalls(self):
        """Opens a dialog allowing editing of entries in the Calls menu."""
        currentCalls = self.tabs.getColumnEntryList("Call")
        calls, ok = EditCalls.run(currentCalls)
        if ok:
            self.tabs.replace("Call", calls)

    def addResultGroup(self):
        """Adds Results and Groups to screening table based on call."""
        self.tabs.addResultGroup(self.markerdata)

    def enterExperimentDates(self):
        """Opens a dialog to add dates for experiments."""
        experiments = self.tabs.getColumnEntryList("Experiment")
        experimentDates, ok = GetExperimentDates.run(experiments)
        if ok:
            self.tabs.update("Experiment", experimentDates)

    ########################################################################
    def viewPlateStats(self):
        """Opens a dialog showing Group statistics organised by Plate for
		the current round of screening."""
        stats = self.tabs.getPlateStats()
        ok = ViewTable.run(stats)

    def viewPopulationStats(self):
        """Opens a dialog showing Group statistics organised by Population
		for the current round of screening."""
        stats = self.tabs.getPopulationStats()
        ok = ViewTable.run(stats)

    ########################################################################
    def setIncludeAll(self):
        """Sets the Include column of the current tab to True for all 
		samples. If the current tab is Kea or EBrida, sets the Include
		column of the Sample tab to True for all samples."""
        self.tabs.setColumn("Include", True)

    def setIncludeNone(self):
        """Sets the Include column of the current tab to True for all 
		samples. If the current tab is Kea or EBrida, sets the Include
		column of the Sample tab to True for all samples."""
        self.tabs.setColumn("Include", False)

    def setIncludeByResult(self):
        """Sets the Include column of the current tab to True or False,
		depending on an input set of conditions."""
        results = self.tabs.getColumnEntryList("Result")
        included, ok = GetSelection.run(results, "Include")
        if ok:
            self.tabs.update("Result", included)

    def setIncludeByGroup(self):
        """Sets the Include column of the current tab to True or False,
		depending on an input set of conditions."""
        groups = self.tabs.getColumnEntryList("Group")
        included, ok = GetSelection.run(groups, "Include")
        if ok:
            self.tabs.update("Group", included)

    def setIncludeByPlate(self):
        """Sets the Include column of the current tab to True or False,
		depending on an input set of conditions."""
        plates = self.tabs.getColumnEntryList("Plate ID")
        included, ok = GetSelection.run(plates, "Include")
        if ok:
            self.tabs.update("Plate ID", included)

    def setIncludeByPopulation(self):
        """Sets the Include column of the current tab to True or False,
		depending on an input set of conditions."""
        populations = self.tabs.sampleTable.getColumnEntryList("Population")
        included, ok = GetSelection.run(populations, "Include")
        if ok:
            self.tabs.setByPopulation("Include", included)

    def setIncludeByPopulationAndGroup(self):
        """Sets the Include column of the current tab to True or False,
		depending on an input set of conditions."""
        populations = self.tabs.sampleTable.getColumnEntryList("Population")
        groups = self.tabs.getColumnEntryList("Group")
        included, ok = GetPopGroupSelection.run(populations, groups)
        if ok:
            self.tabs.setIncludeByPopulationAndGroup(included)

    def setIncludeForTwoOfEachResultByPop(self):
        """Sets the Include column of the current tab to True or Ralse,
		depending on an input set of conditions."""
        populations = self.tabs.sampleTable.getColumnEntryList("Population")
        groups = self.tabs.getColumnEntryList("Group")
        included, ok = GetPopulationsAndNU.run(populations, groups)
        if ok:
            self.tabs.setIncludeByPopulationAndGroup2(included)

    def setExcludeNoSample(self):
        """Sets Include column to False for non-existing samples, leaving others as is."""
        nonExists = self.tabs.getNonExists()
        nonExists["Include"] = nonExists["Exists"]
        self.tabs.update(["Plate ID", "Well"], nonExists)

    ########################################################################
    ##	Output Menu Actions
    ########################################################################
    def outputAll(self):
        """Sets output column to True for all samples."""
        self.tabs.setColumn("Output", True)

    def outputNone(self):
        """Sets output column to False for all samples."""
        self.tabs.setColumn("Output", False)

    def setOutputByPlate(self):
        """Opens a dialog to select which plates to output."""
        plates = self.tabs.getColumnEntryList("Plate ID")
        output, ok = GetSelection.run(plates, "Output")
        if ok:
            self.tabs.update("Plate ID", output)

    def setOutputByPopulation(self):
        """Opens a dialog to select which populations to output."""
        populations = self.tabs.sampleTable.getColumnEntryList("Population")
        output, ok = GetSelection.run(populations, "Output")
        if ok:
            self.tabs.setByPopulation("Output", output)

    def outputExcludeNoResult(self):
        """Sets Output column to False for samples with no result, leaving others as is."""
        pass

    def outputExcludeNoSample(self):
        """Sets Output column to False for non-existing samples, leaving others as is."""
        nonExists = self.tabs.getNonExists()
        nonExists["Output"] = nonExists["Exists"]
        self.tabs.update(["Plate ID", "Well"], nonExists)

    def outputExcludeNegativeFailGrinds(self):
        """Sets Output column to False for Negative failed grinds, leaving others as is."""
        negativeFailGrinds = self.tabs.getNegativeFailGrinds()
        self.tabs.update(["Plate ID", "Well"], negativeFailGrinds)

    ########################################################################
    def getOutputFileName(self, suffix):
        """Creates an output fileName by prompting with a dialog box."""
        title = "Excel filename..."
        projectName = self.var.get("project", self.tabs.makeProjectName())
        defaultName = os.path.join(self.var["path"], projectName + "-" + suffix)
        fileName, f = QtGui.QFileDialog.getSaveFileName(self, title, defaultName)
        fileName = fileName.split(".")[0]
        return fileName

    def outputColouredPlatesGeneral(self, suffix, kea):
        """Outputs coloured platesheets for the active screening tab."""
        fileName = self.getOutputFileName(suffix)
        if fileName != "":
            results = self.tabs.getScreenResultsTable()
            results = ResultsTable(results)
            labels = results.getLabels()
            labels, ok = GetPlateLabels.run(labels)
            if ok:
                results.setLabels(labels)
                workBook = Workbook()
                addMarkerResultsTable(workBook, results, kea, self.markerdata, self.colours)
                addMarkerSheets(
                    workBook,
                    results,
                    kea,
                    self.markerdata,
                    self.markernotes,
                    self.colours,
                    self.var["images"],
                    self.validated,
                )
                addPlateSheets(workBook, results, kea, self.markerdata, self.colours)
                workBook.save(fileName + ".xlsx")

    def outputColouredPlatesAllGeneral(self, suffix, kea):
        """Outputs coloured platesheets for all rounds of screening."""
        fileName = self.getOutputFileName(suffix)
        if fileName != "":
            results = self.tabs.getAllResultsTable()
            results = ResultsTable(results)
            labels = results.getLabels()
            labels, ok = GetPlateLabels.run(labels)
            if ok:
                results.setLabels(labels)
                workBook = Workbook()
                addAllResultsTable(workBook, results, kea, self.markerdata, self.colours)
                addMarkerSheets(
                    workBook,
                    results,
                    kea,
                    self.markerdata,
                    self.markernotes,
                    self.colours,
                    self.var["images"],
                    self.validated,
                )
                addPlateSheets(workBook, results, kea, self.markerdata, self.colours)
                workBook.save(fileName + ".xlsx")

    ########################################################################
    def outputEbridaHarvestSheets(self):
        """'Outputs an Excel file containing harvest platesheets."""
        fileName = self.getOutputFileName("harvest")
        if fileName != "":
            samples = self.tabs.getEbridaHarvestData()
            workBook = HarvestBook()
            workBook.addEbridaHarvestSheets(samples)
            workBook.save(fileName + ".xls")

    def outputColouredPlates(self):
        """Outputs coloured platesheets for the active screening tab without
		Kea information."""
        self.outputColouredPlatesGeneral("sheets", False)

    def outputColouredPlatesKea(self):
        """Outputs coloured platesheets for the active screening tab with
		Kea information."""
        self.outputColouredPlatesGeneral("sheets-kea", True)

    def outputForKeaProcess(self):
        """Outputs a Kea uploadable spreadsheet for the active screening tab."""
        fileName = self.getOutputFileName("process-kea")
        if fileName != "":
            results = self.tabs.getScreenResultsTable()
            results = ResultsTable(results)
            results = results.keaProcessRun()
            writer = pd.ExcelWriter(fileName + ".xls")
            results.to_excel(writer, "Sheet1", index=False)
            writer.save()

    def outputForEbrida(self):
        """Outputs an EBrida spreadsheet of results for the active screening tab."""
        fileName = self.getOutputFileName("ebrida")
        if fileName != "":
            results = self.tabs.getScreenResultsTable()
            results = ResultsTable(results)
            results = results.ebridaResults()
            writer = pd.ExcelWriter(fileName + ".xls")
            results.to_excel(writer, "Sheet1", index=False)
            writer.save()

    def outputCustomPlates(self):
        """Outputs coloured platesheets in a format given by a dialog."""
        fileName = self.getOutputFileName("results")
        if fileName != "":
            results = self.tabs.getScreenResultsTable()
            results = ResultsTable(results)
            labels = results.getLabels()
            labels, ok = GetPlateLabels.run(labels)
            if ok:
                pass

    ########################################################################
    def outputColouredPlatesAll(self):
        """Outputs coloured platesheets for all rounds of screening without
		Kea information."""
        self.outputColouredPlatesAllGeneral("sheets-all", False)

    def outputColouredPlatesKeaAll(self):
        """Outputs coloured platesheets for all rounds of screening, with
		Kea information."""
        self.outputColouredPlatesAllGeneral("sheets-kea-all", True)

    def outputCustomPlatesAll(self):
        """Outputs coloured platesheets in a format given by a dialog."""
        fileName = self.getOutputFileName("results-all")
        if fileName != "":
            results = self.tabs.getAllResultsTable()
            results = ResultsTable(results)
            labels = results.getLabels()
            labels, ok = GetPlateLabels.run(labels)
            if ok:
                pass
Exemplo n.º 2
0
    def loadMarkerData(self):
        """Reads the markers file (stored in self.var) and creates a marker
		table."""
        fileName = self.var["markerdata"]
        coloursName = self.var["colours"]
        self.markerdata = MarkerTable(fileName)