sqlexport.py 21.6 KB
Newer Older
1 2
# -*- coding: utf-8 -*-
"""
3 4 5
GEPARD - Gepard-Enabled PARticle Detection
Copyright (C) 2018  Lars Bittrich and Josef Brandt, Leibniz-Institut für 
Polymerforschung Dresden e. V. <bittrich-lars@ipfdd.de>    
6

7 8 9 10 11 12 13 14 15 16 17 18 19
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program, see COPYING.  
If not, see <https://www.gnu.org/licenses/>.
20 21
"""

22
from PyQt5 import QtWidgets, QtCore
23 24 25 26 27 28 29 30
import numpy as np
import mysql.connector
import difflib
from io import StringIO
import os
import datetime
import json

31 32 33
import analysis.DBAssignments as dbassignments
from analysis.DBAssignments import DBAssignment

34
class SQLExport(QtWidgets.QDialog):
35 36
    def __init__(self, dataset):
        super(SQLExport, self).__init__()
37 38
        self.setWindowTitle('Export to SQL Database')
        
39 40 41 42 43 44
        self.dataset = dataset
        self.particleContainer = dataset.particleContainer
        
        self.longSizes = np.round(self.particleContainer.getSizesOfAllParticles())
        self.shortSize = np.round(self.particleContainer.getShortSizesOfAllParticles())
        self.spectra = self.particleContainer.getSpectraFromDisk()
45 46 47
        
        self.particleImages = None
        self.log = []
48
        self.dbAssignments = None
49
        
Lars Bittrich's avatar
Lars Bittrich committed
50
        configfilename = os.path.join(os.path.split(__file__)[0], 'database_config.txt')
51 52 53 54 55 56 57 58 59 60 61 62
        
        if not os.path.exists(configfilename):
            QtWidgets.QMessageBox.warning(self, 'Warning!',
                                'No server credentials provided! Put a json file in gepard/analysis.',
                                QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
            self.config = None
        else:
            with open(configfilename, 'r') as fp:
                self.config = json.load(fp)
                for key in ['user', 'password', 'host', 'database', 
                            'raise_on_warnings', 'charset', 'use_unicode']:
                    assert key in self.config, \
63
                        f'server config key {key} is missing databae_config json file'
64 65 66 67 68 69 70 71
        
        self.cnx = None
        self.createInterface()

    def createInterface(self):
        layout = QtWidgets.QVBoxLayout()
        self.setLayout(layout)
        
72 73 74 75 76 77 78 79
        assignmentFolder = QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.AppLocalDataLocation)
        assignmentPath = os.path.join(assignmentFolder, 'dbassignments.pkl')
        if not os.path.exists(assignmentPath):
            self.dbAssignments = DBAssignment()
            self.dbAssignments.setFileName(assignmentPath)
        else:
            self.dbAssignments = dbassignments.loadAssigments(assignmentPath)
            
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
        self.connect()
        
        promptGroup = QtWidgets.QGroupBox('General Properties')
        promptLayout = QtWidgets.QGridLayout()
        
        self.sampleSelector = QtWidgets.QComboBox()
        self.sampleSelector.addItems(self.getColFromTable('Sample_name', 'samples'))
        self.sampleEdit = LinkedLineEdit(self.sampleSelector)
        self.sampleEdit.setMaximumWidth(250)
        promptLayout.addWidget(QtWidgets.QLabel('Sample name*: '), 0, 0)
        promptLayout.addWidget(self.sampleSelector, 0, 1)
        promptLayout.addWidget(QtWidgets.QLabel(' (refine selection by typing here: '), 0, 2)
        promptLayout.addWidget(self.sampleEdit, 0, 3)
        promptLayout.addWidget(QtWidgets.QLabel(')'), 0, 4)
        
95
        self.methodIndices = self.getMethodIDs()
96
        self.methodSelector = QtWidgets.QComboBox()
97 98
        self.methodSelector.addItems(self.getMethodNames())
        
