-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifySave.py
393 lines (300 loc) · 13.8 KB
/
verifySave.py
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
import os
import errno
from collections import defaultdict
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from gui.generate import Ui_Generate
from gui.validation_error import Ui_Dialog
from qtmodern.styles import dark
from qtmodern.windows import ModernWindow
import datetime
import data_fields
from PyQt5.QtGui import QBrush
def tree(): return defaultdict(tree)
class ValErrDialog(QDialog, Ui_Dialog):
def __init__(self):
super(ValErrDialog, self).__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.on_click)
def on_click(self):
self.close()
class Generate(QWidget, Ui_Generate):
def __init__(self, parent):
super(Generate, self).__init__()
self.setupUi(self)
self.treeWidget.setUniformRowHeights(True)
self.plainTextEdit.setStyleSheet("""QPlainTextEdit {font-family: Courier;}""")
self.populate_review(parent)
self.populate_plainTextEdit(parent)
self.pushButton_cancel.clicked.connect(self.cancel)
self.pushButton_ok.clicked.connect(lambda: self.save(parent))
self.setWindowTitle("Review and Save")
self.setWindowIcon(QtGui.QIcon('icons/icon.png'))
stylesheet = """
QTableWidget {
background-color: rgb(80, 80, 80);
}
QPushButton {
background-color: rgb(90,70,0);
}
QTreeWidget::indicator {
width: 10px;
height: 10px;
margin: 5px;
border-radius: 5px;
border: 3px solid rgb(120,90,0);
}
QTreeWidget::indicator::unchecked {
background-color: transparent rgb(80, 80, 80);
}
QTreeWidget::indicator::checked {
background-color: rgb(150,120,0);
}
QTreeWidget {
background-color: rgb(80, 80, 80);
}
"""
self.setStyleSheet(stylesheet)
self.grip1 = QSizeGrip(self)
self.verticalLayout.addWidget(self.grip1, 0, Qt.AlignRight | Qt.AlignBottom)
def cell_contains_text(self, item):
if item != None:
item_txt = item.text()
if any(chr.isalnum() for chr in item_txt):
return True
else:
return False
else:
return False
def show_valerrordialog(self, incrows):
d = ValErrDialog()
for i in incrows:
# print(i)
d.plainTextEdi_missing_fields.appendPlainText(i)
d.exec_()
def crow2list(self, parent, c_row):
data_row = []
cmethod = parent.comboBox_method.currentText()
# cset5 = parent.comboBox_P5.currentText()
# cset7 = parent.comboBox_P7.currentText()
cinstrument = parent.comboBox_instrument.currentText()
for field in parent.sdata_fields_ss:
if parent.sdata_fields_ss[field]['ss']:
if parent.sdata_fields_ss[field]['c_p'] >= 0:
if field is "N":
column = parent.sdata_fields_ss[field]['c_p']
pwidget = parent.tableWidget_construct.cellWidget(c_row, column)
checkbox = pwidget.findChild(QCheckBox)
state = checkbox.checkState()
# print("state", state)
if state == 2:
data_row.append('NORMAL')
else:
data_row.append('STANDARD')
elif field is 'Group':
item = parent.tableWidget_construct.item(c_row, parent.sdata_fields_ss[field]['c_p'])
if self.cell_contains_text(item):
value = item.text()
value = value.replace(",", "/")
data_row.append(value)
else:
data_row.append('')
else:
item = parent.tableWidget_construct.item(c_row, parent.sdata_fields_ss[field]['c_p'])
if self.cell_contains_text(item):
value = item.text()
data_row.append(value.strip())
else:
data_row.append("")
else:
if field is "Panel_Target":
item = parent.tableWidget_construct.item(c_row, parent.sdata_fields_ss['Panel']['c_p'])
cpanel = ""
if self.cell_contains_text(item):
cpanel = item.text()
value = parent.yconfig['Methods'][cmethod]['Panels'][cpanel]['PanelTarget']
# print(value)
if len(value) > 0:
data_row.append(value.strip())
else:
data_row.append("")
elif field is 'Sample_Name':
item = parent.tableWidget_construct.item(c_row,
parent.sdata_fields_ss['Sample_ID']['c_p'])
if self.cell_contains_text(item):
value = item.text()
# print(value)
data_row.append(value.strip())
else:
data_row.append("")
elif field is 'index2':
item = parent.tableWidget_construct.item(c_row,
parent.sdata_fields_ss['I5_Index_ID']['c_p'])
if self.cell_contains_text(item):
i = item.text().strip()
if i in parent.yindices_mod[cmethod][cinstrument]:
iseq5 = parent.yindices_mod[cmethod][cinstrument][i]
data_row.append(iseq5.strip())
else:
data_row.append('')
else:
data_row.append('')
elif field is 'index':
item = parent.tableWidget_construct.item(c_row,
parent.sdata_fields_ss['I7_Index_ID']['c_p'])
if self.cell_contains_text(item):
i = item.text().strip()
if i in parent.yindices_mod[cmethod][cinstrument]:
iseq7 = parent.yindices_mod[cmethod][cinstrument][i]
data_row.append(iseq7.strip())
else:
data_row.append('')
else:
data_row.append('')
elif field is 'Method':
data_row.append(cmethod.strip())
return data_row
def populate_review(self, parent):
rows = parent.tableWidget_construct.rowCount()
header = []
name2col = {}
i = 0
for key in parent.sdata_fields_ss.keys():
if parent.sdata_fields_ss[key]['ss']:
header.append(key)
name2col[key] = i
i += 1
self.treeWidget.setHeaderLabels(header)
data_dict = tree()
tree_dict = tree()
for row in range(rows):
sample_item = parent.tableWidget_construct.item(row, parent.sdata_fields_ss['Sample_ID']['c_p'])
if self.cell_contains_text(sample_item):
current_row_data = self.crow2list(parent, row)
sample_id = current_row_data[name2col['Sample_ID']]
batch_list = current_row_data[name2col['Group']].split("/")
for batch in batch_list:
data_dict[batch][sample_id] = current_row_data
for batch, subdict in data_dict.items():
batchname = "Group " + batch
if not tree_dict[batch]:
tree_dict[batch] = QTreeWidgetItem(self.treeWidget)
tree_dict[batch].setText(0, batchname)
tree_dict[batch].setFlags(tree_dict[batch].flags()
| Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
for sample_id, current_row_data in subdict.items():
child = QTreeWidgetItem(tree_dict[batch])
for index, value in enumerate(current_row_data):
child.setText(int(index), str(value))
child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
child.setCheckState(0, Qt.Unchecked)
# if current_row_data[name2col["N"]] is "NORMAL":
# child.setBackground(int(index), QBrush(Qt.green))
# else:
# child.setBackground(int(index), QBrush(Qt.yellow))
def populate_plainTextEdit(self, parent):
SampleSheetCreator_settings = QSettings('vll', 'SampleSheetCreator')
rows = parent.tableWidget_construct.rowCount()
samplesheet = []
tmp_date = parent.dateEdit.date()
date_var = tmp_date.toPyDate()
run = parent.lineEdit_run.text()
institute = SampleSheetCreator_settings.value('institute', type=str)
investigator = parent.comboBox_investigator.currentText()
cmethod = parent.comboBox_method.currentText()
description_tmp = parent.plainTextEdit.toPlainText()
description_tmp = description_tmp.replace(",", " ")
description = description_tmp.replace("\n", " ")
header_dict = parent.yconfig['Methods'][cmethod]['Header']
samplesheet.append('[Header]')
for key, value in header_dict.items():
samplesheet.append(','.join([str(key), str(value)]))
samplesheet.append(','.join(["Investigator Name", str(investigator)]))
samplesheet.append(','.join(["Experiment Name", str(run)]))
samplesheet.append(','.join(["Date", str(date_var)]))
samplesheet.append(','.join(["Description", str(description)]))
samplesheet.append(','.join(["Institute", str(institute)]))
samplesheet.append(",")
""" enter settings data """
settings_dict = parent.yconfig['Methods'][cmethod]['Settings']
samplesheet.append('[Settings]')
for key, value in settings_dict.items():
if key != "Reads":
samplesheet.append(','.join([str(key), str(value)]))
samplesheet.append(",")
""" enter reads data """
samplesheet.append('[Reads]')
cmethod = parent.comboBox_method.currentText()
reads_list = parent.yconfig['Methods'][cmethod]['Settings']['Reads']
for read in reads_list:
samplesheet.append(str(read))
samplesheet.append(",")
samplesheet.append('[Data]')
header = []
for key in parent.sdata_fields_ss.keys():
if parent.sdata_fields_ss[key]['ss']:
header.append(key)
header_str = ','.join(header)
samplesheet.append(header_str)
for r in range(rows):
item = parent.tableWidget_construct.item(r, parent.sdata_fields_ss['Sample_ID']['c_p'])
if self.cell_contains_text(item):
data_row = self.crow2list(parent, r)
data_row_str = ','.join(data_row)
samplesheet.append(data_row_str)
for ss_row in samplesheet:
self.plainTextEdit.appendPlainText(ss_row)
def cancel(self):
self.close()
def find_unchecked(self):
unchecked = 0
checked = 0
root = self.treeWidget.invisibleRootItem()
child1_count = root.childCount()
# print("child1",child1_count)
for i in range(child1_count):
child1 = root.child(i)
child2_count = child1.childCount()
# print("child2", child2_count)
for j in range(child2_count):
child2 = child1.child(j)
if child2.checkState(0) == QtCore.Qt.Unchecked:
unchecked += 1
else:
checked += 1
# print(unchecked, checked)
return unchecked, checked
def save(self, parent):
unchecked, checked = self.find_unchecked()
print(unchecked, checked)
if unchecked == 0:
now = datetime.datetime.now()
datetime_str = now.strftime("%Y-%m-%d.%H.%M.%S")
print(datetime_str)
path = parent.lineEdit_path.text()
samplesheet_file = "SampleSheet_" + datetime_str + ".csv"
path_file = os.path.join(path, samplesheet_file)
print(path)
print(path_file)
ss_out = self.plainTextEdit.toPlainText()
if not os.path.isdir(path):
try:
os.makedirs(path)
except OSError:
print("could not create folder")
with open(path_file, "w") as f:
f.write(ss_out)
self.close()
else:
checkstr = "All samples not checked. Unchecked: " + str(unchecked) + ", Checked: " + str(checked)
incomp_data = [checkstr]
self.show_valerrordialog(incomp_data)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Generate = QtWidgets.QDialog()
ui = Ui_Generate()
ui.setupUi(Generate)
Generate.show()
sys.exit(app.exec_())