-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3279 lines (2746 loc) · 141 KB
/
Copy pathmain.py
File metadata and controls
3279 lines (2746 loc) · 141 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
@author: Robin van Gyseghem, Ronny Friedrich
@date: 2022-06-09
"""
import sys
import urllib.request
from fbs_runtime.application_context.PyQt5 import ApplicationContext
from PyQt5.QtWidgets import QSplitter, QSpacerItem, QSizePolicy, QGroupBox, QFrame, QWidget, QMainWindow, QGroupBox, \
QTableView, QSpacerItem, QTextEdit, QGridLayout, QDialog, QCheckBox, QApplication, QPushButton, QVBoxLayout, \
QLineEdit, QLabel, QHBoxLayout, QComboBox , QTabWidget, QProgressBar ,QMenu
from PyQt5 import QtGui
from PyQt5.QtCore import Qt ,pyqtSignal ,QObject, QThread
from datetime import timedelta, datetime
import sqlite3
from matplotlib.ticker import MaxNLocator
from PyQt5 import QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from pandas.plotting import register_matplotlib_converters
import matplotlib.pyplot as plt
import matplotlib.dates
from pandas import to_datetime, Series
from pandas import DataFrame, read_csv, read_excel, read_sql, DateOffset , ExcelWriter
import pandas
from mpldatacursor import datacursor
from itertools import cycle, islice
from numpy import nan, linspace, tan, arange, sin, pi, isfinite
import os.path
import random
import openpyxl
import xlsxwriter
from config.config_logger import logger
try:
import xlrd
except ImportError:
sys.exit("""You need xlrd!
install it from https://pypi.org/project/xlrd/
or run pip install xlrd.""")
# set logger name for this module
logger.name = __name__
# import seaborn as sns
global dpi
dpi = 100
myVersion = '2022-06-09'
class SearchWindow(QDialog):
def __init__(self, parent=None):
logger.debug('perform function')
super(SearchWindow, self).__init__(parent)
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint )
#self.setStyleSheet("background-color:lightyellow;")
self.figure = plt.figure(dpi=dpi)
#self.figure.set_facecolor("lightyellow")
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
self.setWindowTitle("Search-Resplor")
self.editbox = QLineEdit()
self.roweditX = QComboBox()
#self.roweditX.setStyleSheet("background-color:lightgray;")
self.roweditX.setFixedWidth(100)
self.roweditY = QComboBox()
#self.roweditY.setStyleSheet("background-color:lightgray;")
# self.roweditY2 = QComboBox()
# self.roweditY2.setStyleSheet("background-color:lightgray;")
#self.roweditY.setFixedWidth(100)
# self.roweditY2.setFixedWidth(100)
self.searchcoledit = QComboBox()
#self.searchcoledit.setStyleSheet("background-color:lightgray;")
self.searchcoledit.setFixedWidth(100)
self.nameedit = QLineEdit()
#self.nameedit.setStyleSheet("background-color:lightgray;")
# self.nameedit.setFixedWidth(100)
self.tableedit = QComboBox()
#self.tableedit.setStyleSheet("background-color:lightgray;")
self.labelrowX = QLabel("Plotwerte X", self)
self.labelrowY = QLabel("Plotwerte Y", self)
# self.labelrowY2 = QLabel("Plotwerte Y", self)
self.labelsearchcol = QLabel("in Suchspalte", self)
self.labelname = QLabel("Suche", self)
self.labeltabelle = QLabel("Tabelle", self)
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.search)
self.buttongetdata = QPushButton('Search')
self.buttongetdata.clicked.connect(self.search)
self.checkbx = QCheckBox("Plot Temp", self)
self.checkbx.stateChanged.connect(self.clickBox)
self.checkbox = False
self.tableview = QTableView()
# self.plottbutton = QPushButton('Plot')
# set the layout
self.hbox = QHBoxLayout()
self.vbox = QVBoxLayout()
self.hbox1 = QHBoxLayout()
#self.hbox1.addStretch(1)
self.hbox1.addWidget(self.labelrowX)
self.hbox1.addWidget(self.roweditX)
self.hbox1.addStretch(1)
self.hbox1.addWidget(self.labelrowY)
self.hbox1.addWidget(self.roweditY)
# self.hbox1.addWidget(self.labelrowY2)
# self.hbox1.addWidget(self.roweditY2)
self.hbox.addLayout(self.vbox)
#self.hbox.addStretch(4)
self.hbox.addWidget(self.labeltabelle)
self.hbox.addWidget(self.tableedit)
self.hbox.addWidget(self.labelname)
self.hbox.addWidget(self.nameedit)
self.hbox.addWidget(self.labelsearchcol)
self.hbox.addWidget(self.searchcoledit)
#self.hbox.addStretch(1)
layout = QVBoxLayout(self)
layout.addLayout(self.hbox)
layout.addLayout(self.hbox1)
layout.addWidget(self.toolbar)
# layout.addWidget(self.plottbutton)
layout.addWidget(self.canvas)
# layout.addWidget(self.editbox)
layout.addWidget(self.button)
layout.addWidget(self.checkbx)
# self.eadialog = None
# self.eadialog = None
# self.cnmddialog = None
# self.oprawdialog = None
# self.opoddialog = None
self.setLayout(layout)
self.setAcceptDrops(True)
# self.dialogopen = False
# self.infodialogopen = False
# self.roweditX.setText('finishdate')
# self.roweditY.setText('o18gas')
# self.nameedit.setText('Ag3PO4')
# self.tableedit.setItem('opod')
tablelist = self.tablelist()
self.tableedit.addItems(tablelist)
self.tableedit.currentIndexChanged.connect(lambda: self.tablechanged())
self.tablechanged()
self.tableedit.setCurrentText('cnod')
def contextMenuEvent(self, event):
logger.debug('perform function')
contextMenu = QMenu(self)
newAct = contextMenu.addAction("New")
openAct = contextMenu.addAction("Open")
quitAct = contextMenu.addAction("Quit")
action = contextMenu.exec_(self.mapToGlobal(event.pos()))
if action == quitAct:
self.close()
def search(self):
logger.debug('perform function')
# random data tabletoload = "cnmdtable"
self.plotcol = self.roweditX.currentText()
self.plotcolY1 = self.roweditY.currentText()
# self.plotcolY2 = self.roweditY2.currentText()
self.searchname = self.nameedit.text()
self.searchcol = self.searchcoledit.currentText()
self.tabletoload = self.tableedit.currentText()
# noch auf geschützte eingabe umändern
# if self.plotcolY2 != '':
# self.plotcolY1 = self.plotcolY1 +","+ self.plotcolY2
plottable = "SELECT " + self.plotcol + ',' + self.plotcolY1 + ",filename FROM " + self.tabletoload + " WHERE " + self.searchcol + " LIKE '%" + self.searchname + "%';"
# temphumidvalues = "SELECT temp,humid FROM temphumidtable "
title = self.searchname
self.plotprepare(plottable, title)
def tablechanged(self):
logger.debug('perform function')
print('tablechanged to :' + self.tableedit.currentText())
collist = self.collist()
self.searchcoledit.clear()
self.roweditX.clear()
self.roweditY.clear()
# self.roweditY2.clear()
self.searchcoledit.addItems(collist)
self.roweditX.addItems(collist)
self.roweditY.addItems(collist)
# self.roweditY2.addItems(collist)
# self.roweditY2.addItem('')
self.roweditY.setCurrentIndex(-1)
# self.roweditY2.setCurrentIndex(-1)
#
self.roweditX.setCurrentText('finishdate')
self.roweditY.setCurrentText('o18vsmowod')
self.searchcoledit.setCurrentText('name')
def collist(self):
logger.debug('perform function')
table = self.tableedit.currentText()
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute("PRAGMA table_info(" + table + " );")
columnlist = c.fetchall()
columnlist = [x[1] for x in columnlist]
conn.commit()
conn.close()
return (columnlist)
def tablelist(self):
logger.debug('perform function')
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';")
tablelist = c.fetchall()
print(tablelist)
conn.commit()
conn.close()
tablelist = [x[0] for x in tablelist]
print(tablelist)
tablelist.remove('temphumidtable')
# tablelist.remove('temptable')
return (tablelist)
def clickBox(self, state):
logger.debug('perform function')
if state == QtCore.Qt.Checked:
print('Checked')
self.checkbox = True
else:
print('Unchecked')
self.checkbox = False
def plotprepare(self, plottable, title):
logger.debug('perform function')
print(plottable)
self.title = title
try:
connection = sqlite3.connect(database)
self.plotdf = read_sql(plottable, con=connection, coerce_float=True, params=None, parse_dates=None,
columns=None, chunksize=None)
# self.temphumiddf = read_sql(temphumidvalues, con = connection, coerce_float=True, params=None, parse_dates=None, chunksize=None)
self.plotdfcols = self.plotdf.columns
# plotdf['finishdate'].replace(to_replace=[None], value = "2018.11.11 11:11:11", inplace=True)
self.plotdf = self.plotdf.sort_values(by=self.plotdf.columns[0])
if set(['date']).issubset(self.plotdf.columns):
self.plotdf['date'] = to_datetime(self.plotdf.date, format='%Y/%m/%d %H:%M:%S')
self.plotdf = self.plotdf.sort_values(by='date')
self.plotdf = self.plotdf.iloc[1::20, :]
if set(['finishdate']).issubset(self.plotdf.columns):
self.plotdf['finishdate'] = to_datetime(self.plotdf.finishdate)
self.plotdf = self.plotdf.sort_values(by='finishdate') # sort_byvalues inplace=True, ascending=False
if set(['id']).issubset(self.plotdf.columns):
self.plotdf = self.plotdf.sort_values(by=['id'])
# self.plotdf = self.plotdf[pd.notnull(self.plotdf[self.plotdf.columns[1]])] # get rid off nan
# sortieren nach col0 also finsishdate oder id
self.plotdf = self.plotdf.reset_index(drop=True) # index wieder richtig setzen
# plotdf = plotdf[(plotdf. != 0).any()] 'remove zeros'
# print(len(plotdfcols))
# instead of ax.hold(False)
# self.plotdf.dropna(axis=0, how='any', inplace=True) #get rid of na an zeros
self.plotdf = self.plotdf.replace(0, nan)
if self.checkbox:
self.makeplot(title=title, plottemp=True)
else:
self.makeplot(title=title, plottemp=False)
except Exception as e:
message = 'Fehler bei der Ploterstellung: ' + str(e)
main.open_infodialog(message)
def makeplot(self, title='', plottemp=False):
logger.debug('perform function')
self.plottemp = plottemp
plt.style.use('seaborn-darkgrid')
model = PandasModel(self.plotdf)
Fenstername = 'Plotdata: ' + title
main.open_new_dialog(Fenstername, 'plot', model)
self.figure.clear()
ax = self.figure.add_subplot(111)
xlabel = self.plotdfcols[0]
ylabel = self.plotdfcols[1]
self.figure.suptitle(title, fontsize=16, fontweight='bold')
# ax.hold(True) # deprecated, see above
ax.set_xlabel(xlabel, fontsize=16)
ax.set_ylabel(ylabel, fontsize=16)
if 'filename' in self.plotdf.columns:
print("filename listed to plot")
print(self.plotdf.filename[0])
newlist = list(self.plotdf.filename)
aktuell = self.plotdf.filename[0]
farbe = 'k'
farbliste = []
for inhalt in newlist:
if inhalt == aktuell:
print(farbe + inhalt)
farbliste.append(farbe)
else:
if farbe == 'k':
farbe = 'r'
else:
farbe = 'k'
farbliste.append(farbe)
aktuell = inhalt
self.plotdf['farben'] = farbliste
print(self.plotdf)
grouped = self.plotdf.groupby('farben')
blackdf = grouped.get_group('k')
print(grouped.get_group('k'))
try: #abfangen falls nur ein filename in der liste ist
reddf = grouped.get_group('r')
except:
reddf= blackdf
print('only one color')
pass
start, end = ax.get_xlim()
stepsize = 2
if (self.plotdf[self.plotdfcols[0]].dtype == "datetime64[ns]"):
plt.xticks(rotation=45, fontsize=9)
color1 = ax.plot_date(blackdf[self.plotdfcols[0]], blackdf[self.plotdfcols[1]], fmt='o', color='sienna',
picker=5)
color2 = ax.plot_date(reddf[self.plotdfcols[0]], reddf[self.plotdfcols[1]], fmt='o', color='orange',
picker=5, )
# ax.xaxis.set_ticks(np.arange(start, end, stepsize)
else:
ax.scatter(self.plotdf[self.plotdfcols[0]], self.plotdf[self.plotdfcols[1]], color=farbliste)
elif (self.plotdf[self.plotdfcols[0]].dtype == "datetime64[ns]"):
plt.xticks(rotation=45, fontsize=9)
# ax.xaxis.set_ticks(np.arange(start, end, stepsize))
ax.plot_date(self.plotdf[self.plotdfcols[0]], self.plotdf[self.plotdfcols[1]], fmt='o', picker=5, )
else:
ax.scatter(self.plotdf[self.plotdfcols[0]], self.plotdf[self.plotdfcols[1]], color='g')
if self.plottemp:
ax2 = ax.twinx()
tempdata = self.get_temp_values()
ax2.plot(tempdata[tempdata.columns[0]], tempdata[tempdata.columns[1]], color='r', alpha=.2)
ax2.set_ylabel('temp °C', fontsize=16)
'''
You
can
groupby and plot
them
separately
for each color:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots(figsize=(30, 10))
color = 'tab:red'
for pcolor, gp in df.groupby('color'):
ax1.plot_date(gp['time'], gp['distance'], marker='o', color=pcolor)
'''
# ax.set_position([0, 0, 0,0])
self.figure.subplots_adjust(0.1, 0.2, 0.9, 0.9, ) # 0.2,0.3
datacursor(formatter=self.myformatter, display='multiple', draggable=True)
ax.legend(fontsize=12)
ax.legend().set_visible(False)
ax.grid(True)
# (pdfile.index,pdfile.values,150,marker = ">")
# ax.plot(plotdf.columns[1].value, plotdf.columns[1].value)
self.canvas.draw()
def myformatter(self, **kwarg):
logger.debug('perform function')
values = self.collist()
items = []
# for item in values
# value = searchvalue(item)
xaxis = self.plotdfcols[0] + ': '
yaxis = self.plotdfcols[1] + ': '
if self.plotdfcols[0] == 'finishdate':
val1 = matplotlib.dates.num2date(kwarg['x']).strftime('%Y-%m-%d %H:%M:%S')
else:
val1 = self.getfinishdate(kwarg['x'], self.plotdfcols[0])
print(self.plotdfcols[0], int(kwarg['x']))
print("retrived:", val1)
valuesdf = self.getvalues(val1)
pandas.set_option('display.max_columns', 30)
# label = xaxis + val1 + '\n' + yaxis + ' {y:.3f}'.format(**kwarg) +str(values)
label = str(valuesdf)
label = label.split("\n", 1)[1]
print(type(val1), val1)
return label
# if len(self.plotdfcols)>2:
# ax.scatter(self.plotdf[self.plotdfcols[0]], self.plotdf[self.plotdfcols[2]])
# temperatur plotten
# ax.scatter(self.temphumiddf[0],self.temphumiddf[1])
# datacursor(ax)
'''SELECT DISTINCT column_list
FROM table_list
JOIN table ON join_condition
WHERE row_filter
ORDER BY column
LIMIT count OFFSET offset
GROUP BY column
HAVING group_filter '''
def getvalues(self, finishdate):
logger.debug('perform function')
print(finishdate)
print(type(finishdate))
connection = sqlite3.connect(database)
sqlsynt = "SELECT * FROM " + self.tabletoload + " WHERE finishdate LIKE '%" + str(finishdate) + "%';"
values = read_sql(sqlsynt, con=connection, coerce_float=True, params=None, parse_dates=None, columns=None,
chunksize=None)
connection.commit
values = values.T
print(values)
return values
def get_temp_values(self):
logger.debug('perform function')
connection = sqlite3.connect(database)
tempvalues = "SELECT date,temp FROM temphumidtable"
tempdata = read_sql(tempvalues, con=connection, coerce_float=True, params=None, parse_dates=None, columns=None,
chunksize=None)
tempdata['date'] = to_datetime(tempdata['date'], format='%Y/%m/%d %H:%M:%S')
tempdata = tempdata.sort_values(by='date')
tempdata = tempdata.iloc[1::20, :]
tempdata = tempdata.replace(0, 'nan')
tempdata.dropna(axis=0, how='any', inplace=True)
return tempdata
class Window(QDialog):
'''
Main Class that defines the main window after program start with all the buttons
'''
register_matplotlib_converters()
# set name of the database - using sqlite for not that is tored in the same folder as the code
# --------------------------------------------------------
global database
database = "data1.db"
logger.debug('set database to ' + database)
# --------------------------------------------------------
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.setWindowTitle('Resplor v. ' + myVersion)
self.setWindowFlags(
self.windowFlags() | QtCore.Qt.WindowMinimizeButtonHint )
# a figure instance to plot on
# self.setStyleSheet("background-color:lightyellow;")
self.resize(300,300)
self.move(100,100)
# Just some button connected to `plot` method
self.buttonsql = QPushButton('SQL query')
self.buttonsql.clicked.connect(self.sqlquery)
self.buttonstd = QPushButton('Standards')
self.buttonstd.clicked.connect(self.stdtab)
self.buttonsamples = QPushButton('Samples')
self.buttonsamples.clicked.connect(self.samplestaba)
self.buttonsearch = QPushButton('Search')
self.buttonsearch.clicked.connect(self.searchtab)
self.buttondeleterun = QPushButton('Delete Run Data')
self.buttondeleterun.clicked.connect(self.deltab)
self.buttonoutput = QPushButton('Output')
self.buttonoutput.clicked.connect(self.outputtab)
self.buttonoptions = QPushButton('Options')
self.buttonoptions.clicked.connect(self.optiontab)
self.image = QLabel(self)
pixmap = QtGui.QPixmap("speichern.png")
#pixmap.fill(Qt.transparent)
self.image.setPixmap(pixmap)
self.image.setAlignment(Qt.AlignCenter)
self.image.setToolTip('Drop Excel Files here')
# generate Layout
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.buttonsamples)
self.vbox.addWidget(self.buttonstd)
self.vbox.addWidget(self.buttonsearch)
self.vbox.addWidget(self.buttonsql)
self.vbox.addWidget(self.buttondeleterun)
self.vbox.addWidget(self.buttonoutput)
self.vbox.addWidget(self.buttonoptions)
self.vbox.addWidget(self.image)
self.setLayout(self.vbox)
self.setAcceptDrops(True)
# self.dialogopen = False
# self.infodialogopen = False
# self.roweditX.setText('finishdate')
# self.roweditY.setText('o18gas')
# self.nameedit.setText('Ag3PO4')
# self.tableedit.setItem('opod')
def getfinishdate(self, value, valuename):
logger.debug('perform function')
valuef = int(value)
connection = sqlite3.connect(database)
sqlsynt = "SELECT finishdate FROM " + self.tabletoload + " WHERE " + valuename + " LIKE " + str(valuef)
datedf = read_sql(sqlsynt, con=connection, coerce_float=True, params=None, parse_dates=None, columns=None,
chunksize=None)
connection.commit
print(datedf.finishdate.values)
return datedf.finishdate.values[0]
def get_temp_values(self):
logger.debug('perform function')
connection = sqlite3.connect(database)
tempvalues = "SELECT date,temp FROM temphumidtable"
tempdata = read_sql(tempvalues, con=connection, coerce_float=True, params=None, parse_dates=None, columns=None,
chunksize=None)
tempdata['date'] = to_datetime(tempdata['date'], format='%Y/%m/%d %H:%M:%S')
tempdata = tempdata.sort_values(by='date')
tempdata = tempdata.iloc[1::20, :]
tempdata = tempdata.replace(0, 'nan')
tempdata.dropna(axis=0, how='any', inplace=True)
return tempdata
def geklickt(self):
logger.debug('perform function')
print()
def delzero(self):
logger.debug('perform function')
self.plotdf = self.plotdf.replace(0, nan) # set zero to nan
self.plotdialog.done(0)
self.makeplot()
def dropna(self):
logger.debug('perform function')
try:
self.plotdf.dropna(axis=0, how='any', inplace=True) #
self.plotdialog.done(0)
self.makeplot()
except Exception as e:
message = 'there are probs droping na values' + e
self.open_infodialog(message)
def dragEnterEvent(self, event):
logger.debug('perform function')
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
logger.debug('perform function')
for url in event.mimeData().urls():
file = url.toLocalFile()
logger.debug('File dropped: ' + file)
if os.path.isfile(file):
print(file)
# self.editbox.setText(file)
self.importfile = file
self.sheetErzeugen()
def sheetErzeugen(self):
# runs when a excel sheet is dropped onto the drop field
logger.debug('perform function')
logger.debug('excel file has been dropped onto the drop field')
self.samshe = Samplesheet() # instantiate samplesheet
logger.debug('instantiate sample sheet for new data')
print("methode sheeterzeugen - samplesheet erstellt")
logger.debug('methode sheeterzeugen - samplesheet erstellt')
file = self.importfile
self.db_anlegen()
try:
self.samshe.load(file)
except Exception as e:
message = 'Fehler in der Formatierung ' + str(e)
self.open_infodialog(message)
def sqlquery(self):
logger.debug('perform function')
file = 'sql query'
sqldialog = SqlDialog(self, database)
# sqldialog.resize(700, 300)
sqldialog.show()
def stdtab(self):
logger.debug('perform function')
self.dialog = SampleDialog(self)
self.dialog.changelayout2()
self.dialog.show()
def samplestaba(self):
logger.debug('perform function')
self.dialog = SampleDialog(self)
self.dialog.changelayout()
self.dialog.show()
def searchtab(self):
logger.debug('perform function')
self.searchwindow = SearchWindow()
self.searchwindow.show()
def outputtab(self):
logger.debug('perform function')
self.dialog = SampleDialog(self)
self.dialog.changelayout3()
self.dialog.show()
def deltab(self):
logger.debug('perform function')
self.dialog_del = SampleDialog(self)
self.dialog_del.changelayout_delrun()
self.dialog_del.show()
def optiontab(self):
logger.debug('perform function')
self.dialog = QDialog()
self.dialog.setStyleSheet("background-color:lightyellow;")
self.dialog.setWindowTitle('Options')
self.layout = QVBoxLayout(self.dialog)
self.Hlayout = QHBoxLayout()
self.H2layout = QHBoxLayout()
label = QLabel('Set DPI')
self.dpiedit = QLineEdit('100')
self.dpiedit.setAlignment(QtCore.Qt.AlignCenter)
self.savebtn = QPushButton('Save')
#self.delbtn = QPushButton('Delete Run')
self.Hlayout.addWidget(label)
self.Hlayout.addWidget(self.dpiedit)
self.Hlayout.addWidget(self.savebtn)
self.layout.addLayout(self.Hlayout)
#self.H2layout.addWidget(self.delbtn)
self.layout.addLayout(self.H2layout)
self.savebtn.clicked.connect(self.save_dpi)
#self.delbtn.clicked.connect(self.deltab)
self.dialog.show()
def save_dpi(self):
logger.debug('perform function')
global dpi
dpi = int(self.dpiedit.text())
print('new dpi value:' , dpi)
def open_new_dialog(self, title, origin, model):
logger.debug('perform function')
if origin == 'standard':
self.dialog = NewDialog(self, title)
self.dialog.tableview.setModel(model)
self.dialog.show()
# or 'opea'
if (origin == 'opea'):
if self.eadialog is None:
self.opeadialog = NewDialog(self, title)
self.opeadialog.tableview.setModel(model)
self.opeadialog.resize(900, 350)
self.opeadialog.move(100, 100)
self.opeadialog.show()
if self.opeadialog is not None:
self.opeadialog.tableview.setModel(model)
self.opeadialog.show()
if (origin == 'ea'):
if self.eadialog is None:
self.eadialog = NewDialog(self, title)
self.eadialog.tableview.setModel(model)
self.eadialog.resize(900, 350)
self.eadialog.move(100, 100)
self.eadialog.show()
if self.eadialog is not None:
self.eadialog.tableview.setModel(model)
self.eadialog.show()
if (origin == 'cnmd'):
self.cnmddialog = NewDialog(self, title)
self.cnmddialog.tableview.setModel(model)
self.cnmddialog.show()
if (origin == 'cnod'):
self.cnmddialog = NewDialog(self, title)
self.cnmddialog.tableview.setModel(model)
self.cnmddialog.show()
if (origin == "plot"):
plotdialog = NewDialog(self, title)
plotdialog.tableview.setModel(model)
plotdialog.resize(220, 400)
plotdialog.move(100, 100)
delzerobutton = QPushButton('zero -> NaN')
delzerobutton.clicked.connect(self.delzero)
dropnabutton = QPushButton('drop NaN')
dropnabutton.clicked.connect(self.dropna)
hbox = QHBoxLayout()
hbox.addWidget(delzerobutton)
hbox.addWidget(dropnabutton)
plotdialog.layout.addLayout(hbox)
self.plotdialog = plotdialog
self.plotdialog.show()
if origin == "opmd":
self.oprawdialog = NewDialog(self, title)
self.oprawdialog.tableview.setModel(model)
self.oprawdialog.show()
# if (origin == "opraw" and self.oprawdialog is not None):
# self.oprawdialog.tableview.setModel(model)
# .oprawdialog.show()
if origin == "opod":
self.opoddialog = NewDialog(self, title)
self.opoddialog.tableview.setModel(model)
self.opoddialog.show()
# if (origin == "opod" and self.opoddialog is not None):
# self.opoddialog.tableview.setModel(model)
# self.opoddialog.show()
def open_infodialog(self, message):
logger.debug('perform function')
self.fehler = InfoDialog(self, message)
self.fehler.show()
def db_anlegen(self):
logger.debug('perform function')
if not os.path.exists(database):
print("Datenbank data.db nicht vorhanden - Datenbank wird anglegt.")
connection = sqlite3.connect(database)
cursor = connection.cursor()
# Tabelle erzeugen
# sql = "CREATE TABLE rawtableco (id INT PRIMARY KEY, name text NOT NULL, weight FLOAT,\
# finishdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,finishmax TIMESTAMP DEFAULT CURRENT_TIMESTAMP,beamheight FLOAT,dO18gas FLOAT,\
# dO18drift FLOAT,dO18 FLOAT,dN15 FLOAT,dN15drift FLOAT,dC13 FLOAT,dC13drift FLOAT,\
# c FLOAT, n FLOAT,cnratio FLOAT,cfact FLOAT,nfact FLOAT, UNIQUE(finishdate,name))"
rawtableco = "CREATE TABLE rawtableco (idraw INT,superid text PRIMARY KEY, name text NOT NULL,sampletype text,finishdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,peakid INT,time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,width TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\
height FLOAT ,area FLOAT,ratio2928 FLOAT,ratio2928raw FLOAT,ratio3028 FLOAT,ratio3028raw FLOAT,c13gas FLOAT,std13C FLOAT,\
o18gas FLOAT,o18vsmowmd FLOAT,bsC13gas FLOAT,c13gasdrift FLOAT,c13 FLOAT,stddiffc13 FLOAT,bsO18gas FLOAT,o18gasdrift FLOAT,stddiffdO18 FLOAT,quality INT,final INT, comment text, extra INT, filename TEXT)"
opodtable = "CREATE TABLE opodtable (id INT PRIMARY KEY, name text NOT NULL ,finishdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,opercent FLOAT, oarea FLOAT,height FLOAT,sampletype TEXT,o18gas FLOAT,o18vsmowod FLOAT,runid TEXT,filename TEXT,quality INT,final INT, comment text, extra INT)"
#primary key auf superid und filename ausweiten
opmd = "CREATE TABLE opmd (idraw INT,superid text , name text NOT NULL,sampletype text,notes text,finishdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,weight float,peakid INT,time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ,width TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\
height FLOAT ,area FLOAT,ratio2928 FLOAT,ratio2928raw FLOAT,ratio3028 FLOAT,ratio3028raw FLOAT,c13gas FLOAT,std13C FLOAT,\
o18gas FLOAT,o18vsmowmd FLOAT,bsC13gas FLOAT,c13gasdrift FLOAT,c13 FLOAT,stddiffc13 FLOAT,bsO18gas FLOAT,o18gasdrift FLOAT,stddiffdO18 FLOAT,quality INT,final INT, comment text, extra INT, filename TEXT, PRIMARY KEY (superid,filename)"
#primary key auf id und filename ausweiten
opod = "CREATE TABLE opod (id INT , name text NOT NULL ,notes TEXT,finishdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,weight FLOAT, opercent FLOAT, oarea FLOAT,height FLOAT,sampletype TEXT,o18gas FLOAT,o18vsmowod FLOAT,runid TEXT,filename TEXT,quality INT,final INT, comment text, extra INT, PRIMARY KEY (id,filename))"
cnmd = "CREATE TABLE cnmd (idraw INT,superid text ,name text NOT NULL,sampletype text,notes text,finishdate TIMESTAMP CURRENT_TIMESTAMP,weight float,peakid INT,time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,width TIMESTAMP DEFAULT CURRENT_TIMESTAMP,height FLOAT,area FLOAT,ratio2928 FLOAT,ratio2928raw FLOAT,n15gas FLOAT,stdn15air FLOAT,n15gasdrift FLOAT,n15aircali FLOAT,ratio4544 FLOAT,ratio4544raw FLOAT,ratio4644 FLOAT,ratio4644raw FLOAT,c13gas FLOAT,stdc13vpdb FLOAT,c13gasdrift FLOAT,c13vpdbcali FLOAT,runid TEXT,filename TEXT,quality INT,final INT, comment text, extra INT, PRIMARY KEY(superid , filename))"
cnod = "CREATE TABLE cnod (id INT ,sampletype TEXT, name text NOT NULL ,notes text, finishdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,weight float, areac INT,cpercent FLOAT,arean INT,npercent FLOAT,nheight FLOAT,nisoarea FLOAT, n15gas FLOAT, n15drift FLOAT,n15air FLOAT,cheight FLOAT,cisoarea FLOAT, c13gas FLOAT, c13drift FLOAT,c13vpdb FLOAT,runid TEXT,filename TEXT,quality INT,final INT, comment text, extra INT, PRIMARY KEY(id,filename))"
rawtablecn = "CREATE TABLE rawtablecn (idraw INT,superid text PRIMARY KEY,name text NOT NULL,sampletype text,finishdate TIMESTAMP CURRENT_TIMESTAMP,peakid INT,time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,width TIMESTAMP DEFAULT CURRENT_TIMESTAMP,height FLOAT,area FLOAT,ratio2928 FLOAT,ratio2928raw FLOAT,n15gas FLOAT,stdn15air FLOAT,n15gasdrift FLOAT,n15aircali FLOAT,ratio4544 FLOAT,ratio4544raw FLOAT,ratio4644 FLOAT,ratio4644raw FLOAT,c13gas FLOAT,stdc13vpdb FLOAT,c13gasdrift FLOAT,c13vpdbcali FLOAT,runid TEXT,filename TEXT,quality INT,final INT, comment text, extra INT)"
cnodtable = "CREATE TABLE cnodtable (id INT PRIMARY KEY,sampletype TEXT, name text NOT NULL ,finishdate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,areac INT,cpercent FLOAT,arean INT,npercent FLOAT,nheight FLOAT,nisoarea FLOAT, n15gas FLOAT, n15drift FLOAT,n15air FLOAT,cheight FLOAT,cisoarea FLOAT, c13gas FLOAT, c13drift FLOAT,c13vpdb FLOAT,runid TEXT,filename TEXT,quality INT,final INT, comment text, extra INT)"
temphumidtable = "CREATE TABLE temphumidtable (date TIMESTAMP DEFAULT CURRENT_TIMESTAMP PRIMARY KEY, seconds FLOAT, temp FLOAT, humid FLOAT )"
metadata = "CREATE TABLE metadata (manr INT PRIMARY KEY, name TEXT , fundland TEXT, fundort TEXT, fundplatz TEXT, datierung TEXT,skelettelement TEXT, geschlecht TEXT , tierart TEXT, altermin INT , altermax INT, ausbeute FLOAT ,bemerkung TEXT, mams INT)"
cursor.execute(opod)
cursor.execute(opmd)
cursor.execute(cnod)
cursor.execute(cnmd)
cursor.execute(temphumidtable)
cursor.execute(metadata)
connection.commit()
def setruns(self):
logger.debug('perform function')
a = 0
connection = sqlite3.connect(database)
c = connection.cursor()
# c.execute("SELECT finishdate FROM opodtable")
# finishdates = c.fetchall()
# for x in finishdates:
# print(x)
finishdates = "SELECT finishdate , id FROM opod"
datedf = read_sql(finishdates, con=connection, coerce_float=True, params=None, parse_dates=None, columns=None,
chunksize=None)
datedf = datedf.sort_values(by='finishdate')
datedf['finishdate'] = to_datetime(datedf.finishdate)
datedf['runid'] = 1
#print(datedf)
#print(datedf.dtypes)
while a < 20:
pos = datedf.iloc[a]
print(pos)
a += 1
def setrunid(self, runid):
logger.debug('perform function')
connection = sqlite3.connect(database)
c = connection.cursor()
setrunid = "INSERT INTO opod(runid) VALUE " + runid
c.execute(setrunid)
c.close()
connection.commit()
print('runid inserted')
def getrunid(self):
logger.debug('perform function')
connection = sqlite3.connect(database)
c = connection.cursor()
try:
getlastidop = "SELECT MAX(runid) FROM opod"
getlastidcn = "SELECT MAX(runid) FROM cnod"
c.execute(getlastidop)
lastidop = c.fetchall()
c.execute(getlastidcn)
lastidcn = c.fetchall()
if lastidop > lastidcn:
newid = lastidop + 1
else:
newid = lastidcn + 1
print('actual runid:' + newid)
return newid
except:
print('no runid in table, lastid automaticaly set to 0')
return 0
def get_triples(self, resultdf, gleiches='set', tocalculate='o18vsmowod', tocalculate2='o18vsmowmd',
tocalculate3='', tocalculate4=''):
logger.debug('perform function')
toignore = ['Blnk'] # ignore all blanks
pos = 0
anfangspos = 0
self.resultdf = resultdf
logger.debug(self.resultdf.head(5))
self.resultdf['set'] = ''
aktuell = self.resultdf.name[0]
logger.debug('aktueller Name: ' + aktuell)
self.triple = []
for inhalt in self.resultdf.name:
#ist der name der folgenden zeile gleich , notiere die id, ansonsten den namen der nächsten
#ist der name der folgende zeile Blnk überspringe diese
if inhalt == aktuell and inhalt != 'Blnk' :
self.triple.append(self.resultdf.id[anfangspos])
pos += 1
else :
self.triple.append(self.resultdf.id[pos])
anfangspos = pos
pos += 1
if inhalt != 'Blnk':
aktuell = inhalt
self.resultdf.set = self.triple
groupedmean = self.resultdf.groupby(gleiches)[tocalculate].mean()
groupedstd = self.resultdf.groupby(gleiches)[tocalculate].std()
groupedmean2 = self.resultdf.groupby(gleiches)[tocalculate2].mean()
groupedstd2 = self.resultdf.groupby(gleiches)[tocalculate2].std()
if tocalculate3 != '':
groupedmean3 = self.resultdf.groupby(gleiches)[tocalculate3].mean()
groupedstd3 = self.resultdf.groupby(gleiches)[tocalculate3].std()
mean3 = groupedmean3.to_frame()
std3 = groupedstd3.to_frame()
meanname3 = tocalculate3 + 'avg'
stdname3 = tocalculate3 + 'std'
mean3.columns = [meanname3]
std3.columns = [stdname3]
self.resultdf = pandas.merge(self.resultdf, mean3, on='set')
self.resultdf = pandas.merge(self.resultdf, std3, on='set')
if tocalculate4 !='':
groupedmean4 = self.resultdf.groupby(gleiches)[tocalculate4].mean()
groupedstd4 = self.resultdf.groupby(gleiches)[tocalculate4].std()
mean4 = groupedmean4.to_frame()
std4 = groupedstd4.to_frame()
meanname4 = tocalculate4 + 'avg'
stdname4 = tocalculate4 + 'std'
mean4.columns = [meanname4]
std4.columns = [stdname4]
self.resultdf = pandas.merge(self.resultdf, mean4, on='set')
self.resultdf = pandas.merge(self.resultdf, std4, on='set')
mean = groupedmean.to_frame()
std = groupedstd.to_frame()
mean2 = groupedmean2.to_frame()
std2 = groupedstd2.to_frame()
meanname = tocalculate + 'avg'
stdname = tocalculate + 'std'
meanname2 = tocalculate2 + 'avg'
stdname2 = tocalculate2 + 'std'
mean.columns = [meanname]
std.columns = [stdname]
mean2.columns = [meanname2]
std2.columns = [stdname2]
self.resultdf = pandas.merge(self.resultdf, mean, on='set')
self.resultdf = pandas.merge(self.resultdf, std, on='set')
self.resultdf = pandas.merge(self.resultdf, mean2, on='set')
self.resultdf = pandas.merge(self.resultdf, std2, on='set')
#print('tripletdata:', self.resultdf)
#print('hier', self.resultdf)
realdataframe = DataFrame(self.resultdf,index=None)
return (realdataframe)
class Samplesheet(object):
def __init__(self):
logger.debug('perform function')
self.origin = ''
# def speichern(self,fields):
def addtodb(self):
logger.debug('perform function')
logger.debug('Inserting imported data into DB')
origin = self.origin
connection = sqlite3.connect(database)
cursor = connection.cursor()
self.tempdf.to_sql('temptable', index=False, con=connection, if_exists='replace')
# depending on the type of file that was imported, decided what query to run
# in order to INSERT those data into the correct table
if origin == 'metadata':
logger.debug('creating query for ' + origin)
qry = "INSERT OR IGNORE INTO metadata (manr , name , fundland , fundort , fundplatz ,datierung, skelettelement ,tierart, geschlecht , bemerkung,mams,altermin )\
SELECT manr , name,fundland,fundort,fundplatz,datierung, skelettelement, tierart, geschlecht, bemerkung, mams,alterm FROM temptable"
logger.debug(qry)
tabletoload = 'metadata'
if origin == 'templog':
logger.debug('creating query for ' + origin)
qry = "INSERT OR IGNORE INTO temphumidtable (date,seconds,temp,humid) \
SELECT date,seconds,temp,humid FROM temptable "
logger.debug(qry)
tabletoload = "temphumidtable"
if origin == 'opmd':
logger.debug('creating query for ' + origin)
qry = "INSERT OR IGNORE INTO opmd (idraw,superid ,name ,sampletype,finishdate, peakid ,time ,width ,\
height,area,ratio2928,ratio2928raw,ratio3028,ratio3028raw,c13gas,std13C,o18gas,bsC13gas ,c13gasdrift,c13,\
stddiffc13,bsO18gas,o18gasdrift,o18vsmowmd,stddiffdO18,filename)\
SELECT Id,superid,Name,SampleType,finishdate,PeakID,Time,Width,Height,Area,ratio2928,ratio2928raw,ratio3028,ratio3028raw,C13gas,Std13C,\
O18gas,bsC13gas,C13gasdrift,C13vpdb,stddiffC13,bsO18gas,O18gasdrift,O18vsmowmd,stddiffdO18,filename FROM temptable"
logger.debug(qry)
tabletoload = "opmd"
if origin == 'opod':
logger.debug('creating query for ' + origin)
qry = "INSERT OR IGNORE INTO opod(id, name, finishdate,sampletype,opercent,oarea, height, o18gas, o18vsmowod ,filename)\