99 100 101 102 103 104 105 106 107 108 109 110 111
        self.methodEdit = LinkedLineEdit(self.methodSelector)
        self.methodEdit.setMaximumWidth(250)
        promptLayout.addWidget(QtWidgets.QLabel('Analysis Method*: '), 1, 0)
        promptLayout.addWidget(self.methodSelector, 1, 1)
        promptLayout.addWidget(QtWidgets.QLabel(' (refine selection by typing here: '), 1, 2)
        promptLayout.addWidget(self.methodEdit, 1, 3)
        promptLayout.addWidget(QtWidgets.QLabel(')'), 1, 4)
        
        analystList = self.getEntireTable('contributor')[1]
        self.analystIndices = [i[0] for i in analystList]
        self.analystSelector = QtWidgets.QComboBox()
        self.analystSelector.addItems([', '.join([i[2], i[1]]) for i in analystList])
        self.analysisDate = QtWidgets.QDateEdit()
112
        self.analysisDate.setDate(QtCore.QDate().currentDate())
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        self.arrivalDate = QtWidgets.QDateEdit()
        furtherProperties = {QtWidgets.QLabel('ArrivalDate*: '): self.arrivalDate,
                             QtWidgets.QLabel('Analysis : '): self.analysisDate, 
                             QtWidgets.QLabel('Analyst*: '): self.analystSelector}
        
        for index, key in enumerate(furtherProperties):
            promptLayout.addWidget(key, index+2, 0)
            promptLayout.addWidget(furtherProperties[key], index+2, 1)
            
        promptGroup.setLayout(promptLayout)
        layout.addWidget(promptGroup)
        
        ##prompt Result and catecorized Result for each polymer type:
        self.typeScrollArea = QtWidgets.QScrollArea()
        typeGroupBox = QtWidgets.QGroupBox('Polymer Type List')
        typeLayout = QtWidgets.QGridLayout()
        
        dbPolymResults = self.getEntireTable('polymer_type')[1]
        self.dbPolymResultsIndices = [i[0] for i in dbPolymResults]
        dbCategResults = self.getEntireTable('polymer_category')[1]
        dbPaintRemark = self.getEntireTable('paint_remark')[1]
        
        for index, entry in enumerate(['Detected Result*', 'DB Polymer Category*', 'DB Categorized Result', 'DB Paint Remark', 'Comment']):
            typeLayout.addWidget(QtWidgets.QLabel(entry), 0, index+1)
JosefBrandt's avatar
JosefBrandt committed
137

JosefBrandt's avatar
JosefBrandt committed
138
        self.polymerTypes = self.particleContainer.getUniquePolymers()
139
        self.polymerCheckboxes = []
140 141 142
        self.db_result_combos = []
        self.db_categs_combos = []
        self.db_pRemark_combos = []
143 144 145
        self.comments =[]
        for index, polymerType in enumerate(self.polymerTypes):
            self.polymerCheckboxes.append(QtWidgets.QCheckBox())
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
            newPolymCombo = QtWidgets.QComboBox()
            newPolymCombo.addItems([i[1] for i in dbPolymResults])
            self.db_result_combos.append(newPolymCombo)
            
            newCategCombo = QtWidgets.QComboBox()
            newCategCombo.addItems([i[1] for i in dbCategResults])
            self.db_categs_combos.append(newCategCombo)
            
            newPaintRemarksCombo = QtWidgets.QComboBox()
            newPaintRemarksCombo.addItems([i[1] for i in dbPaintRemark])
            newPaintRemarksCombo.addItem('')
            self.db_pRemark_combos.append(newPaintRemarksCombo)
            
            self.setComboBoxesToAssignment(newPolymCombo, newCategCombo, newPaintRemarksCombo, polymerType)
            
            
162 163 164
            self.comments.append(QtWidgets.QLineEdit())
            
            self.polymerCheckboxes[-1].stateChanged.connect(self.makeStateChangedLambda(self.polymerCheckboxes[-1], 
165
                                                                     [self.db_result_combos[-1], self.db_categs_combos[-1], self.db_pRemark_combos[-1], self.comments[-1]]))
166 167 168 169 170
            self.polymerCheckboxes[-1].setChecked(True)
            self.polymerCheckboxes[-1].setChecked(False)  #switch twice, so that the stateChanged-function is called
            
            typeLayout.addWidget(self.polymerCheckboxes[-1], index+1, 0)
            typeLayout.addWidget(QtWidgets.QLabel(polymerType), index+1, 1)
171 172 173
            typeLayout.addWidget(self.db_result_combos[-1], index+1, 2)
            typeLayout.addWidget(self.db_categs_combos[-1], index+1, 3)
            typeLayout.addWidget(self.db_pRemark_combos[-1], index+1, 4)
174 175
            typeLayout.addWidget(self.comments[-1], index+1, 5)
        
