-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKCWI_Cal_Gui.sin
More file actions
executable file
·475 lines (400 loc) · 18.9 KB
/
KCWI_Cal_Gui.sin
File metadata and controls
executable file
·475 lines (400 loc) · 18.9 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
#! @KPYTHON3@
import sys, os, subprocess
from PyQt5.QtWidgets import QWidget, QHBoxLayout,QTableWidget, QTableWidgetItem, QVBoxLayout, QRadioButton
from PyQt5.QtWidgets import QPushButton, QCheckBox, QLineEdit, QLabel, QApplication, QTextEdit
from pymongo import MongoClient
from PyQt5 import QtCore
from PyQt5 import QtGui
#from ConfigManager import save_state, state_file_name
#from QtCore import QStringList
class KCWIConfig():
def __init__(self, configurationName, programId):
self.configurationName = configurationName
self.programId = programId
# format is : kcwi script/keyword, database keyword, True if mandatory,False if optional
self.elements = {
'1': ['statenam','statenam',True],
'2': ['image_slicer','image_slicer',False],
'3': ['filterb','filterb',False],
'4': ['gratingb','gratingb',False],
'5': ['nsmaskb','nsmaskb',False],
'6': ['ampmodeb','ampmodeb',False],
'7': ['gainmulb','gainmulb',False],
'8': ['ccdmodeb','ccdmodeb',False],
'9': ['binningb','binningb',False],
'10':['cal_mirror','cal_mirror',False],
'11':['polarizer','polarizer',False],
'12':['cwaveb','cwaveb',False],
'13':['pwaveb','pwaveb',False],
'14':['progname','progname',False],
'15':['camangleb','camangleb',False],
'16':['focusb','focusb',False]
}
self.server = 'observinglogs:27017'
self.retrieveConfiguration()
def retrieveConfiguration(self):
try:
client = MongoClient(self.server)
db = client.KCWI
print("Retrieving configuration %s of program %s" % (self.configurationName, self.programId))
self.configuration = db.Configurations.find_one({'statenam': self.configurationName,'progname': self.programId})
client.close()
except:
print("Error connecting to the configuration database")
return
self.configurationDetails = {}
print(self.configuration)
for key in self.elements.keys():
kcwi_keyword = self.elements[key][0]
mongo_keyword = self.elements[key][1]
required = self.elements[key][2]
if required:
try:
self.configurationDetails[mongo_keyword] = self.configuration[mongo_keyword]
except Exception as e:
raise KeyError("Missing keyword %s" % (e))
else:
try:
self.configurationDetails[mongo_keyword] = self.configuration[mongo_keyword]
except:
self.configurationDetails[mongo_keyword] = ""
self.configurationDetails['id'] = str(self.configuration['_id'])
def stateFileName(self):
id = str(self.configuration['_id']).replace(" ", "-")
name = str(self.configuration['statenam']).replace(" ", "-")
program = str(self.configuration['progname']).replace(" ", "-")
return os.path.join(program+"___"+name+".state")
def save_state(self, outputDir):
output = ''
sys.stdout.write( "Producing save_state file\n")
outfile = os.path.join(outputDir,self.stateFileName())
stateFile = open(outfile, 'w')
for key in self.elements.keys():
kcwi_keyword = self.elements[key][0]
mongo_keyword = self.elements[key][1]
try:
value = self.configurationDetails[mongo_keyword]
if value !="":
output += "%s = %s\n" % (kcwi_keyword, value)
sys.stdout.write( "%s = %s\n" % (kcwi_keyword, value))
stateFile.write( "%s = %s\n" % (kcwi_keyword, value))
except:
pass
id = str(self.configuration['_id']).replace(" ", "-")
id = id.replace("/","-")
stateFile.write( "%s = %s\n" % ("stateid",str(id)))
stateFile.close()
return output
def save_state(stateName, programId, outputDir):
kcwi = KCWIConfig(stateName, programId)
output = kcwi.save_state(outputDir)
return output
def state_file_name(stateName, programId):
kcwi = KCWIConfig(stateName, programId)
fileName = kcwi.stateFileName()
return fileName
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'KCWI Calibration GUI'
self.left = 50
self.right = 50
self.width = 1000
self.height = 600
self.programId = ''
#self.runMode = 'debug'
self.runMode = ''
self.caltype = 'all'
self.normal_color = 'LawnGreen'
self.quit_color = 'Red'
self.optional_color = 'Gold'
self.init_ui()
self.processOutput='Click on the right or define'
self.runOutdir()
def init_ui(self):
# program id
self.lbl1 = QLabel('Program ID')
self.program = QLineEdit()
self.program.setFixedWidth(100)
# output directory
self.lbl2 = QLabel('Output directory')
self.outdir = QLineEdit()
self.outdir.setFixedWidth(300)
self.outdir.editingFinished.connect(self.setWorkingDirectory)
# use outdir for output directory
self.useOutdir = QCheckBox('Use KCWI outdir')
self.useOutdir.setCheckState(QtCore.Qt.Checked)
self.useOutdir.clicked.connect(self.runOutdir)
# use current directory
self.usePwd = QCheckBox('Use current directory')
self.usePwd.setCheckState(QtCore.Qt.Unchecked)
self.usePwd.clicked.connect(self.runPwd)
self.hlayout1 = QHBoxLayout()
self.hlayout1.addWidget(self.lbl1)
self.hlayout1.addWidget(self.program)
self.hlayout1.addWidget(self.lbl2)
self.hlayout1.addWidget(self.outdir)
self.hlayout1.addWidget(self.useOutdir)
self.hlayout1.addWidget(self.usePwd)
self.hlayout1.addStretch(3)
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.right, self.width, self.height)
self.createTable()
buttonSize = 250
self.reload = QPushButton('Reload configurations')
self.reload.setStyleSheet("background-color : %s" % self.optional_color)
self.list = QPushButton('List checked configurations')
self.list.setStyleSheet("background-color : %s" % self.optional_color)
self.save = QPushButton('1 - Save states to disk')
self.save.setStyleSheet("background-color : %s" % self.normal_color)
self.genfiles = QPushButton('2 - Generate calibration scripts')
self.genfiles.setStyleSheet("background-color : %s" % self.normal_color)
self.gencals = QPushButton('3 - Generate calibration flat files')
self.gencals.setStyleSheet("background-color : %s" % self.normal_color)
# radio buttons for calibrations
self.hlayout3 = QHBoxLayout()
self.radiobutton = QRadioButton("All")
self.radiobutton.setChecked(True)
self.radiobutton.caltype = "all"
self.radiobutton.toggled.connect(self.on_radio_button_toggled)
self.hlayout3.addWidget(self.radiobutton)
self.radiobutton = QRadioButton("Dome")
self.radiobutton.setChecked(False)
self.radiobutton.caltype = "dome"
self.radiobutton.toggled.connect(self.on_radio_button_toggled)
self.hlayout3.addWidget(self.radiobutton)
self.radiobutton = QRadioButton("Internal")
self.radiobutton.setChecked(False)
self.radiobutton.caltype = "internal"
self.radiobutton.toggled.connect(self.on_radio_button_toggled)
self.hlayout3.addWidget(self.radiobutton)
# use lamp shutters or not
self.useLampShutters = QCheckBox('Use arc lamp shutters (DEFAULT=OFF')
self.useLampShutters.setCheckState(QtCore.Qt.Unchecked)
self.useLampShutters.clicked.connect(self.on_lamp_Shutters_toggled)
self.runcals = QPushButton('4 - Run cals')
self.runcals.setStyleSheet("background-color : %s" % self.normal_color)
self.alldone = QPushButton('Quit')
self.alldone.setStyleSheet("background-color : %s" % self.quit_color)
buttons = [self.reload,self.list,self.save, self.gencals, self.genfiles, self.runcals, self.alldone]
for button in buttons:
button.setFixedWidth(buttonSize)
self.program.textChanged.connect(self.set_program)
self.reload.clicked.connect(self.refresh_data)
self.list.clicked.connect(self.ListConfigs)
self.save.clicked.connect(self.saveStates)
self.genfiles.clicked.connect(self.run_generate_cal_script)
#self.genfiles.clicked.connect(self.showcurrent)
self.gencals.clicked.connect(self.run_generate_cal_files)
self.runcals.clicked.connect(self.run_calibrations)
self.alldone.clicked.connect(self.quit)
self.layout = QVBoxLayout()
self.layout.addLayout(self.hlayout1)
self.layout.addWidget(self.tableWidget)
self.vlayout1 = QVBoxLayout()
#self.vlayout1.addWidget(self.list)
self.vlayout1.addWidget(self.reload)
self.vlayout1.addWidget(self.save)
self.vlayout1.addWidget(self.genfiles)
self.vlayout1.addWidget(self.gencals)
self.vlayout1.addLayout(self.hlayout3)
self.vlayout1.addWidget(self.useLampShutters)
self.vlayout1.addWidget(self.runcals)
self.vlayout1.addWidget(self.alldone)
self.hlayout2 = QHBoxLayout()
self.hlayout2.addLayout(self.vlayout1)
self.output = QTextEdit()
self.hlayout2.addWidget(self.output)
self.layout.addLayout(self.hlayout2)
self.setLayout(self.layout)
self.show()
def quit(self):
self.close()
def set_program(self):
self.programId = self.program.text()
self.refresh_data()
def load_data(self):
try:
client = MongoClient('observinglogs')
db = client.KCWI
print(self.programId)
if self.programId == "":
return
except:
self.showOutput("Warning: there is a problem connecting to the configuration database")
configurations = list(
db.Configurations.find({'progname': self.programId}, {'statenam': 1, 'image_slicer': 1, 'filterb': 1, 'gratingb': 1,
'cwaveb': 1, 'pwaveb': 1, 'binningb': 1}))
client.close()
currentRow = 0
for configuration in configurations:
self.tableWidget.insertRow(currentRow)
print("Setting row %d to %s\n" % (currentRow, configuration['statenam']))
qwidget = QWidget()
checkbox = QCheckBox()
checkbox.setCheckState(QtCore.Qt.Unchecked)
checkbox.setStyleSheet('background-color: Gold')
qhboxlayout = QHBoxLayout(qwidget)
qhboxlayout.addWidget(checkbox)
qhboxlayout.setContentsMargins(0, 0, 0, 0)
qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
self.tableWidget.setCellWidget(currentRow, 0, qwidget)
try:
if 'pwaveb' not in configuration.keys():
configuration['pwaveb'] = configuration['cwaveb']
self.tableWidget.setItem(currentRow, 1, QTableWidgetItem(configuration['statenam']))
self.tableWidget.setItem(currentRow, 2, QTableWidgetItem(configuration['image_slicer']))
self.tableWidget.setItem(currentRow, 3, QTableWidgetItem(configuration['filterb']))
self.tableWidget.setItem(currentRow, 4, QTableWidgetItem(configuration['gratingb']))
self.tableWidget.setItem(currentRow, 5, QTableWidgetItem(configuration['cwaveb']))
self.tableWidget.setItem(currentRow, 6, QTableWidgetItem(configuration['pwaveb']))
self.tableWidget.setItem(currentRow, 7, QTableWidgetItem(configuration['binningb']))
currentRow += 1
except:
self.showOutput('\n *** Problems loading configuration >> %s << ' % configuration['statenam'])
self.color_table()
def refresh_data(self):
self.tableWidget.setRowCount(0)
self.load_data()
def createTable(self):
self.tableWidget = QTableWidget()
self.tableWidget.setColumnCount(8)
self.tableWidget.setRowCount(0)
col_headers = ['Calibrate?','State Name', 'Slicer', 'Blue Filter', 'Blue Grating', 'CWaveB', 'PWaveB', 'Binning']
self.tableWidget.setHorizontalHeaderLabels(col_headers)
self._list=[]
self.load_data()
print("Load data finished")
print(self.tableWidget.rowCount())
def color_table(self):
for row in range(self.tableWidget.rowCount()):
print("setting color of row %d" % row)
if row % 2 == 0:
color = QtGui.QColor(100,149,237)
else:
color = QtGui.QColor(135,206,250)
for j in range(self.tableWidget.columnCount()):
if self.tableWidget.item(row, j) is not None:
self.tableWidget.item(row, j).setBackground(color)
#self.show()
def ListConfigs(self):
checked_list = []
for i in range(self.tableWidget.rowCount()):
if self.tableWidget.cellWidget(i, 0).findChild(type(QCheckBox())).isChecked():
checked_list.append(self.tableWidget.item(i, 1).text())
self.output.setText(str(checked_list))
def saveStates(self):
output = ''
for i in range(self.tableWidget.rowCount()):
if self.tableWidget.cellWidget(i, 0).findChild(type(QCheckBox())).isChecked():
if self.runMode is not 'debug':
currentOutput = save_state(self.tableWidget.item(i, 1).text(),self.program.text(), self.outdir.text())
else:
currentOutput = 'Simulate mode: saving state %s\n' % (self.tableWidget.item(i, 1).text())
output += currentOutput
output += '---------------------------------------------------\n'
else:
# remote the state file if the state is not "checked"
fileName = state_file_name(self.tableWidget.item(i, 1).text(), self.program.text())
if os.path.isfile(fileName):
os.unlink(fileName)
self.showOutput(str(output))
def on_radio_button_toggled(self):
radiobutton = self.sender()
if radiobutton.isChecked():
self.showOutput("Selected mode is %s" % (radiobutton.caltype))
self.caltype = radiobutton.caltype
# this section of the code deals with running processes using the build-in QProcess class
def dataReady(self):
cursor = self.output.textCursor()
cursor.movePosition(cursor.End)
self.processOutput = str(self.process.readAll(), 'utf-8')
cursor.insertText("%s\n" % self.processOutput)
cursor.movePosition(QtGui.QTextCursor.Up if cursor.atBlockStart() else
QtGui.QTextCursor.StartOfLine)
self.output.ensureCursorVisible()
self.output.moveCursor(QtGui.QTextCursor.End)
print(self.processOutput)
def showOutput(self, text):
cursor = self.output.textCursor()
cursor.movePosition(cursor.End)
cursor.insertText(text)
self.output.ensureCursorVisible()
def showcurrent(self):
self.run_command_qprocess('pwd', use_kroot=False)
def onFinished(self, exitCode, exitStatus):
print("Process finished")
self.showOutput("Exit code: %d\n" % exitCode)
self.showOutput("Exit status: %s\n" % exitStatus)
def onStart(self):
print("Process started")
def launchError(self, error):
if error != QtCore.QProcess.Crashed:
self.showOutput("Warning! There was a problem running the requested function.")
def run_command_qprocess(self,command, command_arguments=[], use_kroot=False, csh=False):
if use_kroot is True:
try:
kroot = os.environ['KROOT']
except:
kroot = ''
cmdline = os.path.join(kroot,'rel','default','bin', command)
else:
cmdline = command
print("Running: %s with arguments %s \n" % (cmdline, str(command_arguments)))
self.process = QtCore.QProcess(self)
self.process.setProcessChannelMode(QtCore.QProcess.MergedChannels)
self.process.readyRead.connect(self.dataReady)
self.process.finished.connect(self.onFinished)
self.process.error.connect(self.launchError)
if self.runMode is 'debug':
self.showOutput('Simulation mode\n Running: %s with arguments %s \n' % (cmdline, str(command_arguments)))
else:
self.showOutput('Running: %s with arguments: %s \n' % (cmdline, str(command_arguments)))
if csh is True:
self.process.start('csh', [cmdline])
else:
self.process.start(cmdline, command_arguments)
self.showOutput('Done\n')
self.process.waitForFinished()
def runOutdir(self):
self.run_command_qprocess('outdir',use_kroot=True)
self.usePwd.setCheckState(QtCore.Qt.Unchecked)
self.outdir.setText(self.processOutput.replace("\n",""))
self.setWorkingDirectory()
def runPwd(self):
self.outdir.setText(str(os.getcwd()))
self.useOutdir.setCheckState(QtCore.Qt.Unchecked)
self.setWorkingDirectory()
def on_lamp_Shutters_toggled(self):
if self.useLampShutters.isChecked():
self.output.setText(""" Lamp shutters will be used instead of lamps on/off
Note that this can lead to arc lines contamination on flat fields
Check your flats for possible arc lines contamination""")
else:
self.output.setText("Using power control to turn on/off arc lamps (DEFAULT)")
def setWorkingDirectory(self):
if os.path.isdir(self.outdir.text()):
os.chdir(self.outdir.text())
self.output.setText("Output directory changed to %s\n" % (self.outdir.text()))
else:
self.output.setText("Output directory does not exist\n")
def run_generate_cal_script(self):
if self.useLampShutters.isChecked():
command_arguments=['-use_lamp_shutters']
else:
command_arguments=[]
self.run_command_qprocess('generate_cal_script.py',command_arguments=command_arguments, use_kroot=True)
def run_generate_cal_files(self):
self.run_command_qprocess('generate_cal_files.csh', use_kroot=False, csh=True)
def run_calibrations(self):
if self.caltype == 'all':
script = 'all_calibrations.csh'
elif self.caltype == 'internal':
script = 'nodome_calibrations.csh'
elif self.caltype == 'dome':
script = 'dome_calibrations.csh'
self.run_command_qprocess(script, use_kroot=False, csh=True)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())