sqlexport.py 21.8 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
        self.dataset = dataset
        self.particleContainer = dataset.particleContainer
        
        self.longSizes = np.round(self.particleContainer.getSizesOfAllParticles())
        self.shortSize = np.round(self.particleContainer.getShortSizesOfAllParticles())
44
        self.colors = self.particleContainer.getColorsOfAllParticles()
45
        self.shapes = self.particleContainer.getShapesOfAllParticles()
46
        self.spectra = self.particleContainer.getSpectraFromDisk()
47 48 49
        
        self.particleImages = None
        self.log = []
50
        self.dbAssignments = None
51
        
Lars Bittrich's avatar
Lars Bittrich committed
52
        configfilename = os.path.join(os.path.split(__file__)[0], 'database_config.txt')
53 54 55 56 57 58 59 60 61 62 63 64
        
        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, \
65
                        f'server config key {key} is missing databae_config json file'
66 67 68 69 70 71 72 73
        
        self.cnx = None
        self.createInterface()

    def createInterface(self):
        layout = QtWidgets.QVBoxLayout()
        self.setLayout(layout)
        
74 75 76 77 78 79 80 81
        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)
            
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
        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)
        
97
        self.methodIndices = self.getMethodIDs()
98
        self.methodSelector = QtWidgets.QComboBox()
99 100
        self.methodSelector.addItems(self.getMethodNames())
        
101 102 103 104 105 106 107 108 109 110 111 112 113
        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()
114
        self.analysisDate.setDate(QtCore.QDate().currentDate())
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        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
139

JosefBrandt's avatar
JosefBrandt committed
140
        self.polymerTypes = self.particleContainer.getUniquePolymers()
141
        self.polymerCheckboxes = []
142 143 144
        self.db_result_combos = []
        self.db_categs_combos = []
        self.db_pRemark_combos = []
145 146 147
        self.comments =[]
        for index, polymerType in enumerate(self.polymerTypes):
            self.polymerCheckboxes.append(QtWidgets.QCheckBox())
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
            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)
            
            
164 165 166
            self.comments.append(QtWidgets.QLineEdit())
            
            self.polymerCheckboxes[-1].stateChanged.connect(self.makeStateChangedLambda(self.polymerCheckboxes[-1], 
167
                                                                     [self.db_result_combos[-1], self.db_categs_combos[-1], self.db_pRemark_combos[-1], self.comments[-1]]))
168 169 170 171 172
            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)
173 174 175
            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)
176 177
            typeLayout.addWidget(self.comments[-1], index+1, 5)
        
178
        for element in (self.db_result_combos + self.db_categs_combos + self.db_pRemark_combos + self.comments):
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
            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
202
            sizeCategories = self.getEntireTable('size_fraction')[1]
203
            
JosefBrandt's avatar
JosefBrandt committed
204 205
            for polymerIndex, polymerType in enumerate(self.polymerTypes):
                if self.polymerCheckboxes[polymerIndex].isChecked():
JosefBrandt's avatar
JosefBrandt committed
206
                    polymIndices = self.particleContainer.getIndicesOfParticleType(polymerType)
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
                    
                    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])
222
                        usedCols['Colour'] = self.colors[polymInd]
223
                        usedCols['Shape'] = self.shapes[polymInd]
224 225 226 227
                        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]
228 229 230
                        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() 
231 232 233 234 235 236 237 238 239
                            
                        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)
240
                        self.cnx.commit()
241 242 243 244 245 246 247 248
                        
                        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)
                    
249
                       ##upload to analyses:
250 251 252
                        method = self.methodIndices[self.methodSelector.currentIndex()]
                        lib = polymerType
                        hqi = str(0)
253
                        specIDs = self.particleContainer.getSpectraIndicesOfParticle(polymInd)
254
                        for specID in specIDs:
JosefBrandt's avatar
JosefBrandt committed
255
                            spec = self.spectra[:, [0, specID+1]]
256 257 258 259
                            fp = StringIO()
                            np.savetxt(fp, spec)
                            fp.seek(0)
                            spec = fp.read()
260
                            res = self.dbPolymResultsIndices[self.db_result_combos[polymerIndex].currentIndex()]
JosefBrandt's avatar
JosefBrandt committed
261
                            com = self.comments[polymerIndex].text()
262 263 264 265 266 267 268 269 270
                            
                            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)
271
                            self.cnx.commit()
272 273 274 275 276 277 278 279 280 281 282
                            #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)
                    

283 284 285 286 287 288 289
            ##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()
290 291 292

            for index, polymType in enumerate(self.polymerTypes):
                if self.polymerCheckboxes[index].isChecked():
293 294 295
                    if polymType not in self.dataset.resultsUploadedToSQL:
                        self.dataset.resultsUploadedToSQL.append(polymType)
                    self.dataset.save()
296 297
                    
            #write log to file
298
            logfile = os.path.join(self.dataset.path, 'sql_log.txt')
299 300
            increment = 1
            while os.path.exists(logfile):
301
                logfile = os.path.join(self.dataset.path, 'sql_log ({}).txt'.format(increment))
302 303 304 305 306 307 308 309 310 311 312
                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
313
        size = np.round(size)
314
        for i in sizeList:
Hackmet's avatar
Hackmet committed
315 316
            if i[1].find('>') != -1:    #i.e., string is '>100000'
                return i[1]
317
            else:
Hackmet's avatar
Hackmet committed
318 319 320 321 322
                limits = [i[2], i[3]]
                upper = float(limits[1])
                lower = float(limits[0])
                if lower <= size <= upper:
                    return i[1]
323 324 325 326 327 328 329 330 331 332 333 334
            

    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())
    
335 336 337 338 339 340 341 342 343 344 345 346 347
    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('')
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        
    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
363 364 365
            QtWidgets.QMessageBox.warning(self, 'Error!',
                                str(err),
                                QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
            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
    
391 392 393 394 395 396 397 398 399 400 401 402
    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]
    
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    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
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    
    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()
440
            
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

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)
461
            self.combobox.update()