176
        for element in (self.db_result_combos + self.db_categs_combos + self.db_pRemark_combos + self.comments):
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
            element.setMaximumWidth(250)
        
        typeGroupBox.setLayout(typeLayout)
        self.typeScrollArea.setWidget(typeGroupBox)
        self.typeScrollArea.setFixedWidth(1200)
        self.typeScrollArea.setFixedHeight(500)
        layout.addWidget(self.typeScrollArea)
        
        self.uploadBtn = QtWidgets.QPushButton('Upload to SQL Database')
        self.uploadBtn.released.connect(self.uploadResults)
        self.uploadBtn.setMaximumWidth(150)
        layout.addWidget(self.uploadBtn)
        layout.addStretch()
        
    def uploadResults(self):
        if self.connectionIsValid():
            cursor = self.cnx.cursor()
            particles2analasyses = {}
            self.log = []
            
            currentParticleInd = self.getPartIndicesOfSample(self.sampleSelector.currentText())
            
            currentAnalysisInd  = self.getAnalyisIndicesOfMethod(self.methodIndices[self.methodSelector.currentIndex()])
Hackmet's avatar
Hackmet committed
200
            sizeCategories = self.getEntireTable('size_fraction')[1]
201
            
JosefBrandt's avatar
JosefBrandt committed
202 203
            for polymerIndex, polymerType in enumerate(self.polymerTypes):
                if self.polymerCheckboxes[polymerIndex].isChecked():
JosefBrandt's avatar
JosefBrandt committed
204
                    polymIndices = self.particleContainer.getIndicesOfParticleType(polymerType)
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
                    
                    particleCols = self.getEntireTable('particles')[0]
                    sizeCols = [i for i in particleCols if i.startswith('Size') and i.endswith(']')]
                   
                    for polymInd in polymIndices:
                        
                        #upload to particles:
                        usedCols = {}
                        usedCols['Sample'] = str(self.sampleSelector.currentText())
                        usedCols['Preferred_method'] = str(self.methodIndices[self.methodSelector.currentIndex()])
                        usedCols['Arrival_date'] = self.getDateString(self.arrivalDate.date())
                        usedCols['Analysis_date'] = self.getDateString(self.analysisDate.date())
                        usedCols['Amount'] = str(1)
                        usedCols['Analyst'] = str(self.analystIndices[self.analystSelector.currentIndex()])
                        usedCols['Size_fraction'] = self.getSizeFraction(sizeCategories, self.longSizes[polymInd])
                        usedCols[sizeCols[0]] = str(self.longSizes[polymInd])
                        usedCols[sizeCols[1]] = str(self.shortSize[polymInd])
                        if self.particleImages is not None:
                            usedCols['Image'] = self.particleImages[polymInd]
224 225 226
                        usedCols['Categorised_result'] = self.db_categs_combos[polymerIndex].currentText()
                        if self.db_pRemark_combos[polymerIndex].currentText() != '':
                            usedCols['Indication_paint'] = self.db_pRemark_combos[polymerIndex].currentText() 
227 228 229 230 231 232 233 234 235
                            
                        requiredColumns = '(`'+'`,`'.join(list(usedCols.keys())) + '`'
                        vals = '","'.join(list(usedCols.values()))

                        sql_command = 'INSERT INTO `micropoll`.`particles`' + requiredColumns + ') VALUES ("' + vals + '");'
                        try:
                            cursor.execute(sql_command)
                        except:
                            print(sql_command)
236
                        self.cnx.commit()
237 238 239 240 241 242 243 244
                        
                        newIndices = self.getPartIndicesOfSample(self.sampleSelector.currentText())
                        addedParticleIndex = list(set(newIndices) - set(currentParticleInd))[0]
                        currentParticleInd = self.getPartIndicesOfSample(self.sampleSelector.currentText())
                        
                        particles2analasyses[addedParticleIndex] = []
                        self.log.append(sql_command)
                    
245
                       ##upload to analyses:
246 247 248
                        method = self.methodIndices[self.methodSelector.currentIndex()]
                        lib = polymerType
                        hqi = str(0)
249
                        specIDs = self.particleContainer.getSpectraIndicesOfParticle(polymInd)
250
                        for specID in specIDs:
JosefBrandt's avatar
JosefBrandt committed
251
                            spec = self.spectra[:, [0, specID+1]]
252 253 254 255
                            fp = StringIO()
                            np.savetxt(fp, spec)
                            fp.seek(0)
                            spec = fp.read()
256
                            res = self.dbPolymResultsIndices[self.db_result_combos[polymerIndex].currentIndex()]
JosefBrandt's avatar
JosefBrandt committed
257
                            com = self.comments[polymerIndex].text()
258 259 260 261 262 263 264 265 266
                            
                            format_str = """INSERT INTO analysis (Method, Library_entry, Spectrum, Result, Comment) 
                                VALUES ("{method}", "{lib}", "{spec}", "{res}", "{com}");"""
                            sql_command = format_str.format(method=method, lib=lib, spec=spec, res=res, com=com)
                            
                            try:
                                cursor.execute(sql_command)
                            except:
                                print(sql_command)
267
                            self.cnx.commit()
268 269 270 271 272 273 274 275 276 277 278
                            #remove spectrum for log...
                            sql_command = format_str.format(method=method, lib=lib, hqi=hqi, spec='SpecFile', res=res, com=com)
                            self.log.append(sql_command)
                            
                            newIndices = self.getAnalyisIndicesOfMethod(self.methodIndices[self.methodSelector.currentIndex()])
                            addedAnalysisIndex = list(set(newIndices) - set(currentAnalysisInd))[0]
                            currentAnalysisInd  = self.getAnalyisIndicesOfMethod(self.methodIndices[self.methodSelector.currentIndex()])
                            
                            particles2analasyses[addedParticleIndex].append(addedAnalysisIndex)
                    

279 280 281 282 283 284 285
            ##upload particles2analyses:
            for particleInd in particles2analasyses:
                for anaInd in particles2analasyses[particleInd]:
                    sql_command = """INSERT INTO particles2analysis (IDParticles, IDAnalysis) VALUES ("{}", "{}");""".format(particleInd, anaInd)
                    cursor.execute(sql_command)
                    self.log.append(sql_command)
            self.cnx.commit()
286 287 288

            for index, polymType in enumerate(self.polymerTypes):
                if self.polymerCheckboxes[index].isChecked():
289 290 291
                    if polymType not in self.dataset.resultsUploadedToSQL:
                        self.dataset.resultsUploadedToSQL.append(polymType)
                    self.dataset.save()
292 293
                    
            #write log to file
294
            logfile = os.path.join(self.dataset.path, 'sql_log.txt')
295 296
            increment = 1
            while os.path.exists(logfile):
297
                logfile = os.path.join(self.dataset.path, 'sql_log ({}).txt'.format(increment))
298 299 300 301 302 303 304 305 306 307 308
                increment += 1
            
            with open(logfile, 'w') as fp:
                fp.write('SQL log from: {}\n'.format(datetime.datetime.now().strftime("%d.%m.%y %H:%M")))
                for line in self.log:
                    fp.write(line + '\n')
                    
            QtWidgets.QMessageBox.about(self, 'Success', 'Upload successfull')
            
            
    def getSizeFraction(self, sizeList, size):
Hackmet's avatar
Hackmet committed
309
        size = np.round(size)
310
        for i in sizeList:
Hackmet's avatar
Hackmet committed
311 312
            if i[1].find('>') != -1:    #i.e., string is '>100000'
                return i[1]
313
            else:
Hackmet's avatar
Hackmet committed
314 315 316 317 318
                limits = [i[2], i[3]]
                upper = float(limits[1])
                lower = float(limits[0])
                if lower <= size <= upper:
                    return i[1]
319 320 321 322 323 324 325 326 327 328 329 330
            

    def getDateString(self, QDateObject):
        return '-'.join([str(i) for i in [QDateObject.year(), QDateObject.month(), QDateObject.day()]])
    
    def makeStateChangedLambda(self, checkbox, elements):
        return lambda: self.setPolymerEnabled(checkbox, elements)
    
    def setPolymerEnabled(self, checkbox, elements):
        for element in elements:
            element.setEnabled(checkbox.isChecked())
    
331 332 333 334 335 336 337 338 339 340 341 342 343
    def setComboBoxesToAssignment(self, resultCombo, categCombo, paintRemarkCombo, polymName):
        if self.dbAssignments.hasAssignment(polymName):
            assignment = self.dbAssignments.getAssignment(polymName)
            resultCombo.setCurrentText(assignment.result)
            categCombo.setCurrentText(assignment.categorizedResult)
            paintRemarkCombo.setCurrentText(assignment.indication_paint)
        else:
            #set to closest Match
            for comboBox in [resultCombo, categCombo]:
                entries = [comboBox.itemText(i) for i in range(comboBox.count())]
                sortedEntries = difflib.get_close_matches(polymName, entries, len(entries), 0)
                comboBox.setCurrentIndex(entries.index(sortedEntries[0]))
            paintRemarkCombo.setCurrentText('')
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
        
    def connectionIsValid(self):
        if self.cnx is None:
            print('Object not connected.')
            return False
        else:
            return True
        
    def connect(self):
        if self.config is None:
            return
        try:
            self.cnx = mysql.connector.connect(**self.config)  #port: 3306
        except mysql.connector.Error as err:
            print(err)
Lars Bittrich's avatar
Lars Bittrich committed
359 360 361
            QtWidgets.QMessageBox.warning(self, 'Error!',
                                str(err),
                                QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
            self.cnx = None
    
    def getEntireTable(self, tablename):
        if self.connectionIsValid():
            cursor = self.cnx.cursor()
            cursor.execute("SHOW columns FROM {}".format(tablename))
            columnNames = [column[0] for column in cursor.fetchall()]            
            cursor.execute("SELECT * FROM {}".format(tablename))
            data = [row for row in cursor]

        else: columnNames = data = None
        
        return columnNames, data
    
    def getColFromTable(self, columnName, tableName):
        if self.connectionIsValid():
            cursor = self.cnx.cursor()
            cursor.execute("SELECT {} FROM {}".format(columnName, tableName))
            data = [row[0] for row in cursor]
        else:
            data = None
            print('returned None from Table '.format('tableName'))
        
        return data
    
387 388 389 390 391 392 393 394 395 396 397 398
    def getMethodIDs(self):
        if self.connectionIsValid():
            cursor = self.cnx.cursor()
            cursor.execute("SELECT IDMethod FROM methods ORDER BY IDMethod")
            return [row[0] for row in cursor]
    
    def getMethodNames(self):
        if self.connectionIsValid():
            cursor = self.cnx.cursor()
            cursor.execute("SELECT Method_name FROM methods ORDER BY IDMethod")
            return [row[0] for row in cursor]
    
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    def getPartIndicesOfSample(self, sampleName):
        if self.connectionIsValid():
            cursor = self.cnx.cursor()
            cursor.execute("SELECT IDParticles FROM particles WHERE Sample = '{}'".format(sampleName))
            data = [row[0] for row in cursor]
        else:
            data = None
            print('returned None from Table '.format('tableName'))
        
        return data
    
    def getAnalyisIndicesOfMethod(self, methodIndex):
        if self.connectionIsValid():
            cursor = self.cnx.cursor()
            cursor.execute("SELECT IDAnalysis FROM analysis WHERE Method = '{}'".format(methodIndex))
            data = [row[0] for row in cursor]
        else:
            data = None
            print('returned None from Table '.format('tableName'))
        
        return data
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    
    def closeEvent(self, event):
        self.saveAssignments()
        event.accept()
    
    def saveAssignments(self):
        if self.dbAssignments is not None:
            for index, polymerType in enumerate(self.polymerTypes):
                if not self.dbAssignments.hasAssignment(polymerType):
                    self.dbAssignments.createNewAssignment(polymerType)
                result = self.db_result_combos[index].currentText()
                categ_result = self.db_categs_combos[index].currentText()
                paint_remark = self.db_pRemark_combos[index].currentText()
                self.dbAssignments.updateAssignment(polymerType, result, categ_result, paint_remark)
            
            self.dbAssignments.save()
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455

class LinkedLineEdit(QtWidgets.QLineEdit):
    def __init__(self, combobox):
        super(LinkedLineEdit, self).__init__()
        self.combobox = combobox
        self.entries = [self.combobox.itemText(i) for i in range(self.combobox.count())]
        self.lowerEntries = [self.combobox.itemText(i).lower() for i in range(self.combobox.count())]
    
    def keyPressEvent(self, event):
        super(LinkedLineEdit, self).keyPressEvent(event)
        curString = self.text().lower()
        self.combobox.clear()
        if len(curString) == 0:
            self.combobox.addItems(self.entries)
        else:
            matchingEntries = []
            for index, entry in enumerate(self.lowerEntries):
                if entry.find(curString) >= 0:
                    matchingEntries.append(self.entries[index])
            self.combobox.addItems(matchingEntries)
456
            self.combobox.update()