def add_device_radio_to_widget(self, devices_list): """ add device radio to widget :param devices_list: :return: """ self.clear_devices_radio_btn() self.devices_list = devices_list for device in devices_list: radio = QRadioButton(device.id + " (" + device.description + ")") if device.status != Device.ONLINE: radio.setDisabled(True) self.devices_radio_buttons.append(radio) self.devices_layout.addWidget(radio) # set default checked radio for device_radio in self.devices_radio_buttons: if Device.ONLINE[1] in device_radio.text(): device_radio.setChecked(True) break
class DataItemWidget(QFrame): def __init__(self, data, data_catalogue_client): QFrame.__init__(self) self.data = data self.dataCatalogueClient = data_catalogue_client layout = QHBoxLayout() layout.setMargin(0) self.radioButton = QRadioButton() self.radioButton.toggled.connect(self.radioButtonToggled) layout.addWidget(self.radioButton) self.button = QPushButton() self.button.clicked.connect(self.buttonClicked) self.updateContent() layout.addStretch() layout.addWidget(self.button) self.setLayout(layout) self.setStyleSheet("QFrame { background-color: white; }") if (QgsSettings().value("/kadasrouting/activeValhallaTilesID", "default") == self.data["id"]): self.radioButton.setChecked(True) def updateContent(self): statuses = { DataCatalogueClient.NOT_INSTALLED: [self.tr("Install"), "black", "bold"], DataCatalogueClient.UPDATABLE: [self.tr("Update"), "orange", "bold"], DataCatalogueClient.UP_TO_DATE: [self.tr("Remove"), "green", "bold"], DataCatalogueClient.LOCAL_ONLY: [self.tr("Remove"), "green", "bold italic"], DataCatalogueClient.LOCAL_DELETED: [self.tr("N/A"), "black", "italic"], } status = self.data["status"] date = datetime.datetime.fromtimestamp(self.data["modified"] / 1e3).strftime("%d-%m-%Y") self.radioButton.setText(f"{self.data['title']} [{date}]") self.radioButton.setStyleSheet( f"color: {statuses[status][1]}; font: {statuses[status][2]}") self.button.setText(statuses[status][0]) if status == DataCatalogueClient.LOCAL_ONLY: self.button.setToolTip( self. tr("This map package is local only, if you delete it you can not download it from the selected URL" )) if status == DataCatalogueClient.LOCAL_DELETED: self.button.setEnabled(False) self.button.hide() self.radioButton.setStyleSheet( f"color: {statuses[status][1]}; font: {statuses[status][2]}; text-decoration: line-through" ) # Add addditional behaviour for radio button according to installation status if (status == DataCatalogueClient.NOT_INSTALLED or status == DataCatalogueClient.LOCAL_DELETED): self.radioButton.setDisabled(True) self.radioButton.setToolTip( self.tr("Map package has to be installed first")) else: self.radioButton.setDisabled(False) self.radioButton.setToolTip("") def buttonClicked(self): status = self.data["status"] if status == DataCatalogueClient.UP_TO_DATE: ret = self.dataCatalogueClient.uninstall(self.data["id"]) if not ret: pushWarning( self. tr("Cannot remove previous version of the {name} map package" ).format(name=self.data["title"])) else: pushMessage( self.tr("Map package {name} has been successfully deleted " ).format(name=self.data["title"])) self.data["status"] = DataCatalogueClient.NOT_INSTALLED elif status == DataCatalogueClient.LOCAL_ONLY: ret = self.dataCatalogueClient.uninstall(self.data["id"]) if not ret: pushWarning( self. tr("Cannot remove previous version of the {name} map package" ).format(name=self.data["title"])) else: pushMessage( self.tr("Map package {name} has been successfully deleted " ).format(name=self.data["title"])) self.data["status"] = DataCatalogueClient.LOCAL_DELETED else: ret = self.dataCatalogueClient.install(self.data) if not ret: pushWarning( self.tr("Cannot install map package {name}").format( name=self.data["title"])) else: pushMessage( self.tr( "Map package {name} has been successfully installed "). format(name=self.data["title"])) self.data["status"] = DataCatalogueClient.UP_TO_DATE if ret: self.updateContent() def radioButtonToggled(self): if self.radioButton.isChecked(): # Update Kadas setting QgsSettings().setValue("/kadasrouting/activeValhallaTilesID", self.data["id"]) pushMessage( self.tr("Active map package is set to {tile}").format( tile=self.data["title"]))
class Left_panel(object): def setup_left_panel(self, parent=None): ####################################################### #Create all buttons ####################################################### self.button_positioning = QPushButton('Positioning finished =>', self) self.button_positioning.clicked.connect(self.clickMethod_positioning) self.button_positioning.setStatusTip('Tare the pressure sensor') self.button_positioning.setIconSize(QSize(100, 100)) self.button_positioning.setMaximumSize( 250, 200) #Set the minimum size of the button self.button_positioning.setFont(QFont("Arial", 14, QFont.Bold)) # Add button for taring tarebutton_load = QPushButton('Tare', self) tarebutton_load.clicked.connect(self.clickMethodTare_load) tarebutton_load.setStatusTip('Tare the load sensor') tarebutton_load.setIconSize(QSize(100, 100)) tarebutton_load.setMaximumSize( 100, 200) #Set the minimum size of the button tarebutton_pressure = QPushButton('Tare', self) tarebutton_pressure.clicked.connect(self.clickMethodTare_pressure) tarebutton_pressure.setStatusTip('Tare the pressure sensor') tarebutton_pressure.setIconSize(QSize(100, 100)) tarebutton_pressure.setMaximumSize( 100, 200) #Set the minimum size of the button tarebutton_volume = QPushButton('Tare', self) tarebutton_volume.clicked.connect(self.clickMethodTare_vol) tarebutton_volume.setStatusTip('Tare the pressure sensor') tarebutton_volume.setIconSize(QSize(100, 100)) tarebutton_volume.setMaximumSize( 100, 200) #Set the minimum size of the button tarebutton_disp = QPushButton('Tare', self) tarebutton_disp.clicked.connect(self.clickMethodTare_disp) tarebutton_disp.setStatusTip('Tare the pressure sensor') tarebutton_disp.setIconSize(QSize(100, 100)) tarebutton_disp.setMaximumSize( 100, 200) #Set the minimum size of the button self.button_vol_more = QPushButton('+', self) self.button_vol_more.clicked.connect(self.clickMethod_volMore) self.button_vol_more.setStatusTip('Add volume') self.button_vol_more.setIconSize(QSize(100, 100)) self.button_vol_more.setMaximumSize( 100, 200) #Set the minimum size of the button self.button_vol_less = QPushButton('-', self) self.button_vol_less.clicked.connect(self.clickMethod_volLess) self.button_vol_less.setStatusTip('Remove volume') self.button_vol_less.setIconSize(QSize(100, 100)) self.button_vol_less.setMaximumSize( 100, 200) #Set the minimum size of the button self.button_disp_more = QPushButton('+', self) self.button_disp_more.clicked.connect(self.clickMethod_dispMore) self.button_disp_more.setStatusTip('Add displacement') self.button_disp_more.setIconSize(QSize(100, 100)) self.button_disp_more.setMaximumSize( 100, 200) #Set the minimum size of the button self.button_disp_less = QPushButton('-', self) self.button_disp_less.clicked.connect(self.clickMethod_dispLess) self.button_disp_less.setStatusTip('Remove displacement') self.button_disp_less.setIconSize(QSize(100, 100)) self.button_disp_less.setMaximumSize( 100, 200) #Set the minimum size of the button self.button_disp_0_d = QPushButton('Return to 0', self) self.button_disp_0_d.clicked.connect(self.clickMethod_disp0) self.button_disp_0_d.setStatusTip('Return to 0 mmHg pressure') self.button_disp_0_d.setIconSize(QSize(100, 100)) self.button_disp_0_d.setMaximumSize( 100, 200) #Set the minimum size of the button self.button_disp_0_P = QPushButton('Return to 0', self) self.button_disp_0_P.clicked.connect(self.clickMethod_pres0) self.button_disp_0_P.setStatusTip( 'Return to 0 mm position in displacement') self.button_disp_0_P.setIconSize(QSize(100, 100)) self.button_disp_0_P.setMaximumSize( 100, 200) #Set the minimum size of the button self.button_motor_stop = QPushButton('Stop Motor', self) self.button_motor_stop.clicked.connect(self.clickMethod_motorStop) self.button_motor_stop.setStatusTip('Stop the motor') self.button_motor_stop.setIconSize(QSize(100, 100)) self.button_motor_stop.setMaximumSize( 100, 200) #Set the minimum size of the button self.button_pump_stop = QPushButton('Stop Pump', self) self.button_pump_stop.clicked.connect(self.clickMethod_pumpStop) self.button_pump_stop.setStatusTip('Stop the pump') self.button_pump_stop.setIconSize(QSize(100, 100)) self.button_pump_stop.setMaximumSize( 100, 200) #Set the minimum size of the button ####################################################### #Create all radio buttons ####################################################### #Add a radio button step vol group_vol = QButtonGroup(self.centralWidget) self.step_vol = 1 self.Radio_step_vol1 = QRadioButton("1") group_vol.addButton(self.Radio_step_vol1) self.Radio_step_vol1.setChecked(True) self.Radio_step_vol1.clicked.connect( lambda: self.radio_vol_step(self.Radio_step_vol1)) self.Radio_step_vol2 = QRadioButton("2") group_vol.addButton(self.Radio_step_vol2) self.Radio_step_vol2.clicked.connect( lambda: self.radio_vol_step(self.Radio_step_vol2)) self.Radio_step_vol5 = QRadioButton("5") group_vol.addButton(self.Radio_step_vol5) self.Radio_step_vol5.clicked.connect( lambda: self.radio_vol_step(self.Radio_step_vol5)) #Add a radio button step disp group_disp = QButtonGroup(self.centralWidget) self.step_disp = 1 self.Radio_step_disp1 = QRadioButton("1") self.Radio_step_disp1.setChecked(True) self.Radio_step_disp1.clicked.connect( lambda: self.radio_disp_step(self.Radio_step_disp1)) group_disp.addButton(self.Radio_step_disp1) self.Radio_step_disp2 = QRadioButton("2") self.Radio_step_disp2.clicked.connect( lambda: self.radio_disp_step(self.Radio_step_disp2)) group_disp.addButton(self.Radio_step_disp2) self.Radio_step_disp5 = QRadioButton("5") self.Radio_step_disp5.clicked.connect( lambda: self.radio_disp_step(self.Radio_step_disp5)) group_disp.addButton(self.Radio_step_disp5) ####################################################### # Creation labels ####################################################### self.label_dir = QLabel("Results directory: ") self.label_dir.setFont(QFont("Arial", 10, QFont.Bold)) self.label_dir.setFont(QFont("Arial", 10, QFont.Bold)) self.label_connection = QLabel("Connections: ") self.label_connection.setFont(QFont("Arial", 10, QFont.Bold)) self.pixmap_0 = QPixmap() self.pixmap_0.load( resource_path('tension_inflation/resources/nottick.png')) self.pixmap_0 = self.pixmap_0.scaledToWidth(20) self.pixmap_1 = QPixmap() self.pixmap_1.load( resource_path('tension_inflation/resources/tick.png')) self.pixmap_1 = self.pixmap_1.scaledToWidth(20) self.label_ard = QLabel() self.label_ard.setPixmap(self.pixmap_0) self.label_ard.setAlignment(Qt.AlignLeft) self.label_mot = QLabel() self.label_mot.setPixmap(self.pixmap_0) self.label_pum = QLabel() self.label_pum.setPixmap(self.pixmap_0) label_pressure_title = QLabel() label_pressure_title.setText("Pressure") label_pressure_title.setAlignment(Qt.AlignCenter) label_pressure_title.setFont(QFont("Arial", 20, QFont.Bold)) label_volume_title = QLabel() label_volume_title.setText("Volume") label_volume_title.setAlignment(Qt.AlignCenter) label_volume_title.setFont(QFont("Arial", 20, QFont.Bold)) label_load_title = QLabel() label_load_title.setText("Load") label_load_title.setAlignment(Qt.AlignCenter) label_load_title.setFont(QFont("Arial", 20, QFont.Bold)) label_disp_title = QLabel() label_disp_title.setText("Disp") label_disp_title.setAlignment(Qt.AlignCenter) label_disp_title.setFont(QFont("Arial", 20, QFont.Bold)) #Create label: display values self.label_pressure_display = QLabel() self.label_pressure_display.setText("Connecting") self.label_pressure_display.setAlignment(Qt.AlignCenter) self.label_pressure_display.setFont(QFont( "Arial", 16, )) self.label_volume_display = QLabel() self.label_volume_display.setText("Unavailable") self.label_volume_display.setAlignment(Qt.AlignCenter) self.label_volume_display.setFont(QFont( "Arial", 16, )) self.label_load_display = QLabel() self.label_load_display.setText("Connecting") self.label_load_display.setAlignment(Qt.AlignCenter) self.label_load_display.setFont(QFont( "Arial", 16, )) self.label_disp_abs_display = QLabel() self.label_disp_abs_display.setText("Connecting") self.label_disp_abs_display.setAlignment(Qt.AlignCenter) self.label_disp_abs_display.setFont(QFont( "Arial", 8, )) self.label_disp_rel_display = QLabel() self.label_disp_rel_display.setText("Connecting") self.label_disp_rel_display.setAlignment(Qt.AlignCenter) self.label_disp_rel_display.setFont(QFont( "Arial", 16, )) self.label_phase = QLabel() self.label_phase.setText("Phase : Positioning") self.label_phase.setAlignment(Qt.AlignLeft) self.label_phase.setFont(QFont("Arial", 24, QFont.Bold)) self.label_phase.setStyleSheet("background-color: QColor(200, 0, 0)") label_step_vol = QLabel() label_step_vol.setText("Step") label_step_vol.setAlignment(Qt.AlignCenter) label_step_vol.setFont(QFont( "Arial", 16, )) label_step_disp = QLabel() label_step_disp.setText("Step") label_step_disp.setAlignment(Qt.AlignCenter) label_step_disp.setFont(QFont( "Arial", 16, )) ####################################################### # Creation of the different composent of the window (Layout !!) ####################################################### #Creation of a line of separation sepH = [QFrame() for i in range(10)] for obj in sepH: obj.setFrameShape(QFrame.HLine) #Vertical line obj.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) obj.setFrameShadow(QFrame.Sunken) obj.setLineWidth(1) sepV = [QFrame() for i in range(10)] for obj in sepV: obj.setFrameShape(QFrame.VLine) #Vertical line obj.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) obj.setFrameShadow(QFrame.Sunken) obj.setLineWidth(1) ################################## #Layout volume vertical box_volume_pm = QHBoxLayout() box_volume_pm.addWidget(self.button_vol_more) box_volume_pm.addWidget(self.button_vol_less) ############### box_volume_step = QHBoxLayout() box_volume_step.addWidget(label_step_vol) box_radio_vol = QVBoxLayout() box_radio_vol.addWidget(self.Radio_step_vol1) box_radio_vol.addWidget(self.Radio_step_vol2) box_radio_vol.addWidget(self.Radio_step_vol5) box_volume_step.addLayout(box_radio_vol) ############### #Layout disp vertical ############### box_disp_rel_abs_display = QVBoxLayout() box_disp_rel_abs_display.addWidget(self.label_disp_rel_display) box_disp_rel_abs_display.addWidget(self.label_disp_abs_display) ############### box_disp_pm = QHBoxLayout() box_disp_pm.addWidget(self.button_disp_more) box_disp_pm.addWidget(self.button_disp_less) ############### box_disp_step = QHBoxLayout() box_disp_step.addWidget(label_step_disp) box_radio_disp = QVBoxLayout() box_radio_disp.addWidget(self.Radio_step_disp1) box_radio_disp.addWidget(self.Radio_step_disp2) box_radio_disp.addWidget(self.Radio_step_disp5) box_disp_step.addLayout(box_radio_disp) ############### n = 0 panel_grid = QGridLayout() panel_grid.setSpacing(10) panel_grid.addWidget(label_pressure_title, 0, n) panel_grid.addWidget(sepH[0], 1, n) panel_grid.addWidget(self.label_pressure_display, 2, n, Qt.AlignRight) panel_grid.addWidget(tarebutton_pressure, 3, n, Qt.AlignCenter) panel_grid.addWidget(self.button_disp_0_P, 4, n, Qt.AlignCenter) panel_grid.addWidget(sepV[0], 0, 1, 10, 1) n = 2 panel_grid.addWidget(label_volume_title, 0, n) panel_grid.addWidget(sepH[1], 1, n) panel_grid.addWidget(self.label_volume_display, 2, n) panel_grid.addWidget(tarebutton_volume, 3, n, Qt.AlignCenter) panel_grid.addLayout(box_volume_pm, 4, n) panel_grid.addLayout(box_volume_step, 5, n) panel_grid.addWidget(self.button_pump_stop, 6, n, Qt.AlignCenter) panel_grid.addWidget(sepV[1], 0, 3, 10, 1) n = 4 panel_grid.addWidget(label_load_title, 0, n) panel_grid.addWidget(sepH[2], 1, n) panel_grid.addWidget(self.label_load_display, 2, n, Qt.AlignCenter) panel_grid.addWidget(tarebutton_load, 3, n, Qt.AlignCenter) panel_grid.addWidget(sepV[2], 0, 5, 10, 1) n = 6 panel_grid.addWidget(label_disp_title, 0, n) panel_grid.addWidget(sepH[3], 1, n) panel_grid.addLayout(box_disp_rel_abs_display, 2, n) panel_grid.addWidget(tarebutton_disp, 3, n, Qt.AlignCenter) panel_grid.addLayout(box_disp_pm, 4, n) panel_grid.addLayout(box_disp_step, 5, n) panel_grid.addWidget(self.button_disp_0_d, 6, n, Qt.AlignCenter) panel_grid.addWidget(self.button_motor_stop, 7, n, Qt.AlignCenter) panel_grid.setColumnMinimumWidth(0, 140) panel_grid.setColumnMinimumWidth(2, 140) panel_grid.setColumnMinimumWidth(4, 140) panel_grid.setColumnMinimumWidth(6, 140) layout_pos = QHBoxLayout() layout_pos.addWidget(self.label_phase) layout_pos.addSpacing(20) layout_pos.addWidget(self.button_positioning) panel_layout = QVBoxLayout() panel_layout.addLayout(layout_pos) panel_layout.addStretch() panel_layout.addSpacing(100) panel_layout.addStretch() panel_layout.addLayout(panel_grid) panel_layout.addStretch() #------------------------------------------- #Add the connection visuals to the panel dir_layout = QHBoxLayout() dir_layout.addWidget(self.label_dir) dir_layout.addWidget(QLabel(self.path + "/")) dir_layout.addStretch(1) ard_layout = QHBoxLayout() ard_layout.addWidget(self.label_ard) ard_layout.addWidget(QLabel(' Arduino')) ard_layout.addStretch(1) mot_layout = QHBoxLayout() mot_layout.addWidget(self.label_mot) mot_layout.addWidget(QLabel(' Motor PI')) mot_layout.addStretch(1) pum_layout = QHBoxLayout() pum_layout.addWidget(self.label_pum) pum_layout.addWidget(QLabel(' Seringe pump')) pum_layout.addStretch(1) panel_layout.addLayout(dir_layout) panel_layout.addWidget(self.label_connection) panel_layout.addLayout(ard_layout) panel_layout.addLayout(mot_layout) panel_layout.addLayout(pum_layout) #------------------------------------------- self.panel_control_layout = panel_layout self.connectionCall() ############################################### #Function button ############################################### def clickMethod_positioning(self): """Method to """ msg = QMessageBox.question(self, "End of positioning", "Do you want to pass to the Test ?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if msg == QMessageBox.No: return self.test_phase() self.label_phase.setText("Phase: Test command") # QMessageBox.about(self, "Run the engine:", "The positioning is now finished.\n\nThe test phase will start, when you are ready clic on the white arrow") def connectionCall(self): """Function to connect to pump motor and arduino""" try: Arduino.connect() except: print("arduino connection problem") if Arduino.isconnected(): self.label_ard.setPixmap(self.pixmap_1) else: self.label_ard.setPixmap(self.pixmap_0) try: Pump_seringe.connect() except: print("pump connection problem") if Pump_seringe.isconnected(): self.label_pum.setPixmap(self.pixmap_1) else: self.label_pum.setPixmap(self.pixmap_0) try: MotorPI.connect() except: print("motor connection problem") if MotorPI.isconnected(): self.label_mot.setPixmap(self.pixmap_1) else: self.label_mot.setPixmap(self.pixmap_0) #print('connection test') def test_phase(self): """Method to activate the test phase""" self.input_sample.setDisabled(False) self.inibutton.setDisabled(False) self.stopbutton.setDisabled(False) self.input_sample.setDisabled(False) self.Radio_volumeMode.setDisabled(False) self.Radio_pressureMode.setDisabled(False) self.Radio_dispMode.setDisabled(False) self.Radio_loadMode.setDisabled(False) self.input_disp_load.setDisabled(False) self.input_vol_pressure.setDisabled(False) self.input_cycleF.setDisabled(False) self.input_cycleP.setDisabled(False) self.button_vol_more.setDisabled(True) self.button_vol_less.setDisabled(True) self.button_disp_more.setDisabled(True) self.button_disp_less.setDisabled(True) self.Radio_step_vol1.setDisabled(True) self.Radio_step_vol2.setDisabled(True) self.Radio_step_vol5.setDisabled(True) self.Radio_step_disp1.setDisabled(True) self.Radio_step_disp2.setDisabled(True) self.Radio_step_disp5.setDisabled(True) self.button_positioning.setDisabled(True) self.button_pause.setDisabled(True) self.button_restart.setDisabled(True) def positioning_phase(self): """Method to activate the positionning phase""" self.input_sample.setDisabled(True) self.inibutton.setDisabled(True) self.stopbutton.setDisabled(True) self.input_sample.setDisabled(True) self.Radio_volumeMode.setDisabled(True) self.Radio_pressureMode.setDisabled(True) self.Radio_dispMode.setDisabled(True) self.Radio_loadMode.setDisabled(True) self.input_disp_load.setDisabled(True) self.input_vol_pressure.setDisabled(True) self.input_cycleF.setDisabled(True) self.input_cycleP.setDisabled(True) self.button_pause.setDisabled(True) self.button_restart.setDisabled(True) self.button_vol_more.setDisabled(False) self.button_vol_less.setDisabled(False) self.button_disp_more.setDisabled(False) self.button_disp_less.setDisabled(False) self.Radio_step_vol1.setDisabled(False) self.Radio_step_vol2.setDisabled(False) self.Radio_step_vol5.setDisabled(False) self.Radio_step_disp1.setDisabled(False) self.Radio_step_disp2.setDisabled(False) self.Radio_step_disp5.setDisabled(False) self.button_positioning.setDisabled(False) self.Radio_graphON.setDisabled(False) self.Radio_graphOFF.setDisabled(False) def running_phase(self): """Method to activate the running phase""" self.input_sample.setDisabled(True) self.inibutton.setDisabled(True) # self.stopbutton.setDisabled(True) self.input_sample.setDisabled(True) self.Radio_volumeMode.setDisabled(True) self.Radio_pressureMode.setDisabled(True) self.Radio_dispMode.setDisabled(True) self.Radio_loadMode.setDisabled(True) self.input_disp_load.setDisabled(True) self.input_vol_pressure.setDisabled(True) self.input_cycleF.setDisabled(True) self.input_cycleP.setDisabled(True) self.button_vol_more.setDisabled(True) self.button_vol_less.setDisabled(True) self.button_disp_more.setDisabled(True) self.button_disp_less.setDisabled(True) self.Radio_step_vol1.setDisabled(True) self.Radio_step_vol2.setDisabled(True) self.Radio_step_vol5.setDisabled(True) self.Radio_step_disp1.setDisabled(True) self.Radio_step_disp2.setDisabled(True) self.Radio_step_disp5.setDisabled(True) self.button_positioning.setDisabled(True) self.Radio_graphON.setDisabled(True) self.Radio_graphOFF.setDisabled(True) self.button_pause.setDisabled(False) self.button_restart.setDisabled(False) def pause_phase(self): """Method to activate the pause phase""" self.input_disp_load.setDisabled(False) self.input_vol_pressure.setDisabled(False) self.Radio_volumeMode.setDisabled(False) self.Radio_pressureMode.setDisabled(False) self.Radio_dispMode.setDisabled(False) self.Radio_loadMode.setDisabled(False) self.input_cycleF.setDisabled(False) self.input_cycleP.setDisabled(False) def clickMethodTare_vol(self): """Method to tare volume""" reply = QMessageBox.question( self, 'To Tare or not to tare, that is the question !', 'Are you sure ?', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: Pump_seringe.vol_clear() print("Vol tare") else: print("no") #do something if no def clickMethodTare_pressure(self): """Method to tare pressure""" reply = QMessageBox.question( self, 'To Tare or not to tare, that is the question !', 'Are you sure ?', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: try: Arduino.write_ino( "tare_P" ) #Send to the arduino the command that activate the function Tare print("Tare Pressure") except SerialException: QMessageBox.about(self, "WARNING:", "Problem with arduino program sending !") def clickMethodTare_disp(self): """Method to tare displacement""" reply = QMessageBox.question( self, 'To Tare or not to tare, that is the question !', 'Are you sure ?', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: self.tare_disp = MotorPI.motor_pos() print("Disp tare") def clickMethodTare_load(self): """Method to tare load""" reply = QMessageBox.question( self, 'To Tare or not to tare, that is the question !', 'Are you sure ?', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: try: Arduino.write_ino( "tare_F" ) #Send to the arduino the command that activate the function Tare except SerialException: QMessageBox.about(self, "WARNING:", "Problem with arduino program sending !") def clickMethod_volMore(self): """Method to """ self.pump_run = True time.sleep(0.1) try: Pump_seringe.dose(self.step_vol) except: QMessageBox.about(self, "WARNING:", "The pump is not connected") self.pump_run = False def clickMethod_volLess(self): """Method to """ self.pump_run = True time.sleep(0.1) try: Pump_seringe.dose(-self.step_vol) except: QMessageBox.about(self, "WARNING:", "The pump is not connected") self.pump_run = False def clickMethod_dispMore(self): """Method to """ try: MotorPI.move_rel(self.step_disp) except: QMessageBox.about(self, "WARNING:", "The motor is not connected") def clickMethod_dispLess(self): """Method to """ try: MotorPI.move_rel(-self.step_disp) except: QMessageBox.about(self, "WARNING:", "The motor is not connected") def clickMethod_disp0(self): """Method to """ msg = QMessageBox.question(self, "Come back to the base", "Are u sure ?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if msg == QMessageBox.Yes: try: MotorPI.move_rel(-round((self.d - self.tare_disp), 2)) except: QMessageBox.about(self, "WARNING:", "The motor is not connected") def clickMethod_pres0(self): """Method for pressure to return to 0 mmHg""" msg = QMessageBox.question(self, "Come back to 0 pressure", "Are u sure ?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if msg == QMessageBox.Yes: self.CommandThread = CommandThread(0, 10, 0, 0, 'P', 'D') self.CommandThread.signal_end.connect(self.test_end) self.CommandThread.update_thread.connect(self.update_value) self.CommandThread.start() def clickMethod_motorStop(self): MotorPI.stop() def clickMethod_pumpStop(self): Pump_seringe.stop() ############################################### #Function for radio buttons ############################################### def radio_vol_step(self, radio_value): if radio_value.text() == "1": if radio_value.isChecked() == True: self.step_vol = 1 if radio_value.text() == "2": if radio_value.isChecked() == True: self.step_vol = 2 if radio_value.text() == "5": if radio_value.isChecked() == True: self.step_vol = 5 def radio_disp_step(self, radio_value): if radio_value.text() == "1": if radio_value.isChecked() == True: self.step_disp = 1 if radio_value.text() == "2": if radio_value.isChecked() == True: self.step_disp = 2 if radio_value.text() == "5": if radio_value.isChecked() == True: self.step_disp = 5
class TextEditor(QWidget): '''Class creating a TextEditor object.''' def __init__(self, txt_width=500, txt_height=220, txt_text=tr('Text :'), parent=None): '''Create the text.''' #------ini super().__init__(parent) self.fn = tr('-- Select a file --') self.lst_f_hist = [] self.style = GuiStyle().style_sheet #------widgets #---layout main_lay = QGridLayout() main_lay.setRowStretch(0, 1) self.setLayout(main_lay) #---text #-Radio button self.rb_txt = QRadioButton(txt_text) self.rb_txt.setChecked(True) main_lay.addWidget(self.rb_txt, 0, 0) #-font self.fixed_font = QFont('monospace') self.fixed_font.setStyleHint(QFont.TypeWriter) #-text self.txt = QTextEdit() self.txt.setMinimumSize(txt_width, txt_height) self.txt.setAcceptRichText(False) self.txt.setStyleSheet(self.style) self.txt.setObjectName('orange_border_hover') self.txt.setFont(self.fixed_font) main_lay.addWidget(self.txt, 0, 1, 1, 7) #---clear self.bt_clear = QPushButton(tr('Clear')) self.bt_clear.setMaximumSize(len(tr('Clear')) * 13, 50) self.bt_clear.clicked.connect(self.clear) main_lay.addWidget(self.bt_clear, 0, 0, alignment=Qt.AlignTop) #---file #-radio button self.rb_fn = QRadioButton(tr('File') + ' :') main_lay.addWidget(self.rb_fn, 1, 0) #-option menu files self.lst_f = (tr('-- Select a file --'), *list_files()) self.opt_fn = QComboBox() self.opt_fn.addItems(self.lst_f) self.opt_fn.insertSeparator(1) self.opt_fn.activated[str].connect(self.select_fn) main_lay.addWidget(self.opt_fn, 1, 1, 1, 2) #-buttons self.bt_select = QPushButton(tr('Select a file ...')) self.bt_select.setMaximumSize(len(tr('Select a file ...')) * 13, 50) self.bt_select.clicked.connect(self.select_fn) main_lay.addWidget(self.bt_select, 1, 3) self.bt_select_load = QPushButton(tr('Select and load') + ' ▲') self.bt_select_load.setMaximumSize( (len(tr('Select and load')) + 2) * 13, 50) self.bt_select_load.clicked.connect(self.select_load_fn) main_lay.addWidget(self.bt_select_load, 1, 4) self.bt_load = QPushButton(tr('Load') + ' ▲') self.bt_load.setMaximumSize((len(tr('Load')) + 2) * 13, 50) self.bt_load.clicked.connect(self.load_fn) main_lay.addWidget(self.bt_load, 1, 5) self.bt_save = QPushButton(tr('Save') + ' ▼') self.bt_save.setMaximumSize((len(tr('Save')) + 2) * 13, 50) self.bt_save.clicked.connect(self.save_fn) main_lay.addWidget(self.bt_save, 1, 6) self.bt_reload = QPushButton(tr('Reload')) self.bt_reload.setMaximumSize(len(tr('Reload')) * 13, 50) self.bt_reload.clicked.connect(self.reload) main_lay.addWidget(self.bt_reload, 1, 7, alignment=Qt.AlignRight) #-encoding self.rb_encod = QRadioButton(tr('Text encoding :')) main_lay.addWidget(self.rb_encod, 2, 1) self.opt_encod = QComboBox() self.opt_encod.addItems(lst_encod) main_lay.addWidget(self.opt_encod, 2, 2) rb_lay = QHBoxLayout() main_lay.addLayout(rb_lay, 2, 3, 1, 3) #-binary mode self.rb_bin = QRadioButton(tr('Binary mode')) rb_lay.addWidget(self.rb_bin) #-hexa mode self.rb_hexa = QRadioButton(tr('Hexa mode')) rb_lay.addWidget(self.rb_hexa) #-bytes mode self.rb_bytes = QRadioButton(tr('Bytes mode')) rb_lay.addWidget(self.rb_bytes) self.rb_txt.toggled.connect(self.check_bytes) self.rb_fn.toggled.connect(self.check_bytes) self.rb_fn.toggled.connect(self.select_fn_rb) self.rb_bytes.toggled.connect(self.check_bytes) self.rb_bt_grp1 = QButtonGroup() self.rb_bt_grp1.addButton(self.rb_txt) self.rb_bt_grp1.addButton(self.rb_fn) self.rb_bt_grp2 = QButtonGroup() self.rb_bt_grp2.addButton(self.rb_encod) self.rb_bt_grp2.addButton(self.rb_bin) self.rb_bt_grp2.addButton(self.rb_hexa) self.rb_bt_grp2.addButton(self.rb_bytes) #------show self.setMinimumSize(txt_width + 100, txt_height + 110) self.check_bytes() #------check def check_bytes(self): ''' Check the bytes mode checkbutton's status to dislable or not the encoding menu, and check the radiobuttons to dislable or not the bytes checkbuttons. ''' if self.rb_txt.isChecked(): self.opt_encod.setDisabled(False) self.rb_bytes.setDisabled(True) self.rb_bytes.setChecked(False) elif self.rb_fn.isChecked(): self.rb_bytes.setDisabled(False) if self.rb_bytes.isChecked(): self.opt_encod.setDisabled(True) else: self.opt_encod.setDisabled(False) #------clear def clear(self): '''Clear the text widget.''' if self.txt.toPlainText() != '': sure = QMessageBox.question(self, tr('Sure') + ' ?', '<h2>' + tr('Are you sure ?') + '</h2>', \ QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Yes) if sure != QMessageBox.Yes: return None self.txt.clear() #------select_fn_rb def select_fn_rb(self): ''' Activated when pressing the radio button "plain file". If no file is selected, launch select_fn. ''' if self.opt_fn.currentText() == tr('-- Select a file --'): self.select_fn() self.rb_bytes.setChecked(True) self.check_bytes() #---------select file "fn" def select_fn(self, fn=False): ''' Select a file using the PyQt5 file dialog. fn : the filename. It is given when choosing with the combo box. ''' if fn == False: fn = QFileDialog.getOpenFileName(self, tr('Open file'), getcwd())[0] if fn in ((), ''): #cancel fn = tr('-- Select a file --') self.fn = fn self.rb_txt.setChecked(True) self.rb_fn.setChecked(False) return None self.fn = fn f = fn.split('/')[-1] if f not in self.lst_f: if len(self.lst_f_hist) == 0: self.opt_fn.insertSeparator(10000) if fn not in self.lst_f_hist: self.lst_f_hist.append(fn) self.opt_fn.addItem(fn) self.opt_fn.setCurrentText(fn) else: self.opt_fn.setCurrentText(f) #------select and load def select_load_fn(self): '''Uses the functions select and load.''' self.select_fn() self.load_fn() #------load file "fn" def load_fn(self): '''Load the selected file to the text widget.''' #self.fn = self.opt_fn.currentText() if self.fn == tr('-- Select a file --'): QMessageBox.warning(QWidget(), '!!! ' + tr('No file selected') + ' !!!', \ '<h1>' + tr('Please select a file') + ' !</h1>\n' + tr('Or use the button "Select and load"')) return -3 try: if self.rb_encod.isChecked(): with open(self.fn, mode='r', encoding=str(self.opt_encod.currentText())) as f: file_content = f.read() else: with open(self.fn, mode='rb') as f: file_content = f.read() if self.rb_hexa.isChecked() or self.rb_bin.isChecked(): file_content = file_content.hex() if self.rb_bin.isChecked(): d = { '0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100', '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', 'a': '1010', 'b': '1011', 'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111' } for k in d: file_content = file_content.replace(k, d[k]) except FileNotFoundError: QMessageBox.critical( QWidget(), '!!! ' + tr('Error') + ' !!!', '<h2>' + tr('The file was NOT found') + ' !!!</h2>') return -1 #stop except UnicodeDecodeError: QMessageBox.critical(QWidget(), '!!! ' + tr('Encoding error') + ' !!!', \ '<h2>' + tr('The file can\'t be decoded with this encoding') + ' !!!</h2>\n' + tr('Try bytes mode')) return -2 #stop txt = self.txt.toPlainText() if txt != '': sure = QMessageBox.question(self, '!!! ' + tr('Erase Text data') + ' !!!', \ '<h2>' + tr('Text is detected in the box ! Remplace by the file\'s data ?') + '</h2>', \ QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if sure != QMessageBox.Yes: return -3 #stop if type(file_content) == str: self.txt.setPlainText(file_content) elif type(file_content) == bytes: try: self.txt.setPlainText(file_content.decode()) except UnicodeDecodeError: QMessageBox.critical( None, '!!! ' + tr('Decoding error') + ' !!!', '<h2>' + tr("The file can't be decoded in bytes mode") + '!</h2>') return -2 #------save in file "fn" def save_fn(self, data=False): ''' Save the content of the text widget in a file. data : the text to write. If False, write text which is in the text widget. Default is False. return -3 if canceled or aborted, -2 if an encoding error occur, None otherwise. ''' if self.fn == tr('-- Select a file --'): filename = QFileDialog.getSaveFileName(self, tr('Save file'), getcwd())[0] if filename in ((), ''): return -3 #Canceled else: filename = self.fn try: if not self.rb_bytes.isChecked(): with open(filename, 'r', encoding=str(self.opt_encod.currentText())) as f: line = f.readline() else: with open(filename, mode='rb') as f: line = f.readline() except FileNotFoundError: #the file can be created, it don't exists pass except UnicodeDecodeError: pass else: if line not in ('', '\n'): sure = QMessageBox.question(self, '!!! ' + tr('Erase file data') + ' !!!', \ '<h2>' + tr('The selected file is NOT empty') + ' !!!</h2>\n<h3>' + tr('Overwrite with text data ?') + '</h3>', \ QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if sure != QMessageBox.Yes: return -3 #Aborted if data == False: txt = self.txt.toPlainText() else: txt = data if txt == '': emp = QMessageBox.question(self, tr('Text is empty'), \ '<h2>' + tr('There is no text in the box') + '.\n' + tr('Write anyway ?') + '</h2>', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if emp != QMessageBox.Yes: return -3 #Aborted if self.rb_encod.isChecked(): with open(filename, 'w', encoding=str(self.opt_encod.currentText())) as f: if type(txt) == str: f.write(txt) else: f.write(txt.decode()) else: try: if not self.rb_bytes.isChecked(): if self.rb_bin.isChecked(): if len(txt) % 8 != 0: QMessageBox.critical(QWidget(), '!!! ' + tr('Value Error') + ' !!!', \ '<h2>' + tr('The number of binary digits is not a multiple of 8') + ' !!!</h2>') return -2 #stop else: d = { '0000': '0', '0001': '1', '0010': '2', '0011': '3', '0100': '4', '0101': '5', '0110': '6', '0111': '7', '1000': '8', '1001': '9', '1010': 'a', '1011': 'b', '1100': 'c', '1101': 'd', '1110': 'e', '1111': 'f' } txt2 = "" for k in range(len(txt) // 4): if txt[k * 4:k * 4 + 4] not in d: QMessageBox.critical(QWidget(), '!!! ' + tr('Value Error') + ' !!!', \ '<h2>' + tr('A binary number is composed only of 0 and 1') + ' !!!</h2>') return -2 #stop else: txt2 += d[txt[k * 4:k * 4 + 4]] txt = txt2 try: if len(txt) % 2 != 0: QMessageBox.critical(QWidget(), '!!! ' + tr('Value Error') + ' !!!', \ "<h2>The number of hexadecimal digits is not a multiple of 2 !!!</h2>") return -2 #stop txt = bytes.fromhex(txt) except ValueError: QMessageBox.critical(QWidget(), '!!! ' + tr('Value Error') + ' !!!', \ '<h2>' + tr('Error in the conversion of hexadecimal to bytes') + ' !!!</h2>') return -2 #stop with open(filename, mode='wb') as f: if type(txt) == str: f.write( txt.encode( encoding=str(self.opt_encod.currentText()))) else: f.write(txt) except UnicodeEncodeError: QMessageBox.critical(QWidget(), '!!! ' + tr('Encoding error') + ' !!!', \ '<h2>' + tr("The file can't be encoded with this encoding") + ' !!!</h2>') return -2 #stop self.reload() QMessageBox.about( QWidget(), tr('Done') + ' !', '<h2>' + tr('Your text has been be wrote') + ' !</h2>') #------read_file def read_file(self, fn, bytes_md=False, encod='utf-8', silent=True): ''' Read the content of a file and return its content in a string. fn : filename ; bytes_md : the bytes mode. Should be False for text (default) or True for binary (bytes) ; encod : the encoding. Should be "utf-8", "latin-1", "ascii". Default is "utf-8" ; silent : should be a bool. If False, show error message box in case if one occur. return -1 if the file "fn" was not found, -2 if an encoding error occur, the text otherwise. ''' if bytes_md not in (True, False): return 'The bytes_md should be "True" or "False", but "' + str( bytes_md) + '" was found !!!' try: if not bytes_md: #text with open(fn, mode='r', encoding=encod) as file: txt = file.read() else: with open(fn, mode='rb') as file: txt = file.read() except FileNotFoundError: if not silent: QMessageBox.critical(QWidget(), '!!! ' + tr('File error') + ' !!!', \ '<h2>' + tr('The file') + ' "' + str(fn) + '"' + tr(' was NOT found') + ' !!!</h2>') return -1 except UnicodeDecodeError: if not silent: QMessageBox.critical(QWidget(), '!!! ' + tr('Encoding error') + ' !!!', \ '<h2>' + tr('The file can\'t be decoded with this encoding') + ' !!!</h2>') return -2 return txt #------reload def reload(self): ''' Function which reload the files combo boxes. It can be used if a new file was copied while running, for example. ''' self.lst_f = (tr('-- Select a file --'), *list_files(), *self.lst_f_hist) self.opt_fn.clear() self.opt_fn.addItems((tr('-- Select a file --'), *list_files())) self.opt_fn.insertSeparator(1) self.opt_fn.insertSeparator(10000) if len(self.lst_f_hist) > 0: self.opt_fn.addItems(self.lst_f_hist) self.opt_fn.insertSeparator(20000) if self.fn not in self.lst_f: self.fn = tr('-- Select a file --') self.opt_fn.setCurrentText(tr('-- Select a file --')) else: self.opt_fn.setCurrentText(self.fn) #------get encoding def get_encod(self): '''Return the currend selected encoding.''' return self.opt_encod.currentText() #------get bytes mode def get_bytes(self): '''Return the bytes, either 't' for text, or 'b' for bytes.''' return ('t', 'b')[self.rb_bytes.isChecked()] #------getText def getText(self, silent=False, from_=None): ''' Return the text selected by the user. silent : should be a bool. If False, show popup pointing out the error, if one occur ; from_ : where read. Can be None, 'text', 'file'. if None, check the radiobutton. Default is None. Return : -1 if the file was not found ; -2 if an encoding error occur ; -3 if aborted ; The text otherwise. ''' if from_ not in (None, 'text', 'file'): raise ValueError( tr('Parameter "from_" should be None, "text" or "file", but') + ' "' + str(from_) + '" ' + tr('was found') + ' !!!') txt_t = self.txt.toPlainText() if self.opt_fn.currentText() != tr('-- Select a file --'): txt_f = self.read_file(self.opt_fn.currentText(), \ self.rb_bytes.isChecked(), self.opt_encod.currentText()) else: txt_f = None if from_ == 'text': return txt_t elif from_ == 'file': return txt_f if self.rb_txt.isChecked(): # Text is in the text widget if txt_t == '' and txt_f not in (None, ''): rep = QMessageBox.question(self, '!!! ' + tr('Text is empty') + ' !!!', \ '<h3>' + tr('The text widget seem to be empty') + '.</h3>\n<h2>' + tr('Read the file ?') + '</h2>', \ QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if rep == QMessageBox.Yes: return txt_f else: return -3 # Abort elif txt_t == '': if not silent: QMessageBox.critical(QWidget(), '!!! ' + tr('Text is empty') + ' !!!', \ '<h2>' + tr('The text widget is empty') + ' !!!</h2>') return -3 #Abort return txt_t else: # Text is in the file if txt_f == -1: if not silent: QMessageBox.critical(QWidget(), '!!! ' + tr('File error') + ' !!!', \ '<h2>' + tr('The file') + ' "' + str(fn) + '" ' + tr('was NOT found') + ' !!!</h2>') return -1 elif txt_f == -2: if not silent: QMessageBox.critical(QWidget(), '!!! ' + tr('Encoding error') + ' !!!', \ '<h2>' + tr("The file can't be decoded with this encoding") + ' !!!</h2>') return -2 if txt_f == None and txt_t != '': rep = QMessageBox.question(self, '!!! ' + tr('No file selected') + ' !!!', \ '<h3>' + tr('You did not select a file') + ' !!!</h3>\n<h2>' + tr('Read the text widget ?') + '</h2>', \ QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if rep == QMessageBox.Yes: return txt_t else: return -3 # Abort elif txt_f == None: if not silent: QMessageBox.critical(QWidget(), '!!! ' + tr('No file selected') + ' !!!', \ '<h2>' + tr('Please select a file') + ' !</h2>') return -3 if txt_f in ('', b'') and txt_t != '': rep = QMessageBox.question(self, '!!! ' + tr('File is empty') + ' !!!', \ '<h3>' + tr('The file seem to be empty') + '.</h3>\n<h2>' + tr('Read the text widget ?') + '</h2>', \ QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if rep == QMessageBox.Yes: return txt_t else: return -3 # Abort elif txt_f in ('', b''): if not silent: QMessageBox.critical( QWidget(), '!!! ' + tr('File is empty') + ' !!!', '<h2>' + tr('The file is empty') + ' !!!</h2>') return -3 return txt_f def setText(self, txt): '''Fill the text widget or the file with txt, according to the radiobuttons.''' txt_t = self.txt.toPlainText() if self.opt_fn.currentText() != tr('-- Select a file --'): txt_f = self.read_file(self.opt_fn.currentText(), \ self.rb_bytes.isChecked(), self.opt_encod.currentText()) else: txt_f = None if self.rb_txt.isChecked(): # The text widget is chosen if txt_t != '' and txt_f == '': rep = QMessageBox.question(self, '!!! ' + tr('Text is not empty') + ' !!!', \ '<h2>' + tr('The text widget is not empty, but the file is') + '.</h2>\n<h3>' + tr('Write the file (Yes) or overwrite text (Ignore) ?') + '</h3>', \ QMessageBox.Yes | QMessageBox.Ignore | QMessageBox.Cancel, QMessageBox.Ignore) if rep == QMessageBox.Yes: self.save_fn(txt) elif rep == QMessageBox.Ignore: self.txt.setPlainText(txt) else: return -3 # Abort else: self.txt.setPlainText(txt) else: # The file is chosen if txt_f == -1: rep = QMessageBox.question(self, '!!! ' + tr('File error') + ' !!!', \ '<h2>' + tr('The file') + ' "' + str(fn) + '" ' + tr('was NOT found') + ' !!!</h2>\n<h3>' + tr('Write in the text widget ?') + '</h3>', \ QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if rep == QMessageBox.Yes: self.txt.setPlainText(txt) else: return -1 else: self.save_fn(txt)
class FunctionsMenu(QWidget): def __init__(self): super().__init__() self.layout = QGridLayout() self.setLayout(self.layout) row_hight = 30 margins = self.layout.contentsMargins() margins.setTop(2*row_hight + self.layout.spacing()) margins.setLeft(20) self.layout.setContentsMargins(margins) # Initializing GUI elements self.ipp = QRadioButton() self.ippcp = QRadioButton() self.select_ipp = QPushButton('Select package') self.select_ippcp = QPushButton('Select package') self.select_ipp.package = utils.IPP self.select_ippcp.package = utils.IPPCP self.lib_var_list = QComboBox(self) self.search = QLineEdit(self) self.selected_libraries_list = QListWidget(self) self.auto_build_button = QPushButton('Autobuild') self.current_functions_list = {} # Preparing elements by giving initial values, etc self.ipp.setText('IPP ver. None') self.ippcp.setText('IPP Cryptography ver. None') self.search.setPlaceholderText('Search...') self.ipp.setDisabled(True) self.ippcp.setDisabled(True) self.auto_build_button.setDisabled(True) self.lib_var_list.activated[str].connect(self.on_theme_selected) self.search.textEdited.connect(self.on_search) self.selected_libraries_list.itemClicked.connect(self.on_item_selected) self.auto_build_button.clicked.connect(self.on_build_pressed) self.select_ipp.clicked.connect(self.on_select) self.select_ippcp.clicked.connect(self.on_select) self.ipp.toggled.connect(self.on_switch) # Setting all widgets in their places self.layout.addWidget(self.ipp, 0, 0, 1, 3) self.layout.addWidget(self.ippcp, 1, 0, 1, 3) self.layout.addWidget(self.select_ipp, 0, 3) self.layout.addWidget(self.select_ippcp, 1, 3) self.layout.addWidget(self.lib_var_list, 2, 0, 1, 4) self.layout.addWidget(self.search, 3, 0, 1, 4) self.layout.addWidget(self.selected_libraries_list, 4, 0, 1, 4) self.layout.addWidget(self.auto_build_button, 5, 0, 1, 4) self.select_ipp.setFixedHeight(row_hight) self.select_ippcp.setFixedHeight(row_hight) self.lib_var_list.setFixedHeight(row_hight) path_to_package = self.get_path_to_package() if path_to_package: package = utils.IPPCP if re.compile('.*ippcp.*').match(path_to_package) else utils.IPP self.set_package(package, path_to_package) self.init_menu() def init_menu(self): self.ipp.toggled.disconnect(self.on_switch) self.tl_selected = False if self.ipp.isEnabled(): package = utils.IPP self.init_functions(utils.IPP, settings.CONFIGS[utils.IPP]['Path']) self.ipp.setChecked(True) if self.ippcp.isEnabled(): self.init_functions(utils.IPPCP, settings.CONFIGS[utils.IPPCP]['Path']) if not self.ipp.isEnabled(): package = utils.IPPCP self.ippcp.setChecked(True) self.show_menu(package) self.ipp.toggled.connect(self.on_switch) def set_package(self, package, path): if self.check_package(package, path): settings.CONFIGS[package]['Path'] = path if package == utils.IPP: self.ipp.setText('IPP ver. ' + self.get_version(path)) self.ipp.setEnabled(True) else: self.ippcp.setText('IPP Cryptography ver. ' + self.get_version(path)) self.ippcp.setEnabled(True) return True elif path: if package == utils.IPP: QMessageBox.information(self, 'ERROR!', 'Incorrect Intel® Integrated Performance Primitives package path!') else: QMessageBox.information(self, 'ERROR!', 'Incorrect Intel® Integrated Performance Primitives Cryptography package path!') return False def check_package(self, package, path): if not self.check_batch(package, path): return False if os.path.exists(os.path.join(path, 'include')): for header in os.listdir(os.path.join(path, 'include')): if get_mode_and_domain(header): break else: return False lib_ia32_path = os.path.join(path, 'lib', 'ia32_' + utils.HOST_SYSTEM.lower()[:3]) if utils.HOST_SYSTEM != MACOSX: lib_intel64_path = os.path.join(path, 'lib', 'intel64_' + utils.HOST_SYSTEM.lower()[:3]) else: lib_intel64_path = os.path.join(path, 'lib') return True if self.check_libs(lib_ia32_path) or \ self.check_libs(lib_intel64_path) else False def check_batch(self, package, path): return os.path.exists(os.path.join(path, 'bin', package.lower() + 'vars' + BATCH_EXTENSIONS[utils.HOST_SYSTEM])) def check_libs(self, path): if os.path.exists(path): for lib in os.listdir(path): if STATIC_LIBRARIES_EXTENSIONS[utils.HOST_SYSTEM] in lib: return True return False def on_select(self): package = self.sender().package while True: path = QFileDialog.getExistingDirectory(self, 'Select ' + package + ' package') if not path: return if self.set_package(package, path): break self.init_functions(package, path) if package == utils.IPP: if not self.ipp.isChecked() and not self.ippcp.isChecked(): self.ipp.toggled.disconnect(self.on_switch) self.ipp.setChecked(True) self.ipp.toggled.connect(self.on_switch) else: if not self.ipp.isChecked() and not self.ippcp.isChecked(): self.ippcp.setChecked(True) for config in settings.CONFIGS[package].keys(): if config != 'Path' and config != 'functions_list': settings.CONFIGS[package][config] = False settings.CONFIGS[package]['functions_list'].clear() if package == utils.IPP and self.ipp.isChecked() or \ package == utils.IPPCP and self.ippcp.isChecked(): self.parent.receiver.set_configs(package) self.parent.receiver.functions_names.clear() self.parent.receiver.functions_list.clear() self.show_menu(package) self.parent.receiver.on_block() def on_switch(self): if self.ipp.isChecked(): package = utils.IPP self.parent.receiver.get_configs(utils.IPPCP) else: package = utils.IPPCP self.parent.receiver.get_configs(utils.IPP) self.parent.receiver.set_configs(package) self.show_menu(package) self.parent.receiver.add_items(self.parent.receiver.functions_names) self.parent.receiver.on_block() def on_theme_selected(self, text): self.add_items(self.current_functions_list.get(text)) self.on_search(self.search.text()) def on_search(self, search_request): if self.current_functions_list: self.add_items([entry for entry in self.current_functions_list.get(self.lib_var_list.currentText()) if search_request.upper() in entry.upper()]) def on_item_selected(self, item): self.selected_libraries_list.setCurrentItem(item) def on_build_pressed(self): information = self.parent.get_library_information() library_path = QFileDialog.getExistingDirectory(self, 'Select a folder') if library_path == '': return success = False self.parent.set_disabled(True) QMessageBox.information(self, 'Build', 'Building will start after this window is closed. ' 'Please wait until process is done.') package = utils.IPP if self.ipp.isChecked() else utils.IPPCP os.environ[package + 'ROOT'] = settings.CONFIGS[package]['Path'] self.get_path_to_cnl(settings.CONFIGS[package]['Path']) if information['ia32']: success = tool.core.build( package, information['host_system'], information['target_system'], information['functions'], library_path, information['library_name'], tool.utils.IA32, information['threading'] == 'Multi-threaded', tool.utils.COMPILERS_AND_LIBRARIES_PATH, threading_layer_type=information['threading_layer_type'] ) if information['intel64']: success = tool.core.build( package, information['host_system'], information['target_system'], information['functions'], library_path, information['library_name'], tool.utils.INTEL64, information['threading'] == 'Multi-threaded', tool.utils.COMPILERS_AND_LIBRARIES_PATH, threading_layer_type=information['threading_layer_type'] ) self.parent.set_disabled(False) QMessageBox.information(self, 'Success' if success else 'Failure', 'Build completed!' if success else 'Build failed!') def add_items(self, items): """ Sorts and adds items to list view :param items: list of strings """ self.selected_libraries_list.clear() if items: items.sort() self.selected_libraries_list.addItems(items) self.selected_libraries_list.setCurrentItem(self.selected_libraries_list.item(0)) self.selected_libraries_list.repaint() def add_item(self, function_name): """ Adds function to left list :param function_name: """ self.operation(list.append, function_name) self.add_items(self.current_functions_list.get(self.lib_var_list.currentText())) self.on_search(self.search.text()) def remove_item(self, item): """ Removes item from left list """ if item is None: return None self.operation(list.remove, item) self.add_items(self.current_functions_list.get(self.lib_var_list.currentText())) self.on_search(self.search.text()) def operation(self, action, function_name): for mode in FUNCTIONS_LIST.keys(): for domain in FUNCTIONS_LIST[mode].keys(): if function_name in FUNCTIONS_LIST[mode][domain]: action(self.functions_list[mode][domain], function_name) return def init_func_list(self): """ Taking all domains and their functions """ self.lib_var_list.clear() self.lib_var_list.addItems([entry for entry in self.current_functions_list.keys()]) def init_functions(self, package, path): if package == utils.IPP: FUNCTIONS_LIST['Classical IPP'].clear() FUNCTIONS_LIST['IPP TL'].clear() else: FUNCTIONS_LIST['IPP Cryptography'].clear() get_functions_from_headers(path) self.functions_list = copy.deepcopy(FUNCTIONS_LIST) self.threaded_functions = [item for sublist in self.functions_list['IPP TL'].values() for item in sublist] def show_menu(self, package): if package == utils.IPP: if not self.tl_selected: self.current_functions_list = self.functions_list['Classical IPP'] else: self.current_functions_list = self.functions_list['IPP TL'] else: self.current_functions_list = self.functions_list['IPP Cryptography'] self.init_func_list() self.add_items(self.current_functions_list.get(self.lib_var_list.currentText())) def get_path_to_package(self): dir_path = os.path.dirname(os.path.realpath(__file__)) if re.compile(utils.PATH_TO_PACKAGE_REGULAR_EXPRESSION).match(dir_path): return re.match(utils.PATH_TO_PACKAGE_REGULAR_EXPRESSION, dir_path).group('path') else: return '' def get_version(self, path): if re.compile(utils.VERSION_REGULAR_EXPRESSION).match(path): return re.match(utils.VERSION_REGULAR_EXPRESSION, path).group('ver') else: return 'None' def get_path_to_cnl(self, path): if re.compile(utils.PATH_TO_CNL_REGULAR_EXPRESSION).match(path): utils.COMPILERS_AND_LIBRARIES_PATH = re.match(utils.PATH_TO_CNL_REGULAR_EXPRESSION, path).group('cnl')
class MyWindow(QWidget): sig_abort_workers = pyqtSignal() def __init__(self): super().__init__() self.setWindowTitle("Dummy Files Creator") self.setWindowIcon(QtGui.QIcon(':/icon.png')) QThread.currentThread().setObjectName('main') self.__threads = [] self._files_created = [] self._create_ui() # Creates all UI elements def _create_ui(self): self._window_layout = QGridLayout() self._window_layout.setContentsMargins(0,0,0,0) self._menu_bar = QMenuBar() self._window_layout.addWidget(self._menu_bar) self._help_item = self._menu_bar.addMenu('Help') self._about_action = QAction("Help", self._menu_bar) self._about_action.triggered.connect(self._about_clicked) self._help_item.addAction(self._about_action) self._options_layout = QGridLayout() self._options_layout.setAlignment(QtCore.Qt.AlignCenter) self._options_widget = QWidget() self._options_widget.setLayout(self._options_layout) self._path_label = QLabel() self._path_label.setText("Path") self._path_label.setAlignment(QtCore.Qt.AlignCenter) self._path_textbox = QLineEdit() self._path_textbox.resize(320,20) self._path_textbox.setMinimumWidth(320) self._browse_button = QPushButton("Browse") self._browse_button.setFixedWidth(80) self._browse_button.clicked.connect(self._browse_clicked) self._options_layout.addWidget(self._path_label, 1, 1) self._options_layout.addWidget(self._path_textbox, 1, 2) self._options_layout.addWidget(self._browse_button, 1, 3, QtCore.Qt.AlignCenter) self._number_files_label = QLabel() self._number_files_label.setText("Number of Files") self._number_files_label.setAlignment(QtCore.Qt.AlignCenter) self._number_validator=QtCore.QRegExp("[0-9]+") self._validator = QtGui.QRegExpValidator(self._number_validator) self._number_files_textbox = QLineEdit() self._number_files_textbox.resize(320,20) self._number_files_textbox.setMinimumWidth(320) self._number_files_textbox.setValidator(self._validator) self._options_layout.addWidget(self._number_files_label, 2, 1) self._options_layout.addWidget(self._number_files_textbox, 2, 2) self._size_files_label = QLabel() self._size_files_label.setText("Size of File(s)") self._size_files_label.setAlignment(QtCore.Qt.AlignCenter) self._size_files_textbox = QLineEdit() self._size_files_textbox.resize(320,20) self._size_files_textbox.setMinimumWidth(320) self._size_files_textbox.setValidator(self._validator) self._radio_button_layout = QHBoxLayout() self._radio_button_layout.setSpacing(5) self._radio_widget = QWidget() self._radio_widget.setLayout(self._radio_button_layout) self._kb_button = QRadioButton("KiB") self._kb_button.setChecked(False) self._mb_button = QRadioButton("MiB") self._mb_button.setChecked(True) self._gb_button = QRadioButton("GiB") self._gb_button.setChecked(False) self._radio_button_layout.addWidget(self._kb_button, 1) self._radio_button_layout.addWidget(self._mb_button, 2) self._radio_button_layout.addWidget(self._gb_button, 3) self._options_layout.addWidget(self._size_files_label, 3, 1) self._options_layout.addWidget(self._size_files_textbox, 3, 2) self._options_layout.addWidget(self._radio_widget, 3, 3, QtCore.Qt.AlignLeft) self._advanced_layout = QGridLayout() self._advanced_layout.setContentsMargins(0,0,0,0) self._advanced_widget = QWidget() self._advanced_widget.setLayout(self._advanced_layout) self._options_layout.addWidget(self._advanced_widget, 4, 2) self._debug_label = QLabel() self._debug_label.setText("Debug") self._debug_label.setMaximumHeight(17) self._debug_label.setAlignment(QtCore.Qt.AlignRight) self._advanced_layout.addWidget(self._debug_label, 1, 1) self._debug_checkbox = QCheckBox() self._debug_checkbox.setChecked(False) self._debug_checkbox.setToolTip("Impacts performance") self._advanced_layout.addWidget(self._debug_checkbox, 1, 2, QtCore.Qt.AlignLeft) self._chunksize_label = QLabel() self._chunksize_label.setText("Chunk Size") self._chunksize_label.setMaximumHeight(17) self._chunksize_label.setAlignment(QtCore.Qt.AlignRight) self._advanced_layout.addWidget(self._chunksize_label, 1, 3) self._chunksize_textbox = QLineEdit() self._chunksize_textbox.setText("1024") self._chunksize_textbox.resize(50,20) self._chunksize_textbox.setMaximumWidth(50) self._chunksize_textbox.setValidator(self._validator) self._advanced_layout.addWidget(self._chunksize_textbox, 1, 4, QtCore.Qt.AlignCenter) self._chunksize_combobox = QComboBox() self._chunksize_combobox.addItems(["KiB", "MiB", "GiB"]) self._advanced_layout.addWidget(self._chunksize_combobox, 1, 5, QtCore.Qt.AlignCenter) self._create_close_layout = QHBoxLayout() self._create_close_widget = QWidget() self._create_close_widget.setLayout(self._create_close_layout) self._create_button = QPushButton("Create") self._create_button.setFixedWidth(80) self._create_button.clicked.connect(self._create_clicked) self._close_button = QPushButton("Close") self._close_button.setFixedWidth(80) self._close_button.clicked.connect(self._close_clicked) self._create_close_layout.addWidget(self._create_button, 1) self._create_close_layout.addWidget(self._close_button, 1) self._options_layout.addWidget(self._create_close_widget, 5, 2) self._window_layout.addWidget(self._options_widget) self._window_layout.setSizeConstraint(QLayout.SetFixedSize) self._debug_progress_bar = QProgressBar() self._debug_progress_bar.setContentsMargins(0,0,0,0) self._debug_progress_label = QLabel() self._debug_progress_label.setAlignment(QtCore.Qt.AlignCenter) self._debug_progress_label.setContentsMargins(0,0,0,0) self._overall_progress_bar = QProgressBar() self._overall_progress_bar.setContentsMargins(0,0,0,0) self._overall_progress_label = QLabel() self._overall_progress_label.setAlignment(QtCore.Qt.AlignCenter) self._overall_progress_label.setContentsMargins(0,0,0,0) self.setLayout(self._window_layout) # Opens About window when Help is choosen in top menu def _about_clicked(self): About() # Open native folder dialog to select where test files will be created def _browse_clicked(self): dialog = QFileDialog() path = str(QFileDialog.getExistingDirectory(dialog, "Select Directory")) self._path_textbox.setText(path) # Action to button Create def _create_clicked(self): if self._path_textbox.text() == "" or \ self._number_files_textbox.text() == "" or \ self._size_files_textbox.text() == "": msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error") msg.setInformativeText("You must fill all options to "\ "create files") msg.setWindowTitle("Error") msg.setStandardButtons(QMessageBox.Ok) msg.setStyleSheet("QLabel{min-width: 100px;}") msg.exec_() elif int(self._number_files_textbox.text()) == 0 or \ int(self._size_files_textbox.text()) == 0: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error") msg.setInformativeText("Number of files/File size cannot be zero") msg.setWindowTitle("Error") msg.setStandardButtons(QMessageBox.Ok) msg.setStyleSheet("QLabel{min-width: 100px;}") msg.exec_() else: if self._kb_button.isChecked(): size_unit = 0 elif self._mb_button.isChecked(): size_unit = 1 else: size_unit = 2 self.Files = FilesCreator(self._path_textbox.text(), self._number_files_textbox.text(), self._size_files_textbox.text(), size_unit, self._chunksize_textbox.text(), self._chunksize_combobox.currentIndex(), self._debug_checkbox.isChecked()) self.thread = QThread() self.__threads.append((self.thread, self.Files)) self.Files.moveToThread(self.thread) self.Files.sig_step_overall.connect(self._step_overall) self.Files.sig_step_file.connect(self._step_file) self.Files.sig_done.connect(self._done) self.Files.sig_abort.connect(self._abort) self.thread.started.connect(self.Files.work) self.thread.start() self._change_layout('Running') # Action to button Close/Quit def _close_clicked(self): if self._close_button.text() == "Quit": msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Quit") msg.setText("Are you sure you want to quit?") msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) quit_code = msg.exec_() if quit_code == QMessageBox.Yes: sys.exit(0) else: sys.exit(0) # Action to button Cancel def _cancel_clicked(self): msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Confirmation") msg.setText("Are you sure?") msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) cancel_code = msg.exec_() if cancel_code == QMessageBox.Yes: self.Files.abort() self._change_layout('Stopped') # Changes layout when app is creating files / idle def _change_layout(self, status): if status == 'Running': self._files_created.clear() disabled_style = "background-color: rgb(210,210,210); border: gray" self._path_textbox.setStyleSheet(disabled_style) self._number_files_textbox.setStyleSheet(disabled_style) self._size_files_textbox.setStyleSheet(disabled_style) self._path_textbox.setDisabled(True) self._browse_button.setDisabled(True) self._number_files_textbox.setDisabled(True) self._size_files_textbox.setDisabled(True) self._kb_button.setDisabled(True) self._mb_button.setDisabled(True) self._gb_button.setDisabled(True) self._debug_checkbox.setDisabled(True) self._chunksize_textbox.setDisabled(True) self._chunksize_combobox.setDisabled(True) self._create_button.setText("Cancel") self._create_button.clicked.disconnect() self._create_button.clicked.connect(self._cancel_clicked) self._close_button.setText("Quit") self._close_button.clicked.disconnect() self._close_button.clicked.connect(self._close_clicked) self._debug_progress_label.setText("") self._debug_progress_bar.setValue(0) if self._debug_checkbox.isChecked(): self._debug_progress_bar.show() self._debug_progress_label.show() self._debug_progress_bar.setContentsMargins(0,0,0,0) self._window_layout.addWidget(self._debug_progress_label) self._window_layout.addWidget(self._debug_progress_bar) self._overall_progress_bar.setContentsMargins(0,0,0,0) self._overall_progress_bar.setValue(0) self._overall_progress_label.setText("0/" + \ str(self.Files._number_files)) self._window_layout.addWidget(self._overall_progress_label) self._window_layout.addWidget(self._overall_progress_bar) self.repaint() else: self._path_textbox.setStyleSheet("") self._number_files_textbox.setStyleSheet("") self._size_files_textbox.setStyleSheet("") self._path_textbox.setDisabled(False) self._browse_button.setDisabled(False) self._number_files_textbox.setDisabled(False) self._size_files_textbox.setDisabled(False) self._kb_button.setDisabled(False) self._mb_button.setDisabled(False) self._gb_button.setDisabled(False) self._debug_checkbox.setDisabled(False) self._chunksize_textbox.setDisabled(False) self._chunksize_combobox.setDisabled(False) self._create_button.setText("Create") self._create_button.clicked.disconnect() self._create_button.clicked.connect(self._create_clicked) self._close_button.setText("Close") self._close_button.clicked.disconnect() self._close_button.clicked.connect(self._close_clicked) if self._debug_checkbox.isChecked(): self._debug_progress_bar.hide() self._debug_progress_label.hide() self._window_layout.removeWidget(self._debug_progress_label) self._window_layout.removeWidget(self._debug_progress_bar) self._window_layout.removeWidget(self._overall_progress_label) self._window_layout.removeWidget(self._overall_progress_bar) self.repaint() # Method to treat error during file creation @pyqtSlot(str) def _abort(self, error: str): print(error) msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Error") msg.setText("Error. See details for more information.") msg.setDetailedText(error) msg.setStandardButtons(QMessageBox.Ok) msg.setStyleSheet("QLabel{min-width: 100px;}") msg.exec_() self._change_layout('Stopped') # Method to treat files creation completion @pyqtSlot() def _done(self): self._change_layout('Stopped') msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Info") msg.setText("Info") msg.setInformativeText("Files created!") detailed_text="Files created at " + self._path_textbox.text() + ":\n\n" for i in range(0,len(self._files_created)): detailed_text = detailed_text + self._files_created[i] + "\n" msg.setDetailedText(detailed_text) msg.setStandardButtons(QMessageBox.Ok) msg.setStyleSheet("QLabel{min-width: 175px;}") msg.exec_() # Runs when each file is created to change progress bar UI values @pyqtSlot(str, int) def _step_overall(self, file_name: str, number_files: int): self._overall_progress_label.setText(str(self.Files.created_files) + "/" + \ str(int(self._number_files_textbox.text()))) value = number_files * 100 / int(self._number_files_textbox.text()) self._overall_progress_bar.setValue(value) self._files_created.append(file_name) # Runs when each file chunk is generated to change progress bar UI values @pyqtSlot(str, int, int) def _step_file(self, file_name: str, chunk_idx: int, total: int): self._debug_progress_label.setText("Creating " + file_name + "...") value = (chunk_idx * 100) / total self._debug_progress_bar.setValue(value) # Handles clicking in Exit window button def closeEvent(self, event): self._close_clicked()
class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.initUI() def initUI(self): # Set up window self.setFixedSize(900, 900) self.setWindowTitle("Buffon Needle Simulator") # Set up main widget self.widget = QWidget() self.setCentralWidget(self.widget) # Set up layouts self.hbox = QHBoxLayout() self.hbox.setAlignment(QtCore.Qt.AlignTop) self.vbox = QVBoxLayout() self.vbox.addLayout(self.hbox) self.vbox.setAlignment(QtCore.Qt.AlignTop) self.widget.setLayout(self.vbox) # type selection layout self.t = 'Needle' self.typeSelection = QHBoxLayout() self.typeLabel = QLabel('Type: ') self.typeSelection.addWidget(self.typeLabel) self.needleType = QRadioButton('Needle') self.needleType.setChecked(True) self.needleType.toggled.connect( lambda: self.changeType(self.needleType)) self.typeSelection.addWidget(self.needleType) self.circleType = QRadioButton('Circle') self.circleType.toggled.connect( lambda: self.changeType(self.circleType)) self.typeSelection.addWidget(self.circleType) self.typeSelection.addStretch() self.hbox.addLayout(self.typeSelection) # iterations label and combo box self.selectionSection = QHBoxLayout() self.iterationsLabel = QLabel("Amount:") self.selectionSection.addWidget(self.iterationsLabel) self.iterations = QComboBox() self.iterations.addItem('10') self.iterations.addItem('100') self.iterations.addItem('200') self.iterations.addItem('500') self.iterations.addItem('1000') self.iterations.addItem('2500') self.selectionSection.addWidget(self.iterations) # length label and combo box self.lengthLabel = QLabel("Length/Diameter:") self.selectionSection.addWidget(self.lengthLabel) self.length = QComboBox() self.length.move(150, 30) self.length.addItem('.1') self.length.addItem('.2') self.length.addItem('.3') self.length.addItem('.4') self.length.addItem('.5') self.length.addItem('.6') self.length.addItem('.7') self.length.addItem('.8') self.length.addItem('.9') self.length.addItem('1') self.selectionSection.addWidget(self.length) # Start simulation button self.start = QPushButton("Start Simulation") self.start.clicked.connect(self.simulation) self.selectionSection.addWidget(self.start) # Pause button self.pause = QPushButton('Pause') self.pause.setDisabled(True) self.pause.clicked.connect(self.pauseAction) self.pausing = False self.selectionSection.addWidget(self.pause) # Cancel button self.cancel = QPushButton('Cancel Simulation') self.cancel.setDisabled(True) self.cancel.clicked.connect(self.cancelAction) self.selectionSection.addWidget(self.cancel) # Add second row to vbox self.vbox.addLayout(self.selectionSection) # Stats section self.counter = 0 self.counterLabel = QLabel('Number of Plotted: 0') self.counterLabel.setFixedWidth(150) self.crossCounter = 0 self.crossLabel = QLabel('Number of Crossing: 0 (0.0%)') self.statsSection = QHBoxLayout() self.statsSection.setAlignment(QtCore.Qt.AlignLeft) self.statsSection.stretch(1) self.statsSection.addWidget(self.counterLabel) self.statsSection.addWidget(self.crossLabel) self.vbox.addLayout(self.statsSection) # Set up canvas self.canvas = MplCanvas(self, width=10, height=10, dpi=100) self.vbox.addWidget(self.canvas) self.canvas.axes.set_ylim([-0.5, 5.5]) self.canvas.axes.set_xlim([-0.5, 5.5]) x = [0, 1, 2, 3, 4, 5] for p in x: self.canvas.axes.axvline(p) self.show() def changeType(self, type): if type.text() == 'Needle' and type.isChecked(): self.t = 'Needle' elif type.text() == 'Circle' and type.isChecked(): self.t = "Circle" else: return def pauseAction(self): if self.pausing: self.timer.start() self.pausing = False self.pause.setText('Pause') else: self.timer.stop() self.pausing = True self.pause.setText('Resume') def cancelAction(self): self.timer.stop() self.length.setDisabled(False) self.iterations.setDisabled(False) self.pause.setDisabled(True) self.cancel.setDisabled(True) self.needleType.setDisabled(False) self.circleType.setDisabled(False) def simulation(self): # Set up for simulation self.start.setText('Restart Simulation') self.pause.setDisabled(False) self.pause.setText('Pause') self.cancel.setDisabled(False) self.counter = 0 self.crossCounter = 0 self.counterLabel.setText('Number of Plotted: 0') self.crossLabel.setText('Number of Crossing: 0 (0.0%)') self.length.setDisabled(True) self.iterations.setDisabled(True) self.circleType.setDisabled(True) self.needleType.setDisabled(True) self.canvas.axes.cla() self.xpoints = [0, 1, 2, 3, 4, 5] for p in self.xpoints: self.canvas.axes.axvline(p) cross = mpatches.Patch(color='green', label='Cross') miss = mpatches.Patch(color='red', label='Miss') self.canvas.axes.legend(handles=[cross, miss], loc='upper right', bbox_to_anchor=(1, 1.1)) self.canvas.axes.set_ylim([-0.5, 5.5]) self.canvas.axes.set_xlim([-0.5, 5.5]) self.total = int(self.iterations.currentText()) # Use timer to repeat plotting needles self.timer = QtCore.QTimer() self.timer.setInterval(5) self.timer.timeout.connect(self.plot) self.timer.start() self.canvas.draw() def plot(self): # if finish simulation if self.counter == self.total - 1: self.timer.stop() self.pause.setDisabled(True) self.length.setDisabled(False) self.iterations.setDisabled(False) self.cancel.setDisabled(True) self.needleType.setDisabled(False) self.circleType.setDisabled(False) self.start.setText('Start Simulation') # Updating ui and variables self.counter += 1 self.counterLabel.setText('Number of Plotted: ' + str(self.counter)) # Create a new needle and check crossing if self.t == 'Needle': n = Needle(float(self.length.currentText())) if n.check_cross(self.xpoints): self.canvas.axes.plot([n.start[0], n.end[0]], [n.start[1], n.end[1]], 'g') self.crossCounter += 1 else: self.canvas.axes.plot([n.start[0], n.end[0]], [n.start[1], n.end[1]], 'r') elif self.t == 'Circle': n = Circle(float(self.length.currentText())) if n.check_cross(self.xpoints): c = mpatches.Circle((n.center[0], n.center[1]), n.r, color='g') self.canvas.axes.add_patch(c) self.crossCounter += 1 else: c = mpatches.Circle((n.center[0], n.center[1]), n.r, color='r') self.canvas.axes.add_patch(c) else: print('invalid type') return self.crossLabel.setText( 'Number of Crossing: ' + str(self.crossCounter) + ' (' + str(round((self.crossCounter / self.counter) * 100, 2)) + '%)') self.canvas.draw()
class Phase10PlayerWidget(GamePlayerWidget): roundWinnerSet = QtCore.pyqtSignal(str) def __init__(self, nick, engine, bgroup=None, parent=None): self.engine = engine self.current_phase = min( self.engine.getRemainingPhasesFromPlayer(nick)) self.phases_in_order = self.engine.getPhasesInOrderFlag() self.bgroup = bgroup super(Phase10PlayerWidget, self).__init__( nick, PlayerColours[self.engine.getListPlayers().index(nick)], parent) def initUI(self): css = ("QGroupBox {{ font-size: 28px;" "font-weight: bold; color:rgb({},{},{});}}") self.setStyleSheet(css.format(self.pcolour.red(), self.pcolour.green(), self.pcolour.blue())) self.setTitle(self.player) super(Phase10PlayerWidget, self).initUI() trashWidget = QWidget() trashWidget.setLayout(self.mainLayout) self.mainLayout = QVBoxLayout(self) self.mainLayout.addStretch() self.upperLayout = QHBoxLayout() self.mainLayout.addLayout(self.upperLayout) self.upperLayout.addStretch() self.phaseNameLabel = QLabel(self) self.phaseNameLabel.setStyleSheet( "font-weight: bold; font-size: 24px;") self.updatePhaseName() self.upperLayout.addWidget(self.phaseNameLabel) self.upperLayout.addStretch() self.lowerLayout = QHBoxLayout() self.mainLayout.addLayout(self.lowerLayout) self.mainLayout.addStretch() self.phaseLabelsLayout = QGridLayout() self.phaseLabelsLayout.setSpacing(5) self.checkboxLayout = QVBoxLayout() self.scoreLCD = QLCDNumber(self) self.scoreLCD.setSegmentStyle(QLCDNumber.Flat) self.mainLayout.addWidget(self.scoreLCD) self.scoreLCD.setNumDigits(3) self.scoreLCD.setMinimumWidth(100) css = "QLCDNumber {{ color:rgb({},{},{});}}" self.scoreLCD.setStyleSheet(css.format(self.pcolour.red(), self.pcolour.green(), self.pcolour.blue())) # Left part - score self.lowerLayout.addWidget(self.iconlabel) self.lowerLayout.addWidget(self.scoreLCD) self.lowerLayout.addLayout(self.phaseLabelsLayout) self.lowerLayout.addLayout(self.checkboxLayout) self.iconlabel.setMinimumSize(60, 60) # self.scoreLCD.setMinimumWidth(100) # self.scoreLCD.setMaximumWidth(200) # self.scoreLCD.setMinimumHeight(60) # self.scoreLCD.setMaximumHeight(80) self.scoreLCD.display(self.engine.getScoreFromPlayer(self.player)) # Middle part - Phase list self.phaseLabels = list() for phase in range(1, 11): label = Phase10Label(phase, self) if phase == self.current_phase: label.setCurrent() elif self.engine.hasPhaseCompleted(self.player, phase): label.setPassed() self.phaseLabels.append(label) self.phaseLabelsLayout.addWidget( label, (phase-1)/5, (phase-1) % 5, 1, 1) # Middle part - Inputs self.roundWinnerRadioButton = QRadioButton() self.bgroup.addButton(self.roundWinnerRadioButton) self.checkboxLayout.addWidget(self.roundWinnerRadioButton) self.roundPhaseClearedCheckbox = QCheckBox(self) self.checkboxLayout.addWidget(self.roundPhaseClearedCheckbox) self.roundScore = Phase10ScoreSpinBox(self) self.roundScore.setMaximumWidth(90) self.roundScore.valueChanged.connect(self.updateRoundPhaseCleared) self.lowerLayout.addWidget(self.roundScore) self.roundWinnerRadioButton.toggled.connect( self.roundScore.setDisabled) self.roundWinnerRadioButton.toggled.connect( self.roundPhaseClearedCheckbox.setDisabled) self.roundWinnerRadioButton.toggled.connect( self.roundPhaseClearedCheckbox.setChecked) self.roundWinnerRadioButton.toggled.connect(self.roundWinnerSetAction) self.retranslateUI() def retranslateUI(self): self.roundWinnerRadioButton.setText( i18n("Phase10PlayerWidget", "Winner")) self.roundPhaseClearedCheckbox.setText( i18n("Phase10PlayerWidget", "Completed")) self.updatePhaseName() def updateDisplay(self, points, completed_phases, remaining_phases): if len(remaining_phases) == 0: self.current_phase = 0 else: self.current_phase = min(remaining_phases) self.roundWinnerRadioButton.setDown(True) if points >= 1000: self.scoreLCD.setNumDigits(4) self.scoreLCD.display(points) self.roundScore.setValue(5) self.roundScore.clear() self.roundPhaseClearedCheckbox.setChecked(False) for phase, label in enumerate(self.phaseLabels, start=1): if phase == self.current_phase and not self.engine.getWinner(): if not label.isCurrent(): label.setCurrent() elif phase in completed_phases: if not label.isPassed(): label.setPassed() else: if not label.isRemaining(): label.setRemaining() self.updatePhaseName() def getScore(self): if self.isRoundWinner(): return 0 try: return int(self.roundScore.value()) except Exception: return -1 def switchPhasesInOrder(self, in_order): self.phases_in_order = in_order if not self.phases_in_order: return self.phaseLabels[self.current_phase-1].setRemaining() for label in self.phaseLabels: if label.isRemaining(): label.setCurrent() self.current_phase = label.getNumber() break def updatePhaseSelected(self, phaselabel): if phaselabel.isRemaining(): self.current_phase = phaselabel.getNumber() for label in self.phaseLabels: if label.isCurrent(): label.setRemaining() phaselabel.setCurrent() self.updatePhaseName() def updatePhaseName(self): phasenames = getPhaseNames(self.engine.getPhases()) self.phaseNameLabel.setText(phasenames[self.current_phase-1]) def updateRoundPhaseCleared(self, value): try: score = int(self.roundScore.text()) except Exception: self.roundPhaseClearedCheckbox.setChecked(False) return if score < 0: if not self.roundWinnerRadioButton.isChecked(): self.roundPhaseClearedCheckbox.setChecked(False) return if (score % 5 != 0): return if (score >= 50): self.roundWinnerRadioButton.setChecked(False) self.roundPhaseClearedCheckbox.setChecked(False) elif (score == 0): self.roundWinnerRadioButton.setChecked(True) self.roundPhaseClearedCheckbox.setChecked(True) else: self.roundWinnerRadioButton.setChecked(False) self.roundPhaseClearedCheckbox.setChecked(True) def mousePressEvent(self, event): child = self.childAt(event.pos()) if child is None: self.roundScore.setFocus() elif type(child) == Phase10Label and not self.phases_in_order: self.updatePhaseSelected(child) return QGroupBox.mousePressEvent(self, event) # def isRoundWinner(self): return self.roundWinnerRadioButton.isChecked() def getRoundPhase(self): return self.current_phase def isRoundCleared(self): return self.roundPhaseClearedCheckbox.isChecked() def roundWinnerSetAction(self, isset): if isset: self.roundWinnerSet.emit(self.player) def reset(self): pass def finish(self): self.roundWinnerRadioButton.toggled.disconnect( self.roundScore.setDisabled) self.roundWinnerRadioButton.toggled.disconnect( self.roundPhaseClearedCheckbox.setDisabled) self.roundWinnerRadioButton.toggled.disconnect( self.roundPhaseClearedCheckbox.setChecked) self.roundWinnerRadioButton.toggled.disconnect( self.roundWinnerSetAction) self.roundWinnerRadioButton.setDisabled(True) self.roundPhaseClearedCheckbox.setDisabled(True) self.roundScore.setDisabled(True) def setColour(self, colour): self.pcolour = colour css = ("QGroupBox {{ font-size: 28px; font-weight: bold;" "color:rgb({},{},{});}}") self.setStyleSheet(css.format(self.pcolour.red(), self.pcolour.green(), self.pcolour.blue()))
class TestForm(QWidget): """Class for test window""" def __init__(self, question="", options=["", "", ""], right=""): """Initialize a quiz question window""" super().__init__(None) # main variables self.question_label = QLabel(question) self.variants_group = QGroupBox("Варіанти") self.v1 = QRadioButton(text=f"а) {options[0]}") self.v2 = QRadioButton(text=f"б) {options[1]}") self.v3 = QRadioButton(text=f"в) {options[2]}") self.send_answer_button = QPushButton("Відповісти") self.is_answer_correct_label = QLabel("") self.answer_variants_layout = QVBoxLayout() self.main_layout = QVBoxLayout() self.right_answer = right self.mark = 0 # set window organization self.answer_variants_layout.addWidget(self.v1) self.answer_variants_layout.addWidget(self.v2) self.answer_variants_layout.addWidget(self.v3) self.variants_group.setLayout(self.answer_variants_layout) self.main_layout.addWidget(self.question_label) self.main_layout.addWidget(self.variants_group) self.main_layout.addWidget(self.is_answer_correct_label) self.main_layout.addWidget(self.send_answer_button) self.setLayout(self.main_layout) # set a basis style self.setStyleSheet( "QWidget{background-color: aqua; font-weight: bold;}") self.setWindowTitle("Питання") try: self.setWindowIcon(QIcon(os.getcwd() + "/pictures/logo.png")) except: pass # set connections self.send_answer_button.clicked.connect(lambda: self.check_answer()) def check_answer(self): """To check is answer correct""" # make a message is_correct_message = QMessageBox() message = "" # unlock all buttons self.v1.setDisabled(True) self.v2.setDisabled(True) self.v3.setDisabled(True) self.send_answer_button.setDisabled(True) # answer check if ((self.right_answer == "1" and self.v1.isChecked()) or (self.right_answer == "2" and self.v2.isChecked()) or (self.right_answer == "3" and self.v3.isChecked())): message = "Правильно" self.mark = 1 else: message = "Неправильно\nПравильна відповідь: " if self.right_answer == "1": message += "а)" elif self.right_answer == "2": message += "б)" elif self.right_answer == "3": message += "в)" # show a result of answer self.is_answer_correct_label.setText(message) is_correct_message.setText(message) is_correct_message.exec_()
class NewsWindow(QDialog): def __init__(self, parent): super(NewsWindow, self).__init__(parent) self.parent = parent # top table - news list and filters self.table = QTableWidget(0, 5) horizLabels = ["", "", "", "", ""] self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setSelectionMode(QAbstractItemView.SingleSelection) self.table.itemSelectionChanged.connect(self.doDisplayNewsHeadline) self.table.setHorizontalHeaderLabels(horizLabels) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.table.setWordWrap(True) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) topLayout = QGridLayout() topLayout.addWidget(self.table, 0, 1) filterLayout = QBoxLayout(QBoxLayout.TopToBottom) self.filters = [ QPushButton(parent.graphics.icon[23 + i], "") for i in range(5) ] filterGroup = QButtonGroup() for i, j in zip(self.filters, range(5)): i.setFixedSize(120, 32) i.setAutoExclusive(True) i.setCheckable(True) i.released.connect(partial(self.doRefreshNews, j)) filterGroup.addButton(i) filterLayout.addWidget(i) filterLayout.addSpacing(-5) filterLayout.addSpacing(30) filterLayout.setAlignment(Qt.AlignVCenter) self.ctryList = QComboBox() self.ctryList.setMaxVisibleItems(10) self.ctryList.addItems([ Local.strings[Local.DATA_COUNTRIES + i][Local.CTRY_NAME] for i in range(80) ]) self.ctryList.currentIndexChanged.connect( partial(self.doRefreshNews, 5)) self.localNews = QRadioButton() self.localNews.released.connect(partial(self.doRefreshNews, 5)) filterGroup.addButton(self.localNews) filterLayout.addWidget(self.localNews) filterLayout.addWidget(self.ctryList) topLayout.addLayout(filterLayout, 0, 0) topLayout.setContentsMargins(-50, 0, 0, 0) self.table.setFixedHeight(220) # left half - news buttons = QBoxLayout(QBoxLayout.LeftToRight) leftLayout = QBoxLayout(QBoxLayout.TopToBottom) leftLayout.setContentsMargins(-80, 0, 0, 0) self.newsHline = QLabel() self.newsHline.setWordWrap(True) self.newsHline.setFixedHeight(40) leftLayout.addSpacing(25) leftLayout.addWidget(self.newsHline) leftLayout.addSpacing(30) self.question = QPushButton() self.backDown = QPushButton() self.question.released.connect(self.doTough) self.backDown.released.connect(self.doLoose) for i in (self.question, self.backDown): buttons.addWidget(i) leftLayout.addLayout(buttons) self.reactionLine = QLabel() self.reactionLine.setFixedHeight(30) self.reactionLine.setWordWrap(True) leftLayout.addSpacing(20) leftLayout.addWidget(self.reactionLine) leftLayout.addSpacing(20) leftInfoLayout = [QBoxLayout(QBoxLayout.LeftToRight) for i in range(3)] self.leftInfo = [QLabel() for i in range(3)] self.leftInfoVal = [QLabel() for i in range(3)] for i in range(3): leftInfoLayout[i].addWidget(self.leftInfo[i]) leftInfoLayout[i].addWidget(self.leftInfoVal[i]) leftLayout.addLayout(leftInfoLayout[i]) if i < 2: leftLayout.addSpacing(-5) # right half - advisory rightLayout = QBoxLayout(QBoxLayout.TopToBottom) rightLayout.setContentsMargins(0, -50, 0, 0) #rightLayout.addWidget(self.advisory) headsLayout = QBoxLayout(QBoxLayout.LeftToRight) headsColumn = [QBoxLayout(QBoxLayout.TopToBottom) for i in range(2)] head = [QBoxLayout(QBoxLayout.LeftToRight) for i in range(4)] self.picture = [QLabel() for i in range(4)] self.advice = [QLabel() for i in range(4)] for i in range(4): self.picture[i].setPixmap(parent.graphics.advisor[i]) self.advice[i].setWordWrap(True) self.advice[i].setFixedWidth(100) head[i].addWidget(self.picture[i]) head[i].addWidget(self.advice[i]) headsColumn[i // 2].addLayout(head[i]) self.closeUpButton = QPushButton() for i in range(2): headsLayout.addLayout(headsColumn[i]) rightLayout.addLayout(headsLayout) # save right and left layouts into groups self.detailGroup = [QGroupBox() for i in range(3)] self.detailGroup[0].setLayout(leftLayout) self.detailGroup[1].setLayout(rightLayout) self.detailGroup[2].setLayout(topLayout) mainLayout = QGridLayout() mainLayout.addWidget(self.detailGroup[2], 0, 0, 1, 2) for i in range(2): mainLayout.addWidget(self.detailGroup[i], 1, i) self.setStrings() self.setLayout(mainLayout) self.setFixedSize(830, 590) self.setModal(True) def filterCondition(self, n, mode): if mode == 0: return n.actor == self.parent.world.USA and n.new > n.old #USA Actions elif mode == 1: return n.actor == self.parent.world.USA and n.new < n.old #USA Other elif mode == 2: return n.actor == self.parent.world.USSR and n.new > n.old #USSR Actions elif mode == 3: return n.actor == self.parent.world.USSR and n.new < n.old #USSR Other elif mode == 4: return n.actor.id >= 2 #Minor actions elif mode == 6: return n.isQuestioned #AI turn - questions our moves else: #Filter by country return self.sortedCountries[self.ctryList.currentIndex()] in ( n.actor.id, n.target.id) def doRefreshNews(self, mode): """ Populate the table with event headlines filtered in accordance to the given 'mode' """ self.mode = mode if mode == 5: self.localNews.setChecked(True) news = self.parent.world.news self.table.setRowCount(0) # Filter the news and store successfully filtered objects in the self.news property self.news = [] for n in news: if self.filterCondition(n, mode): self.news.append(n) for i, n in zip(range(len(self.news)), self.news): self.table.insertRow(i) self.table.setItem( i, 0, QTableWidgetItem( QIcon(self.parent.graphics.flag[n.actor.id]), Local.strings[Local.DATA_COUNTRIES + n.actor.id][Local.CTRY_NAME])) self.table.setItem( i, 1, QTableWidgetItem( QIcon(self.parent.graphics.flag[n.target.id]), Local.strings[Local.DATA_COUNTRIES + n.target.id][Local.CTRY_NAME])) self.table.setItem(i, 2, QTableWidgetItem(n.getTypeName())) if n.action not in (0, 6): prefix = "\u25bc" if n.new < n.old else "\u25b2" else: prefix = "" self.table.setItem( i, 3, QTableWidgetItem(prefix + n.getActionValue(False))) checkedItem = QTableWidgetItem() checkedItem.setText("" if n.crisisVal else "✔") checkedItem.setTextAlignment(Qt.AlignCenter) self.table.setItem(i, 4, checkedItem) self.table.resizeRowsToContents() self.table.verticalHeader().setDefaultSectionSize(35) def showUp(self): mode = self._getCurrentMode() self.doRefreshNews(mode) self.setVisible(True) if mode == 6: #Reopen the window closed during AI questioning turn, resume AI actions doCrisis(self, self.parent.world, self.news[0]) def doDisplayNewsHeadline(self): rowNum = self.table.currentRow() if rowNum < 0: self.hideAdvisors() self.newsHline.setText("") self.closeUpButton.setEnabled(False) return headline = self.news[rowNum] self.newsHline.setText(headline.text) # Questionable policy - display advisory panel if not headline.crisisVal: self.question.setEnabled(True) self.backDown.setEnabled(False) for i in range(4): self.advice[i].setText( getAdvisorOpinion(self.parent.world, headline, i + 1)) self.picture[i].setVisible(True) else: self.hideAdvisors() def doLoose(self): """Action performed by releasing the 'back down' button""" doCHumanLoose(self, self.parent.world, self.news[self.table.currentRow()]) def doTough(self): """Action performed by releasing the 'question' button""" doCHumanTough(self, self.parent.world, self.news[self.table.currentRow()]) def hideAdvisors(self): self.backDown.setEnabled(False) self.question.setEnabled(False) for i in range(4): self.picture[i].setVisible(False) self.advice[i].setText("") self.setRiskValuesVisible(False) def setRiskValuesVisible(self, visible): for i, j, k in zip(self.leftInfo, self.leftInfoVal, range(3)): i.setText(Local.strings[Local.CRISIS_FILTER][22 + k] if visible else "") j.setText("") def setLocked(self, value): if not value: previousRow = self.table.currentRow() self.backDown.setText(Local.strings[Local.CRISIS_BD_BUTTON][0]) self.reactionLine.setText("") self.question.setDisabled(value) self.question.setText(Local.strings[Local.CRISIS_SUPER_BUTTON][9]) self.doRefreshNews(self._getCurrentMode()) self.table.selectRow(previousRow) self.setRiskValuesVisible(value) self.table.setDisabled(value) for i in self.filters: i.setDisabled(value) self.ctryList.setDisabled(value) self.localNews.setDisabled(value) def _getCurrentMode(self): if self.parent.world.beingQuestioned: return 6 if self.localNews.isChecked(): return 5 for i, j in zip(range(5), self.filters): if j.isChecked(): return i def endOfCrisis(self): self.setLocked(False) def setTableLocked(self, value): for i in self.filters: i.setEnabled(value) self.table.setEnabled(value) def reject(self): """Window can be closed during the crisis. If so, back down in the current crisis""" resBtn = QMessageBox.Yes w = self.parent.world beingQuestioned = w.beingQuestioned if (beingQuestioned or not self.table.isEnabled()) and not any( (w.ANWFlag, w.NWFlag, w.winFlag)): resBtn = QMessageBox.question( self, "Balance of Power", Local.strings[Local.CRISIS_FILTER][6] + (Local.strings[Local.CRISIS_FILTER][7] if beingQuestioned else ""), QMessageBox.Cancel | QMessageBox.Yes) if resBtn == QMessageBox.Yes: self.doLoose() self.setLocked(False) if beingQuestioned and len(self.news) == 0: w.beingQuestioned = False self.setVisible(False) continueNextTurn(self.parent, w) QDialog.reject(self) else: return QDialog.reject(self) def setStrings(self): self.table.setHorizontalHeaderLabels( Local.strings[Local.CRISIS_FILTER][8:13]) for i in range(5): if i < 3: self.detailGroup[i].setTitle( Local.strings[Local.CRISIS_FILTER][i + 25]) self.filters[i].setText(Local.strings[Local.CRISIS_FILTER][i]) while self.ctryList.count() > 0: self.ctryList.removeItem(0) ctryNames = [ Local.strings[Local.DATA_COUNTRIES + i][Local.CTRY_NAME] for i in range(len(self.parent.world.country)) ] self.sortedCountries = sorted(range(len(ctryNames)), key=ctryNames.__getitem__) self.ctryList.addItems([ ctryNames[self.sortedCountries[i]] for i in range(len(ctryNames)) ]) for i in range(len(ctryNames)): self.ctryList.setItemIcon( i, QIcon(self.parent.graphics.flag[self.sortedCountries[i]])) self.localNews.setText(Local.strings[Local.CRISIS_FILTER][5]) self.question.setText(Local.strings[Local.CRISIS_SUPER_BUTTON][9]) self.backDown.setText(Local.strings[Local.CRISIS_BD_BUTTON][0]) self.reactionLine.setText("") self.newsHline.setText("")
class TimekeepingPropertiesDialog(QDialog): def __init__(self): super().__init__(GlobalAccess().get_main_window()) self.time_format = 'hh:mm:ss' def exec(self): self.init_ui() return super().exec() def init_ui(self): # self.setFixedWidth(500) self.setWindowTitle(_('Timekeeping settings')) # self.setWindowIcon(QIcon(icon_dir('sportident.png'))) self.setSizeGripEnabled(False) self.setModal(True) self.tab_widget = QTabWidget() # timekeeping tab self.timekeeping_tab = QWidget() self.tk_layout = QFormLayout() self.label_zero_time = QLabel(_('Zero time')) self.item_zero_time = QTimeEdit() self.item_zero_time.setDisplayFormat("HH:mm") self.item_zero_time.setMaximumSize(60, 20) self.item_zero_time.setDisabled(True) self.tk_layout.addRow(self.label_zero_time, self.item_zero_time) self.label_si_port = QLabel(_('Available Ports')) self.item_si_port = AdvComboBox() self.item_si_port.addItems(SIReaderClient().get_ports()) self.tk_layout.addRow(self.label_si_port, self.item_si_port) self.start_group_box = QGroupBox(_('Start time')) self.start_layout = QFormLayout() self.item_start_protocol = QRadioButton(_('From protocol')) self.start_layout.addRow(self.item_start_protocol) self.item_start_station = QRadioButton(_('Start station')) self.start_layout.addRow(self.item_start_station) self.item_start_cp = QRadioButton(_('Control point')) self.item_start_cp_value = QSpinBox() self.item_start_cp_value.setMaximumSize(60, 20) self.start_layout.addRow(self.item_start_cp, self.item_start_cp_value) self.item_start_gate = QRadioButton(_('Start gate')) self.item_start_gate.setDisabled(True) self.start_layout.addRow(self.item_start_gate) self.start_group_box.setLayout(self.start_layout) self.tk_layout.addRow(self.start_group_box) self.finish_group_box = QGroupBox(_('Finish time')) self.finish_layout = QFormLayout() self.item_finish_station = QRadioButton(_('Finish station')) self.finish_layout.addRow(self.item_finish_station) self.item_finish_cp = QRadioButton(_('Control point')) self.item_finish_cp_value = QSpinBox() self.item_finish_cp_value.setMinimum(-1) self.item_finish_cp_value.setMaximumSize(60, 20) self.finish_layout.addRow(self.item_finish_cp, self.item_finish_cp_value) self.item_finish_beam = QRadioButton(_('Light beam')) self.item_finish_beam.setDisabled(True) self.finish_layout.addRow(self.item_finish_beam) self.finish_group_box.setLayout(self.finish_layout) self.tk_layout.addRow(self.finish_group_box) self.chip_reading_box = QGroupBox(_('Assigning a chip when reading')) self.chip_reading_layout = QFormLayout() self.chip_reading_off = QRadioButton(_('Off')) self.chip_reading_layout.addRow(self.chip_reading_off) self.chip_reading_unknown = QRadioButton(_('Only unknown members')) self.chip_reading_layout.addRow(self.chip_reading_unknown) self.chip_reading_always = QRadioButton(_('Always')) self.chip_reading_layout.addRow(self.chip_reading_always) self.chip_reading_box.setLayout(self.chip_reading_layout) self.tk_layout.addRow(self.chip_reading_box) self.assignment_mode = QCheckBox(_('Assignment mode')) self.assignment_mode.stateChanged.connect(self.on_assignment_mode) self.tk_layout.addRow(self.assignment_mode) self.timekeeping_tab.setLayout(self.tk_layout) # result processing tab self.result_proc_tab = QWidget() self.result_proc_layout = QFormLayout() self.rp_time_radio = QRadioButton(_('by time')) self.result_proc_layout.addRow(self.rp_time_radio) self.rp_scores_radio = QRadioButton(_('by scores')) self.rp_scores_radio.setDisabled(True) # TODO self.result_proc_layout.addRow(self.rp_scores_radio) self.rp_scores_group = QGroupBox() self.rp_scores_group.setDisabled(True) # TODO self.rp_scores_layout = QFormLayout(self.rp_scores_group) self.rp_rogain_scores_radio = QRadioButton(_('rogain scores')) self.rp_scores_layout.addRow(self.rp_rogain_scores_radio) self.rp_fixed_scores_radio = QRadioButton(_('fixed scores')) self.rp_fixed_scores_edit = QSpinBox() self.rp_fixed_scores_edit.setMaximumWidth(50) self.rp_scores_layout.addRow(self.rp_fixed_scores_radio, self.rp_fixed_scores_edit) self.rp_scores_minute_penalty_label = QLabel(_('minute penalty')) self.rp_scores_minute_penalty_edit = QSpinBox() self.rp_scores_minute_penalty_edit.setMaximumWidth(50) self.rp_scores_layout.addRow(self.rp_scores_minute_penalty_label, self.rp_scores_minute_penalty_edit) self.result_proc_layout.addRow(self.rp_scores_group) self.result_proc_tab.setLayout(self.result_proc_layout) # marked route settings self.marked_route_tab = QWidget() self.mr_layout = QFormLayout() self.mr_off_radio = QRadioButton(_('no penalty')) self.mr_layout.addRow(self.mr_off_radio) self.mr_time_radio = QRadioButton(_('penalty time')) self.mr_time_edit = QTimeEdit() self.mr_time_edit.setDisplayFormat(self.time_format) self.mr_layout.addRow(self.mr_time_radio, self.mr_time_edit) self.mr_laps_radio = QRadioButton(_('penalty laps')) self.mr_layout.addRow(self.mr_laps_radio) self.mr_counting_lap_check = QCheckBox(_('counting lap')) self.mr_counting_lap_check.setDisabled(True) # TODO self.mr_layout.addRow(self.mr_counting_lap_check) self.mr_lap_station_check = QCheckBox(_('lap station')) self.mr_lap_station_check.setDisabled(True) # TODO self.mr_lap_station_edit = QSpinBox() self.mr_lap_station_edit.setMaximumWidth(50) self.mr_layout.addRow(self.mr_lap_station_check, self.mr_lap_station_edit) self.marked_route_tab.setLayout(self.mr_layout) # scores """ Scores [ x ] scores array 40, 37, 35, 33, ... 2, 1 [ Edit ] [ ] scores formula 1000 - 1000 * result / leader [ Edit ] """ self.scores_tab = QWidget() self.scores_layout = QFormLayout() self.scores_off = QRadioButton(_('scores off')) self.scores_array = QRadioButton(_('scores array')) self.scores_array_edit = QLineEdit() self.scores_formula = QRadioButton(_('scores formula')) self.scores_formula_edit = QLineEdit() self.scores_formula_hint = QLabel(_('scores formula hint')) self.scores_formula_hint.setWordWrap(True) self.scores_layout.addRow(self.scores_off) self.scores_layout.addRow(self.scores_array) self.scores_layout.addRow(self.scores_array_edit) self.scores_layout.addRow(self.scores_formula) self.scores_layout.addRow(self.scores_formula_edit) self.scores_layout.addRow(self.scores_formula_hint) self.scores_tab.setLayout(self.scores_layout) # time settings self.time_settings_tab = QWidget() self.time_settings_layout = QFormLayout() self.time_settings_accuracy_label = QLabel(_('Accuracy')) self.time_settings_accuracy_edit = QSpinBox() self.time_settings_accuracy_edit.setMaximumWidth(50) self.time_settings_accuracy_edit.setMaximum(3) self.time_settings_layout.addRow(self.time_settings_accuracy_label, self.time_settings_accuracy_edit) self.time_settings_format = QGroupBox() self.time_settings_format.setTitle(_('Format of competitions')) self.time_settings_format_less = QRadioButton(_('< 24')) self.time_settings_format_more = QRadioButton(_('> 24')) self.time_settings_format_layout = QFormLayout() self.time_settings_format_layout.addRow(self.time_settings_format_less) self.time_settings_format_layout.addRow(self.time_settings_format_more) self.time_settings_format.setLayout(self.time_settings_format_layout) self.time_settings_layout.addRow(self.time_settings_format) self.time_settings_tab.setLayout(self.time_settings_layout) self.tab_widget.addTab(self.timekeeping_tab, _('SPORTident (Sportiduino, ...) settings')) self.tab_widget.addTab(self.result_proc_tab, _('Result processing')) self.tab_widget.addTab(self.scores_tab, _('Scores')) self.tab_widget.addTab(self.marked_route_tab, _('Penalty calculation')) self.tab_widget.addTab(self.time_settings_tab, _('Time settings')) def cancel_changes(): self.close() def apply_changes(): try: self.apply_changes_impl() except Exception as e: logging.error(str(e)) self.close() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.button_ok = button_box.button(QDialogButtonBox.Ok) self.button_ok.setText(_('OK')) self.button_ok.clicked.connect(apply_changes) self.button_cancel = button_box.button(QDialogButtonBox.Cancel) self.button_cancel.setText(_('Cancel')) self.button_cancel.clicked.connect(cancel_changes) self.layout = QFormLayout(self) self.layout.addRow(self.tab_widget) self.layout.addRow(button_box) self.set_values_from_model() self.show() def on_assignment_mode(self): mode = False if self.assignment_mode.isChecked(): mode = True self.start_group_box.setDisabled(mode) self.finish_group_box.setDisabled(mode) self.chip_reading_box.setDisabled(mode) def set_values_from_model(self): cur_race = race() zero_time = cur_race.get_setting('system_zero_time', (8, 0, 0)) start_source = cur_race.get_setting('system_start_source', 'protocol') start_cp_number = cur_race.get_setting('system_start_cp_number', 31) finish_source = cur_race.get_setting('system_finish_source', 'station') finish_cp_number = cur_race.get_setting('system_finish_cp_number', 90) assign_chip_reading = cur_race.get_setting('system_assign_chip_reading', 'off') assignment_mode = cur_race.get_setting('system_assignment_mode', False) si_port = cur_race.get_setting('system_port', '') self.item_zero_time.setTime(QTime(zero_time[0], zero_time[1])) self.item_si_port.setCurrentText(si_port) if start_source == 'protocol': self.item_start_protocol.setChecked(True) elif start_source == 'station': self.item_start_station.setChecked(True) elif start_source == 'cp': self.item_start_cp.setChecked(True) elif start_source == 'gate': self.item_start_gate.setChecked(True) self.item_start_cp_value.setValue(start_cp_number) if finish_source == 'station': self.item_finish_station.setChecked(True) elif finish_source == 'cp': self.item_finish_cp.setChecked(True) elif finish_source == 'beam': self.item_finish_beam.setChecked(True) self.item_finish_cp_value.setValue(finish_cp_number) if assign_chip_reading == 'off': self.chip_reading_off.setChecked(True) elif assign_chip_reading == 'only_unknown_members': self.chip_reading_unknown.setChecked(True) elif assign_chip_reading == 'always': self.chip_reading_always.setChecked(True) self.assignment_mode.setChecked(assignment_mode) # result processing obj = cur_race rp_mode = obj.get_setting('result_processing_mode', 'time') rp_score_mode = obj.get_setting('result_processing_score_mode', 'rogain') rp_fixed_scores_value = obj.get_setting('result_processing_fixed_score_value', 1) rp_scores_minute_penalty = obj.get_setting('result_processing_scores_minute_penalty', 1) if rp_mode == 'time': self.rp_time_radio.setChecked(True) else: self.rp_scores_radio.setChecked(True) if rp_score_mode == 'rogain': self.rp_rogain_scores_radio.setChecked(True) else: self.rp_fixed_scores_radio.setChecked(True) self.rp_fixed_scores_edit.setValue(rp_fixed_scores_value) self.rp_scores_minute_penalty_edit.setValue(rp_scores_minute_penalty) # penalty calculation mr_mode = obj.get_setting('marked_route_mode', 'off') mr_penalty_time = OTime(msec=obj.get_setting('marked_route_penalty_time', 60000)) mr_if_counting_lap = obj.get_setting('marked_route_if_counting_lap', True) mr_if_station_check = obj.get_setting('marked_route_if_station_check', False) mr_station_code = obj.get_setting('marked_route_station_code', 80) if mr_mode == 'off': self.mr_off_radio.setChecked(True) elif mr_mode == 'time': self.mr_time_radio.setChecked(True) else: self.mr_laps_radio.setChecked(True) self.mr_time_edit.setTime(mr_penalty_time.to_time()) self.mr_counting_lap_check.setChecked(mr_if_counting_lap) self.mr_lap_station_check.setChecked(mr_if_station_check) self.mr_lap_station_edit.setValue(mr_station_code) # score settings scores_mode = obj.get_setting('scores_mode', 'off') scores_array = obj.get_setting('scores_array', '40,37,35,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,' '16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1') scores_formula = obj.get_setting('scores_formula', '200 - 100 * time / leader') if scores_mode == 'off': self.scores_off.setChecked(True) elif scores_mode == 'array': self.scores_array.setChecked(True) elif scores_mode == 'formula': self.scores_formula.setChecked(True) self.scores_array_edit.setText(scores_array) self.scores_formula_edit.setText(scores_formula) # time settings time_accuracy = obj.get_setting('time_accuracy', 0) time_format_24 = obj.get_setting('time_format_24', 'less24') self.time_settings_accuracy_edit.setValue(time_accuracy) if time_format_24 == 'less24': self.time_settings_format_less.setChecked(True) elif time_format_24 == 'more24': self.time_settings_format_more.setChecked(True) def apply_changes_impl(self): obj = race() start_source = 'protocol' if self.item_start_station.isChecked(): start_source = 'station' elif self.item_start_cp.isChecked(): start_source = 'cp' elif self.item_start_gate.isChecked(): start_source = 'gate' finish_source = 'station' if self.item_finish_cp.isChecked(): finish_source = 'cp' elif self.item_finish_beam.isChecked(): finish_source = 'beam' assign_chip_reading = 'off' if self.chip_reading_unknown.isChecked(): assign_chip_reading = 'only_unknown_members' elif self.chip_reading_always.isChecked(): assign_chip_reading = 'always' start_cp_number = self.item_start_cp_value.value() finish_cp_number = self.item_finish_cp_value.value() old_start_cp_number = obj.get_setting('system_start_cp_number', 31) old_finish_cp_number = obj.get_setting('system_finish_cp_number', 90) if old_start_cp_number != start_cp_number or old_finish_cp_number != finish_cp_number: race().clear_results() obj.set_setting('system_port', self.item_si_port.currentText()) obj.set_setting('system_start_source', start_source) obj.set_setting('system_finish_source', finish_source) obj.set_setting('system_start_cp_number', start_cp_number) obj.set_setting('system_finish_cp_number', finish_cp_number) obj.set_setting('system_assign_chip_reading', assign_chip_reading) obj.set_setting('system_assignment_mode', self.assignment_mode.isChecked()) # result processing rp_mode = 'time' if self.rp_scores_radio.isChecked(): rp_mode = 'scores' rp_score_mode = 'rogain' if self.rp_fixed_scores_radio.isChecked(): rp_score_mode = 'fixed' rp_fixed_scores_value = self.rp_fixed_scores_edit.value() rp_scores_minute_penalty = self.rp_scores_minute_penalty_edit.value() obj.set_setting('result_processing_mode', rp_mode) obj.set_setting('result_processing_score_mode', rp_score_mode) obj.set_setting('result_processing_fixed_score_value', rp_fixed_scores_value) obj.set_setting('result_processing_scores_minute_penalty', rp_scores_minute_penalty) # marked route mr_mode = 'off' if self.mr_laps_radio.isChecked(): mr_mode = 'laps' if self.mr_time_radio.isChecked(): mr_mode = 'time' obj.set_setting('marked_route_mode', mr_mode) mr_penalty_time = time_to_otime(self.mr_time_edit.time()).to_msec() mr_if_counting_lap = self.mr_counting_lap_check.isChecked() mr_if_station_check = self.mr_lap_station_check.isChecked() mr_station_code = self.mr_lap_station_edit.value() obj.set_setting('marked_route_mode', mr_mode) obj.set_setting('marked_route_penalty_time', mr_penalty_time) obj.set_setting('marked_route_if_counting_lap', mr_if_counting_lap) obj.set_setting('marked_route_if_station_check', mr_if_station_check) obj.set_setting('marked_route_station_code', mr_station_code) # score settings scores_mode = 'off' if self.scores_array.isChecked(): scores_mode = 'array' elif self.scores_formula.isChecked(): scores_mode = 'formula' scores_array = self.scores_array_edit.text() scores_formula = self.scores_formula_edit.text() obj.set_setting('scores_mode', scores_mode) obj.set_setting('scores_array', scores_array) obj.set_setting('scores_formula', scores_formula) # time settings time_accuracy = self.time_settings_accuracy_edit.value() time_format_24 = 'less24' if self.time_settings_format_more.isChecked(): time_format_24 = 'more24' obj.set_setting('time_accuracy', time_accuracy) obj.set_setting('time_format_24', time_format_24) ResultCalculation(race()).process_results() GlobalAccess().get_main_window().refresh()
class TrainingPanel(Panel): def __init__(self, datasets, testing_panel): super().__init__() if isinstance(testing_panel, TestingPanel): self.testing_panel = testing_panel else: raise TypeError('"testing_panel" must be the instance of ' '"TestingPanel"') self.datasets = datasets self.__set_execution_ui() self.__set_options_ui() self.__set_outputs_ui() self.__set_graphic_ui() def __set_execution_ui(self): group_box = QGroupBox('Training Execution') inner_layout = QHBoxLayout() group_box.setLayout(inner_layout) self.data_selector = QComboBox() self.data_selector.addItems(self.datasets.keys()) self.data_selector.setStatusTip('Select the training dataset.') self.start_btn = QPushButton('Train') self.start_btn.setStatusTip('Start training.') self.start_btn.clicked.connect(self.__run) self.stop_btn = QPushButton('Stop') self.stop_btn.setStatusTip('Force the training stop running.') self.stop_btn.setDisabled(True) self.multicore_cb = QCheckBox('Multicore') self.multicore_cb.setStatusTip('Use multiprocessing in calculating ' 'fitting for populations.') self.multicore_cb.setChecked(True) inner_layout.addWidget(self.data_selector, 1) inner_layout.addWidget(self.start_btn) inner_layout.addWidget(self.stop_btn) inner_layout.addWidget(self.multicore_cb) self._layout.addWidget(group_box) def __set_options_ui(self): group_box = QGroupBox('Training Options') inner_layout = QFormLayout() group_box.setLayout(inner_layout) self.iter_times = QSpinBox() self.iter_times.setRange(1, 1000000) self.iter_times.setValue(300) self.iter_times.setStatusTip('The total iterating times for training.') self.population_size = QSpinBox() self.population_size.setRange(1, 100000000) self.population_size.setValue(100) self.population_size.setStatusTip('The population size for genetic ' 'algorithm.') self.reproduction = QHBoxLayout() self.roulette_wheel_selection = QRadioButton('Roulette Wheel') self.tournament_selection = QRadioButton('Tournament') self.reproduction.addWidget(self.roulette_wheel_selection) self.reproduction.addWidget(self.tournament_selection) self.roulette_wheel_selection.toggle() self.score_amplifier = QDoubleSpinBox() self.score_amplifier.setRange(1, 3) self.score_amplifier.setValue(1.7) self.score_amplifier.setSingleStep(0.01) self.score_amplifier.setStatusTip('Amplify the winner score in ' 'selection (exponentially).') self.p_crossover = QDoubleSpinBox() self.p_crossover.setRange(0, 1) self.p_crossover.setValue(0.5) self.p_crossover.setSingleStep(0.1) self.p_crossover.setStatusTip('The probability of crossover for ' 'genetic algorithm.') self.p_mutation = QDoubleSpinBox() self.p_mutation.setRange(0, 1) self.p_mutation.setValue(0.5) self.p_mutation.setSingleStep(0.1) self.p_mutation.setStatusTip('The probability of mutation for ' 'genetic algorithm.') self.mutation_scale = QDoubleSpinBox() self.mutation_scale.setDecimals(3) self.mutation_scale.setRange(0.001, 0.5) self.mutation_scale.setValue(0.1) self.mutation_scale.setSingleStep(0.1) self.mutation_scale.setStatusTip( 'The scale of random noise in ' 'mutation for genetic algorithm. Full ' 'scale (s=1) creates the noise which ' 'range is the domain of parameter of ' 'chromosome itself.') self.nneuron = QSpinBox() self.nneuron.setRange(1, 1000) self.nneuron.setValue(6) self.nneuron.setStatusTip('The number of RBFN neuron.') self.sd_max = QDoubleSpinBox() self.sd_max.setRange(0.01, 20) self.sd_max.setValue(10) self.sd_max.setSingleStep(0.1) self.sd_max.setStatusTip('The maximum of standard deviation of each ' 'neuron in RBFN (only for initialization).') inner_layout.addRow('Iterating Times:', self.iter_times) inner_layout.addRow('Population Size:', self.population_size) inner_layout.addRow('Reproduction:', self.reproduction) inner_layout.addRow('Score Amplifier:', self.score_amplifier) inner_layout.addRow('Crossover Probability:', self.p_crossover) inner_layout.addRow('Mutation Probability:', self.p_mutation) inner_layout.addRow('Mutation Scale:', self.mutation_scale) inner_layout.addRow('Number of Neuron:', self.nneuron) inner_layout.addRow('Maximum of SD:', self.sd_max) self._layout.addWidget(group_box) def __set_outputs_ui(self): group_box = QGroupBox('Training Details') inner_layout = QFormLayout() group_box.setLayout(inner_layout) self.current_iter_time = QLabel('--') self.current_error = QLabel('--') self.avg_error = QLabel('--') self.least_error = QLabel('--') self.progressbar = QProgressBar() self.current_iter_time.setAlignment(Qt.AlignCenter) self.current_error.setAlignment(Qt.AlignCenter) self.avg_error.setAlignment(Qt.AlignCenter) self.least_error.setAlignment(Qt.AlignCenter) self.current_iter_time.setStatusTip('The current iterating time of ' 'genetic algorithm.') self.current_error.setStatusTip('The current error from the fitting ' 'function.') self.avg_error.setStatusTip('The average error from the fitting ' 'function in current iteration.') self.least_error.setStatusTip('The least error from the fitting ' 'function in training.') inner_layout.addRow('Current Iterating Time:', self.current_iter_time) inner_layout.addRow('Current Error:', self.current_error) inner_layout.addRow('Average Error:', self.avg_error) inner_layout.addRow('Least Error:', self.least_error) inner_layout.addRow(self.progressbar) self._layout.addWidget(group_box) def __set_graphic_ui(self): group_box = QGroupBox('Error Line Charts:') inner_layout = QVBoxLayout() group_box.setLayout(inner_layout) self.err_chart = ErrorLineChart(1) self.err_chart.setStatusTip('The history of error from the fitting ' 'of genetic algorithm for each data.') self.__err_x = 1 self.iter_err_chart = ErrorLineChart(2, ('Avg', 'Least')) self.iter_err_chart.setStatusTip('The history of average and least ' 'error from the fitting of genetic ' 'algorithm for each iteration.') self.iter_err_chart.setMinimumHeight(150) inner_layout.addWidget(QLabel('Current Error')) inner_layout.addWidget(self.err_chart) inner_layout.addWidget(QLabel('Average Error')) inner_layout.addWidget(self.iter_err_chart) self._layout.addWidget(group_box) @pyqtSlot() def __init_widgets(self): self.start_btn.setDisabled(True) self.stop_btn.setEnabled(True) self.multicore_cb.setDisabled(True) self.data_selector.setDisabled(True) self.iter_times.setDisabled(True) self.population_size.setDisabled(True) self.score_amplifier.setDisabled(True) self.roulette_wheel_selection.setDisabled(True) self.tournament_selection.setDisabled(True) self.p_crossover.setDisabled(True) self.p_mutation.setDisabled(True) self.mutation_scale.setDisabled(True) self.nneuron.setDisabled(True) self.sd_max.setDisabled(True) self.err_chart.clear() self.iter_err_chart.clear() self.__err_x = 1 @pyqtSlot() def __reset_widgets(self): self.start_btn.setEnabled(True) self.stop_btn.setDisabled(True) self.multicore_cb.setEnabled(True) self.data_selector.setEnabled(True) self.iter_times.setEnabled(True) self.population_size.setEnabled(True) self.score_amplifier.setEnabled(True) self.roulette_wheel_selection.setEnabled(True) self.tournament_selection.setEnabled(True) self.p_crossover.setEnabled(True) self.p_mutation.setEnabled(True) self.mutation_scale.setEnabled(True) self.nneuron.setEnabled(True) self.sd_max.setEnabled(True) @pyqtSlot(int) def __show_current_iter_time(self, value): self.current_iter_time.setText(str(value + 1)) self.progressbar.setValue(value + 1) @pyqtSlot(float) def __show_current_error(self, value): self.current_error.setText('{:.7f}'.format(value)) self.err_chart.append_point(self.__err_x, value) self.__err_x += 1 @pyqtSlot(float, float) def __show_iter_error(self, avg, least): self.avg_error.setText('{:.7f}'.format(avg)) self.least_error.setText('{:.7f}'.format(least)) self.iter_err_chart.append_point(int(self.current_iter_time.text()), least, 1) self.iter_err_chart.append_point(int(self.current_iter_time.text()), avg, 0) def __run(self): self.progressbar.setMaximum(self.iter_times.value()) self.__current_dataset = self.datasets[ self.data_selector.currentText()] mean_range = (min(min(d.i) for d in self.__current_dataset), max(max(d.i) for d in self.__current_dataset)) if self.roulette_wheel_selection.isChecked(): reproduction_method = 'rw' else: reproduction_method = 't' rbfn = RBFN(self.nneuron.value(), mean_range, self.sd_max.value()) self.__ga = GA(self.iter_times.value(), self.population_size.value(), reproduction_method, self.p_crossover.value(), self.p_mutation.value(), self.mutation_scale.value(), rbfn, self.__current_dataset, mean_range, self.sd_max.value(), score_amplifier=self.score_amplifier.value(), is_multicore=self.multicore_cb.isChecked()) self.stop_btn.clicked.connect(self.__ga.stop) self.__ga.started.connect(self.__init_widgets) self.__ga.finished.connect(self.__reset_widgets) self.__ga.sig_current_iter_time.connect(self.__show_current_iter_time) self.__ga.sig_current_error.connect(self.__show_current_error) self.__ga.sig_iter_error.connect(self.__show_iter_error) self.__ga.sig_console.connect(self.testing_panel.print_console) self.__ga.sig_rbfn.connect(self.testing_panel.load_rbfn) self.__ga.start()
class MainWindow(QMainWindow): def __init__(self, args): super().__init__() setting_values = { "img_dir": args.directory, "canvas_width": int(args.width), "canvas_height": int(args.height) } self.img_dir = setting_values["img_dir"] self.img_paths = get_image_paths(self.img_dir) if len(self.img_paths) == 0: self.close() raise BaseException("0 image detected") self.result_path = os.path.join("results", os.path.split(self.img_dir)[-1]) os.makedirs(self.result_path, exist_ok=True) self.positive_path = os.path.join(self.result_path, "positive") os.makedirs(self.positive_path, exist_ok=True) self.negative_path = os.path.join(self.result_path, "negative") os.makedirs(self.negative_path, exist_ok=True) self.mask_path = os.path.join(self.result_path, "mask") os.makedirs(self.mask_path, exist_ok=True) self.negative_mask_path = os.path.join(self.result_path, "neg_mask") os.makedirs(self.negative_mask_path, exist_ok=True) self.label_path = os.path.join(self.result_path, "annotations") os.makedirs(self.label_path, exist_ok=True) # Define widgets self.canvas = Canvas(width=setting_values["canvas_width"], height=setting_values["canvas_height"]) self.canvas.setWindowFlags(Qt.FramelessWindowHint) self.label_index = 0 self.label_index_w = QLabel( f"{self.label_index + 1} / {len(self.img_paths)}") self.before_btn = QPushButton("◀") self.next_btn = QPushButton("▶") self.crop_btn = QPushButton("Go!") self.crop_size = QLineEdit("500") self.stride = QLineEdit("100") self.example_btn = QPushButton("Example") self.example_btn.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.poly_radio = QRadioButton('polygon') self.poly_radio.setChecked(True) self.box_radio = QRadioButton('bbox') self.box_radio.setDisabled(True) # Set events self.before_btn.clicked.connect(lambda: self.move_index(-1)) self.next_btn.clicked.connect(lambda: self.move_index(+1)) self.crop_btn.clicked.connect(self.crop_image) self.crop_size.setValidator(QIntValidator()) self.stride.setValidator(QIntValidator()) self.example_btn.clicked.connect(self.show_example) self.poly_radio.toggled.connect(self.change_ann_mode) self.box_radio.toggled.connect(self.change_ann_mode) # Layout self.setStyleSheet( "font-size: 20px; font-weight: bold; font-family: Arial") w = QWidget() gl = QVBoxLayout() il = QHBoxLayout() il.addWidget(self.label_index_w) il.addWidget(self.before_btn) il.addWidget(self.next_btn) gl.addItem(il) # setting layout sl = QGridLayout() sl.setSpacing(4) sl.addWidget(QLabel("Crop Size"), 0, 0, 1, 1) sl.addWidget(self.crop_size, 0, 1, 1, 2) sl.addWidget(QLabel("Stride"), 1, 0, 1, 1) sl.addWidget(self.stride, 1, 1, 1, 2) sl.addWidget(self.example_btn, 0, 3, 2, 1) gl.addItem(sl) mode_chbx_group = QGroupBox("Annotation Mode") chl = QHBoxLayout() chl.addWidget(self.poly_radio) chl.addWidget(self.box_radio) mode_chbx_group.setLayout(chl) gl.addWidget(mode_chbx_group) gl.addWidget(self.crop_btn) w.setLayout(gl) self.setCentralWidget(w) img_name = os.path.splitext( os.path.split(self.img_paths[self.label_index])[-1])[0] self.setWindowTitle(img_name) self.canvas.SetImage(self.img_paths[self.label_index], os.path.join(self.label_path, img_name + ".txt")) self.show() self.move(30, 30) self.canvas.move(self.x() + self.width() + 15, self.y()) self.canvas.show() def move_index(self, x): self.label_index = (self.label_index + len(self.img_paths) + x) % len( self.img_paths) self.label_index_w.setText( f"{self.label_index + 1} / {len(self.img_paths)}") img_name = os.path.splitext( os.path.split(self.img_paths[self.label_index])[-1])[0] self.setWindowTitle(img_name) self.canvas.SetImage(self.img_paths[self.label_index], os.path.join(self.label_path, img_name + ".txt")) def change_ann_mode(self): if self.poly_radio.isChecked(): self.canvas.change_mode('poly') else: self.canvas.change_mode('box') def crop_image(self): self.crop_btn.setEnabled(False) self.next_btn.setEnabled(False) self.before_btn.setEnabled(False) img = cv2.imread(self.img_paths[self.label_index]) height, width = img.shape[:2] img_name = os.path.splitext( os.path.split(self.img_paths[self.label_index])[-1])[0] # load negative annotation polys = self.canvas.getAnns().copy() for i, poly in enumerate(polys): for j, point in enumerate(poly): polys[i][j] = [int(point[0] * width), int(point[1] * height)] # draw mask mask_img = np.zeros((height, width), dtype=np.uint8) for poly in polys: mask_img = draw_mask(mask_img, poly) # save mask img (whole) cv2.imwrite(os.path.join(self.mask_path, img_name + ".png"), mask_img * 255) # crop img crop_size = int(self.crop_size.text()) stride = int(self.stride.text()) if crop_size != 0: start_xs = list(range(0, width - crop_size, stride)) start_ys = list(range(0, height - crop_size, stride)) positive_index = 0 negative_index = 0 total_step = len(start_xs) * len(start_ys) progress_idx = 0 for x1 in start_xs: for y1 in start_ys: x2 = x1 + crop_size y2 = y1 + crop_size inter_area = np.sum(mask_img[y1:y2, x1:x2]) if inter_area == 0: cv2.imwrite( os.path.join(self.positive_path, f"{img_name}_{positive_index}.png"), img[y1:y2, x1:x2, :]) positive_index += 1 elif inter_area > 0: cv2.imwrite( os.path.join(self.negative_path, f"{img_name}_{negative_index}.png"), img[y1:y2, x1:x2, :]) cv2.imwrite( os.path.join(self.negative_mask_path, f"{img_name}_{negative_index}.png"), mask_img[y1:y2, x1:x2] * 255) negative_index += 1 progress_idx += 1 self.crop_btn.setText( f"{int(progress_idx/total_step*100)} %") QtTest.QTest.qWait(1) self.crop_btn.setEnabled(True) self.next_btn.setEnabled(True) self.before_btn.setEnabled(True) self.crop_btn.setText("Go!") def show_example(self): self.canvas.show_example(int(self.crop_size.text()), int(self.stride.text())) def closeEvent(self, e): try: self.canvas.close() except: pass self.close() def moveEvent(self, e): self.canvas.move(self.x() + self.width() + 15, self.y())
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.SavBool = False self.SaveChk = 0 self.chkMin = QCheckBox('-', self) self.chkSave = QCheckBox('Save', self) self.s = 0 self.lbl = QLabel(self) self.lblCheck = QLabel(self) self.txtNum = QLineEdit(self) self.btnAdd = QRadioButton('+', self) self.btnCon = QRadioButton('*', self) self.btnDiv = QRadioButton('/', self) btnReturn = QPushButton('Return', self) btnOk = QPushButton('Ok', self) btnEnd = QPushButton('Закончить ввод', self) self.btnAdd.setGeometry(170, 30, 50, 50) self.btnCon.setGeometry(170, 60, 50, 50) self.btnDiv.setGeometry(170, 90, 50, 50) btnOk.setGeometry(70, 80, 50, 20) self.chkMin.move(20, 50) self.chkSave.move(20, 100) btnReturn.setGeometry(20, 120, 70, 20) btnEnd.setGeometry(50, 180, 100, 30) self.txtNum.setGeometry(60, 50, 70, 20) btnOk.clicked.connect(self.btnOkClicked) btnEnd.clicked.connect(self.btnEndClicked) btnReturn.clicked.connect(self.btnReturnClicked) self.txtNum.textChanged.connect(self.textChange) self.chkSave.toggled.connect(self.SaveVal) self.lbl.setText('Введите число') self.lbl.move(60, 30) self.lblCheck.setGeometry(60, 100, 100, 100) self.setGeometry(300, 300, 250, 220) self.setWindowTitle('MyApp') self.txtNum.setText("0") self.btnAdd.toggle() self.lblCheck.setText(str(self.s)) self.show() def textChange(self): if self.txtNum.text().isnumeric() == False: self.txtNum.setText("") def SaveVal(self): if self.chkSave.isChecked(): self.SaveChk = self.s self.chkSave.setDisabled(True) self.s = 0 self.txtNum.setText("0") self.lblCheck.setText(str(self.s)) def btnOkClicked(self): OutDate = int(self.txtNum.text()) if self.SavBool: OutDate = self.SaveChk self.txtNum.setEnabled(True) self.btnDiv.setEnabled(True) self.btnCon.setEnabled(True) self.SaveChk = 0 self.SavBool = False if self.chkMin.isChecked(): OutDate = -OutDate if self.btnAdd.isChecked(): self.s = self.s + OutDate elif self.btnCon.isChecked(): self.s = self.s * OutDate elif self.btnDiv.isChecked(): self.s = self.s // OutDate self.lblCheck.setText(str(self.s)) def btnReturnClicked(self): self.chkSave.setChecked(False) self.chkSave.setEnabled(True) self.SavBool = True self.btnAdd.toggle() self.txtNum.setDisabled(True) self.btnDiv.setDisabled(True) self.btnCon.setDisabled(True) def btnEndClicked(self): msg = QMessageBox() msg.setIcon(QMessageBox.Information) if self.s <= -32768 or self.s >= 32767: msg = QMessageBox.question(self, 'Переполнение', "Вы вышли за пределы 16й ОДЗ!", QMessageBox.Ok) else: msg1 = QMessageBox.question( self, 'Все в порядке', "Ваш результат формулы подходит для 16й ОДЗ!", QMessageBox.Ok) self.s = 0 self.lblCheck.setText(str(self.s))
def __init__(self, parent): super().__init__() self.layout = QGridLayout(self) self.settings = parent.settings self.listener = parent.listener self.buttons = {} general = QGroupBox(self) general_layout = QGridLayout(general) general.setTitle('General') self.layout.addWidget(general, 0, 0) ################################### label = QLabel(general) label.setText('Spam Right Click') general_layout.addWidget(label, 0, 0) button = QPushButton(general) self.buttons['right_click'] = button button.setText(nicer_text(self.settings.hotkeys['right_click'])) button.clicked.connect(lambda: self.set_hotkey('right_click')) general_layout.addWidget(button, 0, 1) label = QLabel(general) label.setText('Spam Left Click') general_layout.addWidget(label, 1, 0) button = QPushButton(general) self.buttons['left_click'] = button button.setText(nicer_text(self.settings.hotkeys['left_click'])) button.clicked.connect(lambda: self.set_hotkey('left_click')) general_layout.addWidget(button, 1, 1) label = QLabel(general) label.setText('Normalize Difficulty') general_layout.addWidget(label, 2, 0) button = QPushButton(general) self.buttons['lower_difficulty'] = button button.setText(nicer_text(self.settings.hotkeys['lower_difficulty'])) button.clicked.connect(lambda: self.set_hotkey('lower_difficulty')) general_layout.addWidget(button, 2, 1) label = QLabel(general) label.setText('Swap Armor') general_layout.addWidget(label, 3, 0) button = QPushButton(general) self.buttons['swap_armor'] = button button.setText(nicer_text(self.settings.hotkeys['swap_armor'])) button.clicked.connect(lambda: self.set_hotkey('swap_armor')) general_layout.addWidget(button, 3, 1) radio = QRadioButton(general) radio.setText('Cains') radio.clicked.connect(lambda: self.radio_clicked('cains')) radio.setChecked(self.settings.special['armor_swap_amount'] == 3) general_layout.addWidget(radio, 4, 0) radio = QRadioButton(general) radio.setText('Bounty DH') radio.setDisabled(True) radio.clicked.connect(lambda: self.radio_clicked('bounty_dh')) radio.setChecked(self.settings.special['armor_swap_amount'] == 2) general_layout.addWidget(radio, 4, 1) label = QLabel(general) label.setText('Pause Eule') general_layout.addWidget(label, 5, 0) button = QPushButton(general) self.buttons['pause'] = button button.setText(nicer_text(self.settings.hotkeys['pause'])) button.clicked.connect(lambda: self.set_hotkey('pause')) general_layout.addWidget(button, 5, 1) porting = QGroupBox(self) porting_layout = QGridLayout(porting) porting.setTitle('Porting') self.layout.addWidget(porting, 1, 0) ###################### label = QLabel(porting) label.setText('Port to A1 Town') porting_layout.addWidget(label, 0, 0) button = QPushButton(porting) self.buttons['port_a1'] = button button.setText(nicer_text(self.settings.hotkeys['port_a1'])) button.clicked.connect(lambda: self.set_hotkey('port_a1')) porting_layout.addWidget(button, 0, 1) label = QLabel(porting) label.setText('Port to A2 Town') porting_layout.addWidget(label, 1, 0) button = QPushButton(porting) self.buttons['port_a2'] = button button.setText(nicer_text(self.settings.hotkeys['port_a2'])) button.clicked.connect(lambda: self.set_hotkey('port_a2')) porting_layout.addWidget(button, 1, 1) label = QLabel(porting) label.setText('Port to A3 Town') porting_layout.addWidget(label, 2, 0) button = QPushButton(porting) self.buttons['port_a3'] = button button.setText(nicer_text(self.settings.hotkeys['port_a3'])) button.clicked.connect(lambda: self.set_hotkey('port_a3')) porting_layout.addWidget(button, 2, 1) label = QLabel(porting) label.setText('Port to A4 Town') porting_layout.addWidget(label, 3, 0) button = QPushButton(porting) self.buttons['port_a4'] = button button.setText(nicer_text(self.settings.hotkeys['port_a4'])) button.clicked.connect(lambda: self.set_hotkey('port_a4')) porting_layout.addWidget(button, 3, 1) label = QLabel(porting) label.setText('Port to A5 Town') porting_layout.addWidget(label, 4, 0) button = QPushButton(porting) self.buttons['port_a5'] = button button.setText(nicer_text(self.settings.hotkeys['port_a5'])) button.clicked.connect(lambda: self.set_hotkey('port_a5')) porting_layout.addWidget(button, 4, 1) label = QLabel(porting) label.setText('Port to Pool') porting_layout.addWidget(label, 5, 0) button = QPushButton(porting) self.buttons['port_pool'] = button button.setText(nicer_text(self.settings.hotkeys['port_pool'])) button.clicked.connect(lambda: self.set_hotkey('port_pool')) porting_layout.addWidget(button, 5, 1) greater_rift = QGroupBox(self) greater_rift_layout = QGridLayout(greater_rift) greater_rift.setTitle('Greater Rift') self.layout.addWidget(greater_rift, 0, 1) #################### label = QLabel(greater_rift) label.setText('Open Grift') greater_rift_layout.addWidget(label, 0, 0) button = QPushButton(greater_rift) self.buttons['open_gr'] = button button.setText(nicer_text(self.settings.hotkeys['open_gr'])) button.clicked.connect(lambda: self.set_hotkey('open_gr')) greater_rift_layout.addWidget(button, 0, 1) label = QLabel(greater_rift) label.setText('Upgrade Gem') greater_rift_layout.addWidget(label, 1, 0) button = QPushButton(greater_rift) self.buttons['upgrade_gem'] = button button.setText(nicer_text(self.settings.hotkeys['upgrade_gem'])) button.clicked.connect(lambda: self.set_hotkey('upgrade_gem')) greater_rift_layout.addWidget(button, 1, 1) checkbox = QCheckBox(greater_rift) checkbox.setText('Empowered') checkbox.stateChanged.connect( lambda: self.checkbox_clicked('empowered')) checkbox.setChecked(self.settings.special['empowered']) greater_rift_layout.addWidget(checkbox, 2, 0) checkbox = QCheckBox(greater_rift) checkbox.setText('Choose Gem to upgrade') checkbox.setToolTip( 'If checked, will upgrade the gem currently selected.') checkbox.stateChanged.connect( lambda: self.checkbox_clicked('choose_gem')) checkbox.setChecked(self.settings.special['choose_gem']) greater_rift_layout.addWidget(checkbox, 2, 1) label = QLabel(greater_rift) label.setText('Leave Game') greater_rift_layout.addWidget(label, 3, 0) button = QPushButton(greater_rift) self.buttons['leave_game'] = button button.setText(nicer_text(self.settings.hotkeys['leave_game'])) button.clicked.connect(lambda: self.set_hotkey('leave_game')) greater_rift_layout.addWidget(button, 3, 1) after_rift = QGroupBox(self) after_rift_layout = QGridLayout(after_rift) after_rift.setTitle('After Rift') self.layout.addWidget(after_rift, 1, 1) ###################### label = QLabel(after_rift) label.setText('Salvage') after_rift_layout.addWidget(label, 0, 0) button = QPushButton(after_rift) self.buttons['salvage'] = button button.setText(nicer_text(self.settings.hotkeys['salvage'])) button.clicked.connect(lambda: self.set_hotkey('salvage')) after_rift_layout.addWidget(button, 0, 1) label = QLabel(after_rift) label.setText('Drop Inventory') after_rift_layout.addWidget(label, 1, 0) button = QPushButton(after_rift) self.buttons['drop_inventory'] = button button.setText(nicer_text(self.settings.hotkeys['drop_inventory'])) button.clicked.connect(lambda: self.set_hotkey('drop_inventory')) after_rift_layout.addWidget(button, 1, 1) label = QLabel(after_rift) label.setText('Spare Columns') after_rift_layout.addWidget(label, 2, 0) spinbox = QSpinBox(after_rift) spinbox.setMinimum(0) spinbox.setMaximum(10) spinbox.setValue(self.settings.special['spare_columns']) spinbox.valueChanged.connect(self.spinbox_changed) after_rift_layout.addWidget(spinbox, 2, 1) label = QLabel(after_rift) label.setText('Gamble') after_rift_layout.addWidget(label, 3, 0) button = QPushButton(after_rift) self.buttons['gamble'] = button button.setText(nicer_text(self.settings.hotkeys['gamble'])) button.clicked.connect(lambda: self.set_hotkey('gamble')) after_rift_layout.addWidget(button, 3, 1) cube_converter = QGroupBox(self) cube_converter_layout = QGridLayout(cube_converter) cube_converter.setTitle('Cube Converter') self.layout.addWidget(cube_converter, 2, 1) ###################### label = QLabel(cube_converter) label.setText('Convert 1-Slot') cube_converter_layout.addWidget(label, 0, 0, 1, 3) button = QPushButton(cube_converter) self.buttons['cube_conv_sm'] = button button.setText(nicer_text(self.settings.hotkeys['cube_conv_sm'])) button.clicked.connect(lambda: self.set_hotkey('cube_conv_sm')) cube_converter_layout.addWidget(button, 0, 3, 1, 3) label = QLabel(cube_converter) label.setText('Convert 2-Slot') cube_converter_layout.addWidget(label, 1, 0, 1, 3) button = QPushButton(cube_converter) self.buttons['cube_conv_lg'] = button button.setText(nicer_text(self.settings.hotkeys['cube_conv_lg'])) button.clicked.connect(lambda: self.set_hotkey('cube_conv_lg')) cube_converter_layout.addWidget(button, 1, 3, 1, 3) radio = QRadioButton(cube_converter) radio.setText('SoL') radio.setChecked(self.settings.special['cube_conv_speed'] == 'sol') radio.clicked.connect(lambda: self.radio_clicked('sol')) cube_converter_layout.addWidget(radio, 2, 0, 1, 2) radio = QRadioButton(cube_converter) radio.setText('Normal') radio.setChecked(self.settings.special['cube_conv_speed'] == 'normal') radio.clicked.connect(lambda: self.radio_clicked('normal')) cube_converter_layout.addWidget(radio, 2, 2, 1, 2) radio = QRadioButton(cube_converter) radio.setText('Slow') radio.setChecked(self.settings.special['cube_conv_speed'] == 'slow') radio.clicked.connect(lambda: self.radio_clicked('slow')) cube_converter_layout.addWidget(radio, 2, 4, 1, 2) label = QLabel(cube_converter) label.setText('Reforge / Convert Set') cube_converter_layout.addWidget(label, 3, 0, 1, 3) button = QPushButton(cube_converter) self.buttons['reforge'] = button button.setText(nicer_text(self.settings.hotkeys['reforge'])) button.clicked.connect(lambda: self.set_hotkey('reforge')) cube_converter_layout.addWidget(button, 3, 3, 1, 3) skill_macro = QGroupBox(self) skill_macro_layout = QGridLayout(skill_macro) skill_macro.setTitle('Skill Macro') self.layout.addWidget(skill_macro, 2, 0, -1, 1) label = QLabel(skill_macro) label.setText('Activate / Deactivate') skill_macro_layout.addWidget(label, 0, 0) button = QPushButton(self) self.buttons['skill_macro'] = button button.setText(nicer_text(self.settings.hotkeys['skill_macro'])) button.clicked.connect(lambda: self.set_hotkey('skill_macro')) skill_macro_layout.addWidget(button, 0, 1) self.setLayout(self.layout)
def __init__(self, object_tab, *args): super().__init__(*args) self.object_tab = object_tab # data series selection data_series_group = QGroupBox('Data Series', self) data_series_group.setAlignment(Qt.AlignCenter) data_series_group.setMaximumWidth(550) data_series_group.setMinimumWidth(300) original_check = QCheckBox('Original', data_series_group) original_check.setChecked(True) decontaminated_check = QCheckBox('Decontaminated', data_series_group) decontaminated_check.setChecked(True) contamination_check = QCheckBox('Contamination', data_series_group) contamination_check.setChecked(True) model_check = QCheckBox('Model', data_series_group) data_series_group.setLayout(QGridLayout()) data_series_group.layout().addWidget(original_check, 0, 0) data_series_group.layout().addWidget(decontaminated_check, 0, 1) data_series_group.layout().addWidget(contamination_check, 1, 0) data_series_group.layout().addWidget(model_check, 1, 1) self._original = original_check self._decon = decontaminated_check self._contam = contamination_check self._model = model_check # y-axis type selection y_axis_type = QGroupBox('y-axis type', self) y_axis_type.setAlignment(Qt.AlignCenter) y_axis_type.setMaximumWidth(300) y_axis_type.setMinimumWidth(200) data_number_radio = QRadioButton('Image Units', y_axis_type) calibrated_flux_radio = QRadioButton('Calibrated Flux', y_axis_type) if self.object_tab.inspector.sensitivities[self.object_tab.dither] is None: calibrated_flux_radio.setDisabled(True) data_number_radio.setChecked(True) else: calibrated_flux_radio.setChecked(True) y_axis_type.setLayout(QVBoxLayout()) y_axis_type.layout().addWidget(data_number_radio) y_axis_type.layout().addWidget(calibrated_flux_radio) self._data_number = data_number_radio self._flux = calibrated_flux_radio # x-axis type selection x_axis_type = QGroupBox('x-axis type', self) x_axis_type.setAlignment(Qt.AlignCenter) x_axis_type.setMaximumWidth(300) x_axis_type.setMinimumWidth(200) wavelength_radio = QRadioButton('Wavelength', x_axis_type) wavelength_radio.setChecked(True) pixel_number_radio = QRadioButton('Pixel number', x_axis_type) x_axis_type.setLayout(QVBoxLayout()) x_axis_type.layout().addWidget(pixel_number_radio) x_axis_type.layout().addWidget(wavelength_radio) self._wavelength = wavelength_radio self._pixel_num = pixel_number_radio # buttons detector_button = QPushButton('Show Detectors', self) detector_button.setMaximumWidth(128) detector_button.pressed.connect(self.object_tab.open_detectors) detector_button.setDisabled(True) plot_button = QPushButton('Make Plot(s)', self) plot_button.setMaximumWidth(128) plot_button.setMinimumWidth(100) plot_button.pressed.connect(self.object_tab.make_plots) plot_button.setDisabled(True) self.detector_button = detector_button self.plot_button = plot_button buttons = QVBoxLayout() buttons.addSpacing(23) buttons.addWidget(detector_button) buttons.addWidget(plot_button) layout = QGridLayout() layout.setSpacing(15) layout.setContentsMargins(10, 0, 10, 10) layout.addWidget(data_series_group, 0, 0) layout.addWidget(y_axis_type, 0, 1) layout.addWidget(x_axis_type, 0, 2) layout.addLayout(buttons, 0, 3) self.setContentsMargins(8, 0, 8, 8) self.setLayout(layout)
class ScriptsMenu(QWidget): def interface_check(function): def wrapper(self): function(self) try: self.on_block() except: return wrapper return wrapper def __init__(self): super().__init__() self.layout = QGridLayout() self.setLayout(self.layout) row_hight = 30 margins = self.layout.contentsMargins() margins.setTop(row_hight) margins.setRight(20) self.layout.setContentsMargins(margins) # Initializing GUI elements self.settings_label = QLabel('Settings') self.platform_var_list = QComboBox() self.thread_var_list = QComboBox() self.intel64 = QCheckBox('Intel 64') self.IA32 = QCheckBox('IA32') self.TL = QCheckBox('Threading layer') self.omp = QRadioButton('OpenMP') self.tbb = QRadioButton('TBB') self.lib_name = QLineEdit() self.functions_list = QListWidget() self.save_build_script = QPushButton('Save build script') self.functions_names = [] self.status_receiver = None self.lib_name.setPlaceholderText('Library name...') # Preparing elements by giving initial values and etc self.settings_label.setAlignment(Qt.AlignBottom) self.save_build_script.setDisabled(True) self.save_build_script.clicked.connect(self.on_save_build_script) self.IA32.clicked.connect(self.on_block) self.intel64.clicked.connect(self.on_block) self.TL.clicked.connect(self.set_tl) self.lib_name.textEdited.connect(self.on_block) self.platform_var_list.currentIndexChanged.connect(self.on_target_system_selection) # Setting all widgets in their places self.layout.addWidget(self.settings_label, 0, 0) self.layout.addWidget(self.TL, 1, 0) self.layout.addWidget(self.omp, 2, 0) self.layout.addWidget(self.tbb, 3, 0) self.layout.addWidget(self.intel64, 2, 1) self.layout.addWidget(self.IA32, 3, 1) self.layout.addWidget(self.platform_var_list, 2, 2, 1, 2) self.layout.addWidget(self.thread_var_list, 3, 2, 1, 2) self.layout.addWidget(self.lib_name, 4, 0, 1, 4) self.layout.addWidget(self.functions_list, 5, 0, 1, 4) self.layout.addWidget(self.save_build_script, 6, 0, 1, 4) self.settings_label.setFixedHeight(row_hight) self.TL.setFixedHeight(row_hight) self.platform_var_list.setFixedHeight(row_hight) self.thread_var_list.setFixedHeight(row_hight) self.__post_check() def set_configs(self, package): self.check_configs(package) self.TL.setChecked(settings.CONFIGS[package]['TL']) self.omp.setChecked(settings.CONFIGS[package]['OpenMP']) self.tbb.setChecked(settings.CONFIGS[package]['TBB']) self.set_tl() self.intel64.setChecked(settings.CONFIGS[package]['intel64']) self.IA32.setChecked(settings.CONFIGS[package]['IA32']) if self.intel64.isEnabled(): if not self.intel64.isChecked() and not self.IA32.isChecked(): self.intel64.setChecked(True) elif self.IA32.isEnabled(): self.IA32.setChecked(True) self.thread_var_list.setCurrentText(utils.MULTI_THREADED) if settings.CONFIGS[package]['Multi-threaded'] \ else self.thread_var_list.setCurrentText(utils.SINGLE_THREADED) self.functions_names = settings.CONFIGS[package]['functions_list'] def check_configs(self, package): self.intel64_libs_path = self.parent.source.path_to_libs[package][utils.INTEL64] self.ia32_libs_path = self.parent.source.path_to_libs[package][utils.IA32] if self.intel64_libs_path: self.intel64.setEnabled(True) else: settings.CONFIGS[package]['intel64'] = False self.intel64.setDisabled(True) if self.ia32_libs_path: self.IA32.setEnabled(True) else: settings.CONFIGS[package]['IA32'] = False self.IA32.setDisabled(True) if self.check_dir('tl'): self.TL.setEnabled(True) else: settings.CONFIGS[package]['TL'] = False self.TL.setDisabled(True) self.thread_var_list.clear() if self.check_dir('threaded'): self.thread_var_list.addItems([utils.SINGLE_THREADED, utils.MULTI_THREADED]) else: self.thread_var_list.addItem(utils.SINGLE_THREADED) settings.CONFIGS[package]['Multi-threaded'] = False def check_dir(self, dir): return os.path.exists(os.path.join(self.intel64_libs_path, dir)) or \ os.path.exists(os.path.join(self.ia32_libs_path, dir)) def get_configs(self, package): if self.TL.isEnabled(): settings.CONFIGS[package]['TL'] = self.TL.isChecked() if settings.CONFIGS[package]['TL']: settings.CONFIGS[package]['OpenMP'] = self.omp.isChecked() settings.CONFIGS[package]['TBB'] = self.tbb.isChecked() settings.CONFIGS[package]['intel64'] = self.intel64.isChecked() settings.CONFIGS[package]['IA32'] = self.IA32.isChecked() settings.CONFIGS[package]['Multi-threaded'] = (self.thread_var_list.currentText() == utils.MULTI_THREADED) settings.CONFIGS[package]['functions_list'] = self.functions_names def set_status_output(self, status_receiver): self.status_receiver = status_receiver def __get_interface_state(self): return {settings.PACKAGE: self.parent.source.ipp.isEnabled() or self.parent.source.ippcp.isEnabled(), settings.PLATFORM: self.IA32.isChecked() or self.intel64.isChecked(), settings.LIB_NAME: bool(self.lib_name.text()), settings.FUNCTIONS: bool(self.functions_names), settings.ANDK: not ((not bool(utils.ANDROID_NDK_PATH)) and self.platform_var_list.currentText() == utils.ANDROID) } def on_item_selected(self, item): self.functions_list.setCurrentItem(item) def on_block(self): autobuild_requrements = settings.AUTOBUILD_BUTTON_RULES script_requrements = settings.SCRIPT_BUTTON_GENERATOR_RULES interface_state = self.__get_interface_state() if autobuild_requrements == interface_state: self.parent.set_auto_build_disabled(False) self.status_receiver.showMessage("Ready to build custom library") else: self.parent.set_auto_build_disabled(True) differences = dict(autobuild_requrements.items() - interface_state.items()) self.status_receiver.showMessage("Set " + sorted(differences, key=len)[0]) if script_requrements == {i: interface_state.get(i) for i in script_requrements.keys()}: self.save_build_script.setDisabled(False) else: self.save_build_script.setDisabled(True) def set_tl(self): if self.TL.isEnabled(): self.set_threading_layer_enabled(self.TL.isChecked()) self.parent.source.tl_selected = self.TL.isChecked() else: self.set_threading_layer_enabled(False) self.parent.source.tl_selected = False if self.parent.source.ipp.isChecked(): self.parent.source.show_menu(utils.IPP) if not self.omp.isChecked() and not self.tbb.isChecked(): if self.omp.isEnabled(): self.omp.setChecked(True) elif self.tbb.isEnabled(): self.tbb.setChecked(True) def set_threading_layer_enabled(self, bool): self.omp.setEnabled(bool) if self.check_dir(os.path.join('tl', 'openmp')) else self.omp.setDisabled(True) self.tbb.setEnabled(bool) if self.check_dir(os.path.join('tl', 'tbb')) else self.tbb.setDisabled(True) def on_save_build_script(self): library_path = QFileDialog.getExistingDirectory(self, 'Select a folder') if library_path == '': return host_system = utils.HOST_SYSTEM target_system = self.platform_var_list.currentText() functions = self.functions_names library_name = self.lib_name.text() threading = self.thread_var_list.currentText() == 'Multi-threaded' threading_layer_type = self.parent.get_treading_layer_type() if self.parent.source.ipp.isChecked(): package = utils.IPP root = utils.IPPROOT else: package = utils.IPPCP root = utils.IPPCRYPTOROOT os.environ[root] = settings.CONFIGS[package]['Path'] if self.IA32.isChecked(): generate_script(package, host_system, target_system, functions, library_path, library_name, utils.IA32, threading, threading_layer_type, ) if self.intel64.isChecked(): generate_script(package, host_system, target_system, functions, library_path, library_name, utils.INTEL64, threading, threading_layer_type) QMessageBox.about(self, 'Success', 'Generation completed!') @interface_check def on_target_system_selection(self): system = self.platform_var_list.currentText() if utils.ONLY_THREADABLE[system]: self.thread_var_list.setCurrentIndex(1) self.thread_var_list.setDisabled(True) else: self.thread_var_list.setDisabled(False) if not utils.SUPPORTED_ARCHITECTURES[system][utils.IA32]: self.IA32.setCheckState(Qt.Unchecked) self.IA32.setDisabled(True) else: self.IA32.setDisabled(False) if not utils.SUPPORTED_ARCHITECTURES[system][utils.INTEL64]: self.intel64.setCheckState(Qt.Unchecked) self.intel64.setDisabled(True) else: self.intel64.setDisabled(False) def add_items(self, items): """ Sorts and adds items to list view :param items: list of strings """ self.functions_list.clear() if items: items.sort() self.functions_list.addItems(items) self.functions_list.setCurrentItem(self.functions_list.item(0)) self.functions_list.repaint() def add_item(self, function): """ Adds new function to required list :param domain: domain of function :param function: name if function """ self.functions_names.append(function) self.add_items(self.functions_names) def remove_item(self): """ Removes function from required list """ if self.functions_list.currentItem() is None: return None lib = self.functions_list.currentItem().text() self.functions_names.remove(lib) self.add_items(self.functions_names) return lib def __post_check(self): """ Fills platforms combo box according to host system """ if utils.HOST_SYSTEM == utils.LINUX: self.platform_var_list.addItem(utils.LINUX) elif utils.HOST_SYSTEM == utils.MACOSX: self.platform_var_list.addItem(utils.MACOSX) elif utils.HOST_SYSTEM == utils.WINDOWS: self.platform_var_list.addItem(utils.WINDOWS)
class LoadSumWindow(QMainWindow): def __init__(self, parent=None): super(LoadSumWindow, self).__init__(parent) self.mywidget = QWidget(self) self.setMinimumSize(700, 600) # self.resize(800, 500) self.setWindowTitle('Load Summary Table') self.setWindowIcon(QIcon("./Icon/sheet.ico")) # root = QFileInfo(__file__).absolutePath() # self.setWindowIcon(QIcon(root + "./icon/Text_Edit.ico")) self.xls_temp = None #excel template self.out_path = None #load summary table self.xls_name = None #the name of a new load summary table self.xls_path = None #the path for the new load summary table self.ultimate = False self.fatigue = False self.heat_map = False self.fat_wind = False self.fat_case = False self.aep_dlc = False self.plot_ldd = False self.plot_lrd = False self.pitch_bl = False self.main_bl = False self.gearbox = False self.nacelle = False self.main_all = True self.ult_list = list() self.fat_list = list() self.lct_list = list() self.dlc_list = list() self.loopname = list() self.ldd_list = list() self.lrd_list = list() self.nac_list = list() self.pst_list = list() self.pbl_list = list() # pitch bearing life self.get_list = list() # gearbox equivalent torque self.mbl_list = list() # main bearing life self.title_font = QFont("Calibri", 10) self.title_font.setItalic(True) self.title_font.setBold(True) self.cont_font = QFont("Calibri", 9) self.cont_font.setItalic(False) self.cont_font.setBold(False) self.initUI() self.load_setting() self.center() # self.display() def initUI(self): menubar = self.menuBar() fileMenu = menubar.addMenu('File') helpMenu = menubar.addMenu('Help') excelAction = QAction(QIcon('Icon/Excel.ico'), 'Template', self) excelAction.triggered.connect(self.generate_template) fileMenu.addAction(excelAction) saveAction = QAction(QIcon('Icon/save.ico'), 'Save', self) saveAction.setShortcut('Ctrl+S') saveAction.triggered.connect(self.save_setting) fileMenu.addAction(saveAction) clearAction = QAction(QIcon('Icon/clear.ico'), 'Clear', self) clearAction.setShortcut('Ctrl+R') clearAction.triggered.connect(self.clear_setting) fileMenu.addAction(clearAction) exitAction = QAction(QIcon('Icon/exit.ico'), 'Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.triggered.connect(qApp.quit) fileMenu.addAction(exitAction) helpAction = QAction(QIcon('Icon/doc.ico'), 'User Manual', self) helpAction.triggered.connect(self.user_manual) helpMenu.addAction(helpAction) self.main_layout = QVBoxLayout() # 创建主部件的网格布局 # ******************************* input groupbox ********************************** self.gbox1 = QGroupBox('Input') self.gbox1.setFont(self.title_font) self.lab1 = QLabel('Excel Template') self.lab1.setFont(self.cont_font) self.lin1 = MyQLineEdit() self.lin1.setFont(self.cont_font) self.lin1.setPlaceholderText('Choose the excel template') self.btn1 = QPushButton("...") self.btn1.clicked.connect(self.load_template) # set layout self.glayout1 = QGridLayout() self.glayout1.addWidget(self.lab1, 0, 0, 1, 1) self.glayout1.addWidget(self.lin1, 0, 1, 1, 3) self.glayout1.addWidget(self.btn1, 0, 4, 1, 1) self.gbox1.setLayout(self.glayout1) # ******************************* output groupbox ********************************** self.gbox5 = QGroupBox('Output') self.gbox5.setFont(self.title_font) # sub1 self.gbox5_sub1 = QGroupBox() # two options self.radio_main = QRadioButton('Main result') self.radio_main.setFont(self.cont_font) self.radio_main.setChecked(True) self.radio_main.toggled.connect(self.main_option) self.radio_all = QRadioButton('All result') self.radio_all.setFont(self.cont_font) self.radio_all.toggled.connect(self.all_option) if self.radio_all.isChecked(): self.main_all = False self.lay_sub1 = QGridLayout() self.lay_sub1.addWidget(self.radio_main, 0, 0, 1, 2) self.lay_sub1.addWidget(self.radio_all, 0, 3, 1, 3) self.gbox5_sub1.setLayout(self.lay_sub1) # sub2 self.gbox5_sub2 = QGroupBox() # two options self.radio_new = QRadioButton('New table') self.radio_new.setFont(self.cont_font) self.radio_new.setChecked(True) self.radio_new.toggled.connect(self.new_option) self.radio_app = QRadioButton('Append') self.radio_app.setFont(self.cont_font) self.radio_app.setChecked(False) # self.radio_app.setDisabled(True) self.radio_app.toggled.connect(self.append_option) self.lab2 = QLabel('Excel Directory') self.lab2.setFont(self.cont_font) self.lin2 = MyQLineEdit() self.lin2.setFont(self.cont_font) self.lin2.setPlaceholderText('Choose the path to save result') self.btn2 = QPushButton("...") self.btn2.clicked.connect(self.load_output) self.lab3 = QLabel('Excel Name') self.lab3.setFont(self.cont_font) self.lin3 = QLineEdit() self.lin3.setFont(self.cont_font) self.lin3.setPlaceholderText('Enter the name of the excel') self.lab4 = QLabel('Excel Path') self.lab4.setFont(self.cont_font) self.lin4 = QLineEdit() self.lin4.setFont(self.cont_font) self.lin4.setPlaceholderText('Choose excel to append result') self.btn3 = QPushButton("...") self.btn3.clicked.connect(self.choose_excel) self.lin4.setDisabled(True) self.btn3.setDisabled(True) # set layout # self.lay_sub1 = QGridLayout() # self.lay_sub1.addWidget(self.radio_new, 0, 0, 1, 1) # self.lay_sub1.addWidget(self.radio_app, 0, 2, 1, 1) self.lay_sub2 = QGridLayout() self.lay_sub2.addWidget(self.radio_new, 0, 0, 1, 1) self.lay_sub2.addWidget(self.radio_app, 0, 2, 1, 1) self.lay_sub2.addWidget(self.lab2, 1, 0, 1, 1) self.lay_sub2.addWidget(self.lin2, 1, 1, 1, 3) self.lay_sub2.addWidget(self.btn2, 1, 4, 1, 1) self.lay_sub2.addWidget(self.lab3, 2, 0, 1, 1) self.lay_sub2.addWidget(self.lin3, 2, 1, 1, 3) self.lay_sub2.addWidget(self.lab4, 3, 0, 1, 1) self.lay_sub2.addWidget(self.lin4, 3, 1, 1, 3) self.lay_sub2.addWidget(self.btn3, 3, 4, 1, 1) # self.gbox5_sub1.setLayout(self.lay_sub1) # self.gbox5_sub2.setLayout(self.lay_sub2) self.glayout5 = QVBoxLayout() # self.glayout5.addWidget(self.gbox5_sub1) # self.glayout5.addWidget(self.gbox5_sub2) # self.glayout5.addStretch(1) # self.gbox5.setLayout(self.glayout5) self.gbox5.setLayout(self.lay_sub2) # ******************************* main function groupbox ********************************** self.gbox2 = QGroupBox('Ultimate Function') self.gbox2.setFont(self.title_font) self.cb_ultimate = QCheckBox("Ulitmate") self.cb_ultimate.setFont(self.cont_font) # self.cb_ultimate.setChecked(True) self.cb_fatigue = QCheckBox('Fatigue') self.cb_fatigue.setFont(self.cont_font) # self.cb_fatigue.setChecked(True) self.cb_heatmap = QCheckBox('Heat Map') self.cb_heatmap.setFont(self.cont_font) # self.cb_aepdlc12.font(QFont('微软雅黑', 9)) # self.checkbox4 = QCheckBox('AEP') self.checkbox8 = QLabel() self.checkbox9 = QLabel() self.checkbox10 = QLabel() # self.checkbox8.setDisabled(True) self.glayout2 = QGridLayout() self.glayout2.addWidget(self.cb_ultimate, 0, 0, 1, 1) # self.glayout2.addWidget(self.cb_fatigue, 1, 0, 1, 1) self.glayout2.addWidget(self.cb_heatmap, 1, 0, 1, 1) # self.glayout2.addWidget(self.checkbox4, 3, 0, 1, 1) self.glayout2.addWidget(self.checkbox8, 2, 0, 1, 1) # self.glayout2.addWidget(self.checkbox9, 3, 0, 1, 1) self.gbox2.setLayout(self.glayout2) # ******************************* fatigue function groupbox ********************************** self.gbox3 = QGroupBox('Fatigue Function') self.gbox3.setFont(self.title_font) self.cb_fatwind = QCheckBox('Fatigue per wind') self.cb_fatwind.setFont(self.cont_font) self.cb_fatdlc = QCheckBox('Fatigue per DLC') self.cb_fatdlc.setFont(self.cont_font) self.cb_fatwave = QCheckBox('Fatigue per wave') self.cb_fatwave.setFont(self.cont_font) self.cb_fatwave.setDisabled(True) self.glayout3 = QGridLayout() self.glayout3.addWidget(self.cb_fatigue, 0, 0, 1, 1) self.glayout3.addWidget(self.cb_fatwind, 1, 0, 1, 1) self.glayout3.addWidget(self.cb_fatdlc, 2, 0, 1, 1) # self.glayout3.addWidget(self.cb_fatwave, 2, 0, 1, 1) # self.glayout3.addWidget(self.checkbox10, 3, 0, 1, 1) self.gbox3.setLayout(self.glayout3) # ******************************* other function groupbox ********************************** self.gbox4 = QGroupBox(' Other function') self.gbox4.setFont(self.title_font) self.cb_aepdlc12 = QCheckBox('Annual Energy Production') self.cb_aepdlc12.setFont(self.cont_font) # self.cb_towercl = QCheckBox('Tower Clearance') # self.cb_towercl.setFont(self.cont_font) # self.cb_towercl.setDisabled(True) self.cb_alarmid = QCheckBox('Alarm ID') self.cb_alarmid.setFont(self.cont_font) self.cb_alarmid.setDisabled(True) self.cb_plotlrd = QCheckBox('Plot Pitch Travel') self.cb_plotlrd.setFont(self.cont_font) # self.cb_plotlrd.setDisabled(True) self.cb_nacacce = QCheckBox('Nacelle Fore-Aft/Side-Side Acc') self.cb_nacacce.setFont(self.cont_font) self.cb_nacacce.setDisabled(False) self.cb_gearequ = QCheckBox('Gearbox Equivalent Torque') self.cb_gearequ.setFont(self.cont_font) self.cb_gearequ.setDisabled(False) self.cb_mainber = QCheckBox('Main Bearing Life(single bearing)') self.cb_mainber.setFont(self.cont_font) self.cb_mainber.setDisabled(False) self.cb_pitbear = QCheckBox('Pitch Bearing Life/Equivalent Torque') self.cb_pitbear.setFont(self.cont_font) self.cb_pitbear.setDisabled(False) self.cb_plotldd = QCheckBox('Plot MxHR LDD') self.cb_plotldd.setFont(self.cont_font) # self.cb_plotldd.setDisabled(True) self.cb_dynpowc = QCheckBox('Dynamic Power Curve') self.cb_dynpowc.setFont(self.cont_font) self.cb_dynpowc.setDisabled(False) self.glayout4 = QGridLayout() # self.glayout4.addWidget(self.cb_alarmid, 0, 0, 1, 1) self.glayout4.addWidget(self.cb_plotldd, 0, 0, 1, 1) self.glayout4.addWidget(self.cb_plotlrd, 1, 0, 1, 1) self.glayout4.addWidget(self.cb_dynpowc, 2, 0, 1, 1) self.glayout4.addWidget(self.cb_aepdlc12, 3, 0, 1, 1) # self.glayout4.addWidget(self.cb_towercl, 0, 1, 1, 1) self.glayout4.addWidget(self.cb_nacacce, 0, 1, 1, 1) self.glayout4.addWidget(self.cb_pitbear, 1, 1, 1, 1) self.glayout4.addWidget(self.cb_gearequ, 2, 1, 1, 1) self.glayout4.addWidget(self.cb_mainber, 3, 1, 1, 1) self.gbox4.setLayout(self.glayout4) # set main layout # check button self.btn_check = QPushButton('Check Input') self.btn_check.setFont(self.cont_font) self.btn_check.clicked.connect(self.check_input) # handle button self.btn_handle = QPushButton('Handle Data') self.btn_handle.setFont(self.cont_font) self.btn_handle.setDisabled(True) self.btn_handle.clicked.connect(self.handle) # reset button self.btn_reset = QPushButton('Reset Selection') self.btn_reset.setFont(self.cont_font) self.btn_reset.setDisabled(True) self.btn_reset.clicked.connect(self.reset) self.Hlayout = QHBoxLayout() self.Hlayout.addWidget(self.gbox2) self.Hlayout.addWidget(self.gbox3) self.main_layout.addWidget(self.gbox1) self.main_layout.addWidget(self.gbox5) self.main_layout.addLayout(self.Hlayout) self.main_layout.addWidget(self.gbox4) self.main_layout.addWidget(self.btn_check) self.main_layout.addWidget(self.btn_handle) self.main_layout.addWidget(self.btn_reset) self.main_layout.addStretch(0) self.mywidget.setLayout(self.main_layout) self.setCentralWidget(self.mywidget) def save_setting(self): config = configparser.ConfigParser() config.read('config.ini', encoding='utf-8') if not config.has_section('Load Summary'): config.add_section('Load Summary') config['Load Summary'] = { 'Excel template': self.lin1.text(), 'Excel directory': self.lin2.text(), 'Excel name': self.lin3.text(), 'Excel path': self.lin4.text() } with open("config.ini", 'w') as f: config.write(f) def clear_setting(self): self.lin1.setText('') self.lin2.setText('') self.lin3.setText('') self.lin4.setText('') def load_setting(self): config = configparser.ConfigParser() config.read('config.ini', encoding='utf-8') if config.has_section('Load Summary'): self.lin1.setText(config.get('Load Summary', 'Excel template')) self.lin2.setText(config.get('Load Summary', 'Excel directory')) # self.lin2.home(True) self.lin3.setText(config.get('Load Summary', 'Excel name')) # self.lin3.home(True) self.lin4.setText(config.get('Load Summary', 'Excel path')) # self.lin4.home(True) def generate_template(self): template = 'Load Summary Template.xlsx' path = os.path.abspath('.') file_path = os.path.join(path, template) print(file_path) border = Border(left=Side(border_style='thin', color='000000'), right=Side(border_style='thin', color='000000'), top=Side(border_style='thin', color='000000'), bottom=Side(border_style='thin', color='000000')) if not os.path.isfile(file_path): table = Workbook() sheet = table['Sheet'] sheet.title = 'Main' sheet['A1'] = 'Wind Turbine Name' sheet['B1'] = 'Category' sheet['C1'] = 'Path' # font for the first row sheet['A1'].font = Font(name='Microsoft Ya Hei', size=9, bold=True) sheet['B1'].font = Font(name='Microsoft Ya Hei', size=9, bold=True) sheet['C1'].font = Font(name='Microsoft Ya Hei', size=9, bold=True) # width for each column sheet.column_dimensions['A'].width = 20 sheet.column_dimensions['B'].width = 10 sheet.column_dimensions['C'].width = 70 for col in sheet.iter_rows(min_row=1, max_col=3, max_row=1): for cell in col: cell.alignment = Alignment(vertical='center', horizontal='center') for row in sheet.iter_rows(min_row=2, max_col=3, max_row=31): for cell in row: cell.font = Font(name='Microsoft Ya Hei', size=9) # for row in sheet.iter_rows(min_row=2, max_col=1, max_row=31): for cell in row: cell.alignment = Alignment(vertical='center', horizontal='center') # set data validation for column B dv = DataValidation(type='list', formula1='"Ultimate,Rainflow,Post,LCT,DLC12"') dv.prompt = 'Make sure the selection is unique for each loop' dv.promptTitle = 'List Selection' sheet.add_data_validation(dv) dv.add('B2:B301') # apply the validation to a range of cellls # border for i in range(1, 52): for j in range(1, 4): sheet.cell(row=i, column=j).border = border # merge for i in range(10): sheet.merge_cells(start_row=5 * i + 2, start_column=1, end_row=5 * i + 6, end_column=1) table.save('Load Summary Template.xlsx') print('Template generated successfully!') # open template os.startfile(file_path) def user_manual(self): os.startfile(os.getcwd() + '\\' + 'User Manual_Load Summary.docx') def new_option(self): if self.radio_new.isChecked(): # 初始化功能 # self.lin1.setDisabled(False) # self.btn1.setDisabled(False) self.lin2.setDisabled(False) self.btn2.setDisabled(False) self.lin3.setDisabled(False) self.lin4.setDisabled(True) self.btn3.setDisabled(True) # restore the function for new option, if the append option has been choosed before self.radio_main.setDisabled(False) self.radio_all.setDisabled(False) self.btn_handle.setDisabled(True) self.lin2.setDisabled(False) self.lin3.setDisabled(False) self.cb_heatmap.setDisabled(False) self.cb_fatigue.setDisabled(False) self.cb_fatwind.setDisabled(False) self.cb_fatdlc.setDisabled(False) self.cb_ultimate.setDisabled(False) self.cb_aepdlc12.setDisabled(False) self.cb_plotldd.setDisabled(False) self.cb_plotlrd.setDisabled(False) self.cb_dynpowc.setDisabled(False) self.cb_nacacce.setDisabled(False) self.cb_pitbear.setDisabled(False) self.cb_gearequ.setDisabled(False) self.cb_mainber.setDisabled(False) def append_option(self): if self.radio_app.isChecked(): # 初始化功能 # self.lin1.setDisabled(False) # self.btn1.setDisabled(False) self.lin2.setDisabled(True) self.btn2.setDisabled(True) self.lin3.setDisabled(True) self.lin4.setDisabled(False) self.btn3.setDisabled(False) # if append option is choosed, then the results will be based on the excel self.radio_main.setDisabled(True) self.radio_all.setDisabled(True) self.btn_handle.setDisabled(True) self.cb_heatmap.setDisabled(True) self.cb_fatigue.setDisabled(False) self.cb_ultimate.setDisabled(False) self.cb_fatdlc.setDisabled(True) self.cb_fatwind.setDisabled(True) self.cb_aepdlc12.setDisabled(True) self.cb_plotldd.setDisabled(True) self.cb_plotlrd.setDisabled(True) self.cb_dynpowc.setDisabled(True) self.cb_nacacce.setDisabled(True) self.cb_pitbear.setDisabled(True) self.cb_gearequ.setDisabled(True) self.cb_mainber.setDisabled(True) def main_option(self): if self.radio_main.isChecked(): self.btn_handle.setDisabled(True) # self.lin2.setDisabled(False) # self.lin3.setDisabled(False) # self.cb_aepdlc12.setDisabled(False) # self.cb_heatmap.setDisabled(False) # self.cb_fatigue.setDisabled(False) # self.cb_fatwind.setDisabled(False) # self.cb_fatdlc.setDisabled(False) # self.cb_ultimate.setDisabled(False) def all_option(self): if self.radio_all.isChecked(): self.btn_handle.setDisabled(True) # self.lin2.setDisabled(False) # self.lin3.setDisabled(False) # self.cb_aepdlc12.setDisabled(False) # self.cb_heatmap.setDisabled(False) # self.cb_fatigue.setDisabled(False) # self.cb_fatwind.setDisabled(False) # self.cb_fatdlc.setDisabled(False) # self.cb_ultimate.setDisabled(False) def keyPressEvent(self, e): if e.key() == QtCore.Qt.Key_Escape: self.close() def load_template(self): excel_return = QFileDialog.getOpenFileName( self, "Choose excel template dialog", r".", "excel(*.xlsx)") if excel_return[0]: self.lin1.setText(excel_return[0].replace('/', '\\')) def load_output(self): excel_dir = QFileDialog.getExistingDirectory( self, "Choose excel result path", r".") if excel_dir: self.lin2.setText(excel_dir.replace('/', '\\')) def choose_excel(self): excel_return = QFileDialog.getOpenFileName( self, "Choose excel template dialog", r".", "excel(*.xlsx)") if excel_return[0]: self.lin4.setText(excel_return[0].replace('/', '\\')) def check_input(self): '''check .$TE to find out if the simulation is finished, or give warning''' print('Begin to check excel template...') if '\\' in self.lin1.text(): self.xls_temp = self.lin1.text().replace('\\', '/') else: self.xls_temp = self.lin1.text() print('Excel template: ', self.xls_temp) if self.radio_new.isChecked(): self.xls_path = self.lin2.text() self.xls_name = self.lin3.text() self.out_path = None if self.radio_app.isChecked(): self.out_path = self.lin4.text() self.xls_path = None self.xls_name = None # 如果不关闭窗口,再次读入excel会重复追加excel中的路径 # 初始化列表 self.loopname.clear() self.ult_list.clear() self.fat_list.clear() self.lct_list.clear() self.dlc_list.clear() self.ldd_list.clear() self.lrd_list.clear() self.pbl_list.clear() self.mbl_list.clear() self.get_list.clear() self.nac_list.clear() # read excel template if self.xls_temp: try: workbook = load_workbook(self.lin1.text()) sheet = workbook.get_sheet_by_name('Main') row_num = sheet.max_row row_max = row_num - (row_num - 1) % 5 # print(row_num)> self.loopname = [ sheet[i][0].value for i in range(2, row_max + 1) if sheet[i][0].value != None ] self.pst_list = [ sheet[i][2].value for i in range(2, row_max + 1) if sheet[i][1].value == 'Post' ] self.dlc_list = [ sheet[i][2].value for i in range(2, row_max + 1) if sheet[i][1].value == 'DLC12' ] self.lct_list = [ sheet[i][2].value for i in range(2, row_max + 1) if sheet[i][1].value == 'LCT' ] self.ult_list = [ sheet[i][2].value for i in range(2, row_max + 1) if sheet[i][1].value == 'Ultimate' ] self.fat_list = [ sheet[i][2].value for i in range(2, row_max + 1) if sheet[i][1].value == 'Rainflow' ] print('LPN :', self.loopname) print('ULT :', self.ult_list) print('FAT :', self.fat_list) print('LCT :', self.lct_list) print('PST :', self.pst_list) print('L12 :', self.dlc_list) loop_num = len(self.loopname) # print(loop_num) if any(self.pst_list): for i in range(loop_num): post_path = self.pst_list[i] if not os.path.isdir(post_path): raise Exception('%s not a valid path!' % post_path) file_list = os.listdir(post_path) for file in file_list: if '07_ultimate' == file.lower(): nac_acc = os.path.join( post_path, r'07_Ultimate\13_Nacelle_Acc') if os.path.isdir(nac_acc): self.nac_list.append(nac_acc) else: self.nac_list.append(None) if '05_ldd' == file.lower(): ldd_path = os.path.join(post_path, file) if os.path.isdir(ldd_path): self.ldd_list.append(ldd_path) else: self.ldd_list.append(None) if '06_lrd' == file.lower(): lrd_path = os.path.join(post_path, file) if os.path.isdir(lrd_path): self.lrd_list.append(lrd_path) else: self.lrd_list.append(None) if '06_lrd' == file.lower(): br_mxy_lrd = os.path.join( post_path, r'06_lrd\br_mxy_64') if os.path.isdir(br_mxy_lrd): self.pbl_list.append(br_mxy_lrd) else: self.pbl_list.append(None) if '06_lrd' == file.lower(): hs_lrd = os.path.join(post_path, r'06_lrd\hs_64') if os.path.isdir(hs_lrd): self.get_list.append(hs_lrd) else: self.get_list.append(None) if '05_ldd' == file.lower(): hs_ldd = os.path.join(post_path, r'05_ldd\hs_144') if os.path.isdir(hs_ldd): self.mbl_list.append(hs_ldd) else: self.mbl_list.append(None) print('LDD :', self.ldd_list) print('LRD :', self.lrd_list) print('NAC :', self.nac_list) print('PBL :', self.pbl_list) print('GET :', self.get_list) print('MBL :', self.mbl_list) print() def check(): error_flag = None input_isok = True # check excel input if not self.xls_temp: error_flag = 0 input_isok = False return error_flag, input_isok if len(self.ult_list) != len( self.loopname) and self.cb_ultimate.isChecked(): error_flag = 1 input_isok = False return error_flag, input_isok if len(self.fat_list) != len( self.loopname) and self.cb_fatigue.isChecked(): error_flag = 2 input_isok = False return error_flag, input_isok if not all(self.loopname): error_flag = 3 input_isok = False return error_flag, input_isok # check function if self.cb_fatwind.isChecked() and (len(self.lct_list) != len(self.fat_list)): error_flag = 4 input_isok = False return error_flag, input_isok if self.cb_fatdlc.isChecked() and (len(self.loopname) != len(self.fat_list)): error_flag = 5 input_isok = False return error_flag, input_isok if ((self.cb_dynpowc.isChecked() or self.cb_aepdlc12.isChecked()) and (len(self.lct_list) != len(self.loopname) or len(self.dlc_list) != len(self.loopname))): error_flag = 6 input_isok = False return error_flag, input_isok if self.cb_heatmap.isChecked() and (len(self.ult_list) != len(self.loopname)): error_flag = 7 input_isok = False return error_flag, input_isok if not ( (self.radio_new and self.xls_path and self.xls_name) or (self.radio_app and self.out_path)): error_flag = 8 input_isok = False return error_flag, input_isok if self.cb_plotldd.isChecked() and (len(self.ldd_list) != len(self.loopname)): error_flag = 9 input_isok = False return error_flag, input_isok if self.cb_plotlrd.isChecked() and (len(self.lrd_list) != len(self.loopname)): error_flag = 10 input_isok = False return error_flag, input_isok if self.cb_mainber.isChecked() and (len(self.mbl_list) != len(self.loopname)): error_flag = 11 input_isok = False return error_flag, input_isok if self.cb_pitbear.isChecked() and (len(self.pbl_list) != len(self.loopname)): error_flag = 12 input_isok = False return error_flag, input_isok if self.cb_gearequ.isChecked() and (len(self.get_list) != len(self.loopname)): error_flag = 13 input_isok = False return error_flag, input_isok if self.cb_nacacce.isChecked() and (len(self.nac_list) != len(self.loopname)): error_flag = 15 input_isok = False return error_flag, input_isok if not (self.cb_ultimate.isChecked() or self.cb_gearequ.isChecked() or self.cb_fatigue.isChecked() or self.cb_fatdlc.isChecked() or self.cb_fatwind.isChecked() or self.cb_heatmap.isChecked() or self.cb_plotldd.isChecked() or self.cb_plotlrd.isChecked() or self.cb_pitbear.isChecked() or self.cb_mainber.isChecked() or self.cb_dynpowc.isChecked() or self.cb_aepdlc12.isChecked() or self.cb_alarmid.isChecked() or self.cb_nacacce.isChecked()): error_flag = 14 input_isok = False return error_flag, input_isok return error_flag, input_isok check_result = check() # print(self.cb_dynpowc.isChecked()) # print(check_result[0], check_result[1]) if check_result[0] == 0: QMessageBox.about( self, 'Message', 'The excel template has not been choosed yet...\n\n' 'Please choose a excel template first!') elif check_result[0] == 1: QMessageBox.about( self, 'Message', 'The input for ultimate function is not satisfied...\n\n' 'Please make sure that the ultimate path is right!') elif check_result[0] == 2: QMessageBox.about( self, 'Message', 'The input for fatigue function is not satisfied...\n\n' 'Please make sure that the fatigue path is right!') elif check_result[0] == 3: QMessageBox.about( self, 'Message', 'The template is empty...\n\n' 'Please define the loop first!') elif check_result[0] == 4: QMessageBox.about( self, 'Message', 'The input for fatigue_wind function is not satisfied...\n\n' 'Please make sure that the lct and fatigue inputs are right!' ) elif check_result[0] == 5: QMessageBox.about( self, 'Message', 'The input for fatigue_case function is not satisfied...\n\n' 'Please make sure that the lct and fatigue inputs are right!' ) elif check_result[0] == 6: QMessageBox.about( self, 'Message', 'The input for aep of dlc12 function is not satisfied...\n\n' 'Please make sure that the lct and dlc inputs are right!' ) elif check_result[0] == 7: QMessageBox.about( self, 'Message', 'The input for heat map function is not satisfied...\n\n' 'Please make sure that the ultimate path inputs are right!' ) elif check_result[0] == 8: QMessageBox.about( self, 'Message', 'The output excel has not been choosed...\n\n' 'Please make sure that the ultimate path inputs are right!' ) elif check_result[0] == 9: QMessageBox.about( self, 'Message', 'The input for ldd function is not satisfied...\n\n' 'Please make sure that the ldd path inputs are right!') elif check_result[0] == 10: QMessageBox.about( self, 'Message', 'The input for main bearing life function is not satisfied...\n\n' 'Please make sure that the main bearing path inputs are right!' ) elif check_result[0] == 11: QMessageBox.about( self, 'Message', 'The input for pitch bearing life function is not satisfied...\n\n' 'Please make sure that the pitch bearing path inputs are right!' ) elif check_result[0] == 12: QMessageBox.about( self, 'Message', 'The input for lrd function is not satisfied...\n\n' 'Please make sure that the lrd path inputs are right!') elif check_result[0] == 13: QMessageBox.about( self, 'Message', 'The input for gearbox equivalent torque function is not satisfied...\n\n' 'Please make sure that the path inputs are right!') elif check_result[0] == 14: QMessageBox.about( self, 'Message', 'The function has not been chosen...\n\n' 'Please choose a function first!') elif check_result[0] == 15: QMessageBox.about( self, 'Message', 'The input for nacelle acceleration function is not satisfied...\n\n' 'Please make sure that the path inputs are right!') # check is OK, then disable the pannel if check_result[1]: QMessageBox.about( self, 'Message', 'The input for each functionality is OK...\n\n' 'You can continue to handle date!') self.btn_handle.setDisabled(False) self.btn_reset.setDisabled(False) self.lin1.setDisabled(True) self.btn1.setDisabled(True) self.btn_check.setDisabled(True) self.radio_main.setDisabled(True) self.radio_all.setDisabled(True) if self.radio_new.isChecked(): self.lin2.setDisabled(True) self.btn2.setDisabled(True) self.lin3.setDisabled(True) self.radio_new.setDisabled(True) self.radio_app.setDisabled(True) self.radio_main.setDisabled(True) self.radio_all.setDisabled(True) self.cb_aepdlc12.setDisabled(True) self.cb_heatmap.setDisabled(True) self.cb_fatigue.setDisabled(True) self.cb_fatwind.setDisabled(True) self.cb_fatdlc.setDisabled(True) self.cb_ultimate.setDisabled(True) self.cb_plotldd.setDisabled(True) self.cb_plotlrd.setDisabled(True) self.cb_dynpowc.setDisabled(True) self.cb_gearequ.setDisabled(True) self.cb_pitbear.setDisabled(True) self.cb_mainber.setDisabled(True) self.cb_nacacce.setDisabled(True) if self.radio_app.isChecked(): self.btn3.setDisabled(True) self.lin4.setDisabled(True) self.radio_new.setDisabled(True) self.radio_app.setDisabled(True) self.cb_aepdlc12.setDisabled(True) self.cb_heatmap.setDisabled(True) self.cb_fatigue.setDisabled(True) self.cb_fatwind.setDisabled(True) self.cb_fatdlc.setDisabled(True) self.cb_ultimate.setDisabled(True) self.cb_plotldd.setDisabled(True) self.cb_plotlrd.setDisabled(True) self.cb_gearequ.setDisabled(True) self.cb_pitbear.setDisabled(True) self.cb_mainber.setDisabled(True) else: self.btn_handle.setDisabled(True) except Exception as message: QMessageBox.about(self, 'Message', 'Please check the template!\n%s' % message) def handle(self): if self.cb_ultimate.isChecked(): self.ultimate = True else: self.ultimate = False if self.cb_fatigue.isChecked(): self.fatigue = True else: self.fatigue = False if self.cb_fatwind.isChecked(): self.fat_wind = True else: self.fat_wind = False if self.cb_heatmap.isChecked(): self.heat_map = True else: self.heat_map = False if self.cb_fatdlc.isChecked(): self.fat_case = True else: self.fat_case = False if self.cb_aepdlc12.isChecked() or self.cb_dynpowc.isChecked(): self.aep_dlc = True else: self.aep_dlc = False if self.cb_plotlrd.isChecked(): self.plot_lrd = True else: self.plot_lrd = False if self.cb_plotldd.isChecked(): self.plot_ldd = True else: self.plot_ldd = False if self.cb_mainber.isChecked(): self.main_bl = True else: self.main_bl = False if self.cb_pitbear.isChecked(): self.pitch_bl = True else: self.pitch_bl = False if self.cb_gearequ.isChecked(): self.gearbox = True else: self.gearbox = False if self.cb_nacacce.isChecked(): self.nacelle = True else: self.nacelle = False if self.radio_new.isChecked(): self.out_path = self.lin2.text().replace('\\', '/') self.xls_name = self.lin3.text() logging.basicConfig( level=logging.INFO, # 日志级别,只有日志级别大于等于设置级别的日志才会输出 format= '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', # 日志输出格式 datefmt='[%Y-%m_%d %H:%M:%S]', # 日期表示格式 filename=os.path.dirname(os.path.realpath(__file__)) + "/" + 'logger.log', # 输出定向的日志文件路径 filemode='a') try: new(excel_input=self.xls_temp, output_path=self.out_path, excel_name=self.xls_name, ultimate=self.ultimate, fatigue=self.fatigue, heat_map=self.heat_map, fat_case=self.fat_case, fat_wind=self.fat_wind, aep_dlc=self.aep_dlc, ldd=self.plot_ldd, lrd=self.plot_lrd, mbl=self.main_bl, pbl=self.pitch_bl, get=self.gearbox, nac=self.nacelle) QMessageBox.about(self, 'Message', 'Load summary table is done!') except Exception as error_message: QMessageBox.about(self, 'Message', '%s' % error_message) traceback.print_exc() logging.warning("exec failed, failed msg:" + traceback.format_exc()) if self.radio_app.isChecked(): self.xls_path = self.lin4.text() if '\\' in self.lin4.text(): self.xls_path = self.lin4.text().replace('\\', '/') append(self.xls_temp, self.xls_path, self.ultimate, self.fatigue, self.heat_map, self.fat_case, self.fat_wind, self.aep_dlc) QMessageBox.about(self, 'Message', 'Load summary table is done!') def reset(self): self.btn_handle.setDisabled(True) self.btn_reset.setDisabled(True) self.lin1.setDisabled(False) self.btn1.setDisabled(False) self.btn_check.setDisabled(False) if self.radio_new.isChecked(): self.lin2.setDisabled(False) self.btn2.setDisabled(False) self.lin3.setDisabled(False) self.radio_new.setDisabled(False) # self.radio_app.setDisabled(False) self.radio_main.setDisabled(False) self.radio_all.setDisabled(False) self.cb_aepdlc12.setDisabled(False) self.cb_heatmap.setDisabled(False) self.cb_fatigue.setDisabled(False) self.cb_fatwind.setDisabled(False) self.cb_fatdlc.setDisabled(False) self.cb_ultimate.setDisabled(False) self.cb_plotldd.setDisabled(False) self.cb_plotlrd.setDisabled(False) self.cb_dynpowc.setDisabled(False) self.cb_gearequ.setDisabled(False) self.cb_pitbear.setDisabled(False) self.cb_mainber.setDisabled(False) if self.radio_app.isChecked(): self.btn3.setDisabled(False) self.lin4.setDisabled(False) self.radio_new.setDisabled(False) self.radio_app.setDisabled(False) self.cb_aepdlc12.setDisabled(False) self.cb_heatmap.setDisabled(False) self.cb_fatigue.setDisabled(False) self.cb_fatwind.setDisabled(False) self.cb_fatdlc.setDisabled(False) self.cb_ultimate.setDisabled(False) self.cb_plotldd.setDisabled(False) self.cb_plotlrd.setDisabled(False) self.cb_dynpowc.setDisabled(False) self.cb_gearequ.setDisabled(False) self.cb_pitbear.setDisabled(False) self.cb_mainber.setDisabled(False) # if self.radio_new.isChecked(): # # self.lin1.setDisabled(False) # self.lin2.setDisabled(False) # self.lin3.setDisabled(False) # self.lin4.setDisabled(False) # self.cb_aepdlc12.setDisabled(False) # self.cb_heatmap.setDisabled(False) # self.cb_fatigue.setDisabled(False) # self.cb_fatwind.setDisabled(False) # self.cb_fatdlc.setDisabled(False) # self.cb_ultimate.setDisabled(False) # # if self.radio_app.isChecked(): # # self.lin1.setDisabled(False) # self.lin4.setDisabled(False) # self.cb_aepdlc12.setDisabled(False) # self.cb_heatmap.setDisabled(False) # self.cb_fatigue.setDisabled(False) # self.cb_fatwind.setDisabled(False) # self.cb_fatdlc.setDisabled(False) # self.cb_ultimate.setDisabled(False) def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())
class SettingsWindow(QWidget): def eventFilter(self, object, event): if event.type() == QEvent.FocusIn: self.customspeedRB.setChecked(True) return super(SettingsWindow, self).eventFilter(object, event) def setupUi(self, Form, host='192.168.2.171'): Form.resize(250, 900) Form.setStyleSheet('font: 10pt \"Tahoma\";') self.host = host self.downtimechecked = 0 self.default = defaultsettings self.defaultcutbacks = defaultcutbacksettings db = connector.connect(host=self.host, user="******", passwd="Sequal1234", database="simulation", use_pure=True) buttonSS = "QPushButton {\n" \ " background-color: ;\n" \ " background-color: qlineargradient(spread:pad, x1:0, y1:0, " \ "x2:1, y2:1, stop:0 rgba(0, 115, 119, 255), stop:1 rgb(4, 147, " \ "131));\n" \ " color: white;\n" \ " height: 25px;\n" \ " border: None;\n" \ " border-radius: 2px;\n" \ " \n" \ " font: 11pt \"Tahoma\";\n" \ " width: " self.mainlayout = QVBoxLayout(Form) hlayout = QHBoxLayout() self.titlelabel = QLabel(Form) self.titlelabel.setStyleSheet( 'font: 12pt \"Tahoma\"; font-weight: bold;') hlayout.addWidget(self.titlelabel) hspacer = QSpacerItem(40, 25, QSizePolicy.Expanding, QSizePolicy.Minimum) hlayout.addItem(hspacer) self.resetbutton = QPushButton(Form) self.resetbutton.setStyleSheet(buttonSS + "140px;}") self.resetbutton.setCursor(QCursor(Qt.PointingHandCursor)) hlayout.addWidget(self.resetbutton) self.mainlayout.addLayout(hlayout) self.hlayout = QVBoxLayout() # ################ # # GENERAL SETTINGS # # ################ # self.generalGB = QGroupBox(Form) self.generalGB.setStyleSheet('QGroupBox {font: 11pt \"Tahoma\";}') self.hlayout2 = QVBoxLayout(self.generalGB) self.hlayout2.setSpacing(15) self.gridlayout = QGridLayout() self.gridlayout.setHorizontalSpacing(2) self.loggaplabel = QLabel(self.generalGB) self.gridlayout.addWidget(self.loggaplabel, 0, 0, 1, 1) self.loggapTB = QDoubleSpinBox(self.generalGB) self.loggapTB.setButtonSymbols(QAbstractSpinBox.NoButtons) self.loggapTB.setSingleStep(0.1) self.loggapTB.setMinimum(0.3) self.loggapTB.setStyleSheet( 'QDoubleSpinBox::disabled {color: rgb(200, 200, 200);}') self.gridlayout.addWidget(self.loggapTB, 0, 1, 1, 1) self.loggapAuto = QCheckBox(self.generalGB) self.gridlayout.addWidget(self.loggapAuto, 0, 2, 1, 1) self.numbinslabel = QLabel(self.generalGB) self.gridlayout.addWidget(self.numbinslabel, 1, 0, 1, 1) self.numbinsTB = QSpinBox(self.generalGB) self.numbinsTB.setMinimum(1) self.numbinsTB.setMaximum(40) self.gridlayout.addWidget(self.numbinsTB, 1, 1, 1, 1) vspacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridlayout.addItem(vspacer, 2, 0, 1, 1) self.hlayout2.addLayout(self.gridlayout) # hspacer = QSpacerItem( # 20, 40, QSizePolicy.Expanding, QSizePolicy.Minimum) # self.hlayout2.addItem(hspacer) # Line speed group box self.linespeedGB = QGroupBox(self.generalGB) self.linespeedGB.setStyleSheet('QGroupBox {font: 11pt \"Tahoma\";}') vlayout = QVBoxLayout(self.linespeedGB) self.highspeedRB = QRadioButton(self.linespeedGB) vlayout.addWidget(self.highspeedRB) self.lowspeedRB = QRadioButton(self.linespeedGB) vlayout.addWidget(self.lowspeedRB) self.autospeedRB = QRadioButton(self.linespeedGB) vlayout.addWidget(self.autospeedRB) hlayout = QHBoxLayout() hlayout.setSpacing(0) self.customspeedRB = QRadioButton(self.linespeedGB) self.customspeedRB.setMinimumWidth(17) self.customspeedRB.setMaximumWidth(17) hlayout.addWidget(self.customspeedRB) self.customspeedTB = QDoubleSpinBox(self.linespeedGB) self.customspeedTB.setButtonSymbols(QAbstractSpinBox.NoButtons) self.customspeedTB.setDecimals(1) self.customspeedTB.setMaximum(200) self.customspeedTB.installEventFilter(self) hlayout.addWidget(self.customspeedTB) vlayout.addLayout(hlayout) vspacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) vlayout.addItem(vspacer) self.hlayout2.addWidget(self.linespeedGB) self.hlayout.addWidget(self.generalGB) # ################# # # DOWNTIME SETTINGS # # ################# # self.downtimeGB = QGroupBox(Form) self.downtimeGB.setStyleSheet('QGroupBox {font: 11pt \"Tahoma\";}') gridlayout = QGridLayout(self.downtimeGB) self.downtimeCBall = QCheckBox(self.downtimeGB) gridlayout.addWidget(self.downtimeCBall, 0, 0, 1, 1) self.downtimeCBtexts = list( read_sql('SELECT * From DowntimeSettings Where SimID = -1;', db).head())[1:] self.downtimeCBs = [] for i in range(len(self.downtimeCBtexts)): self.downtimeCBs.append(QCheckBox(self.downtimeGB)) row = int(i / 2) col = i % 2 gridlayout.addWidget(self.downtimeCBs[i], row + 1, col, 1, 1) vspacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) gridlayout.addItem(vspacer, row + 1, 0, 1, 1) self.hlayout.addWidget(self.downtimeGB) # ################ # # CUTBACK SETTINGS # # ################ # self.cutbackGB = QGroupBox(Form) self.cutbackGB.setStyleSheet('QGroupBox {font: 11pt \"Tahoma\";}') gridlayout = QGridLayout(self.cutbackGB) self.cutbackCBtexts = list( read_sql('SELECT * From CutbackSettings Where SimID = -1;', db).head())[1:] self.cutbackCBs = [] for i in range(len(self.cutbackCBtexts)): self.cutbackCBs.append(QCheckBox(self.cutbackGB)) row = int(i / 2) col = i % 2 gridlayout.addWidget(self.cutbackCBs[i], row, col, 1, 1) vspacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) gridlayout.addItem(vspacer, row + 1, 0, 1, 1) self.hlayout.addWidget(self.cutbackGB) self.mainlayout.addLayout(self.hlayout) self.buttonbox = QDialogButtonBox(Form) self.buttonbox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonbox.setStyleSheet("QDialogButtonBox " + buttonSS + "70px;}") for w in self.buttonbox.children(): if w.metaObject().className() == "QPushButton": w.setCursor(QCursor(Qt.PointingHandCursor)) self.mainlayout.addWidget(self.buttonbox) vspacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.mainlayout.addItem(vspacer) self.retranslateUi(Form) self.SetDefaultSettings() # ####### # # SIGNALS # # ####### # self.resetbutton.clicked.connect(self.SetDefaultSettings) self.loggapAuto.stateChanged.connect(self.onLogGapAuto) self.downtimeCBall.stateChanged.connect(self.onDowntimeAll) for cb in self.downtimeCBs: cb.stateChanged.connect(self.onDowntimeCB) for cb in self.cutbackCBs: cb.stateChanged.connect(self.onCutbackCB) self.numbinsTB.valueChanged.connect(self.showResetButton) self.loggapTB.valueChanged.connect(self.showResetButton) if defaultsettings[3] == 55.0: self.highspeedRB.toggled.connect(self.showResetButton) elif defaultsettings[3] == 35.0: self.lowspeedRB.toggled.connect(self.showResetButton) else: self.autospeedRB.toggled.connect(self.showResetButton) def SetDefaultSettings(self): if defaultsettings[3] == 55.0: self.highspeedRB.setChecked(True) elif defaultsettings[3] == 35.0: self.lowspeedRB.setChecked(True) else: self.autospeedRB.setChecked(True) if defaultsettings[0] > 0: self.loggapTB.setValue(defaultsettings[0]) self.loggapAuto.setChecked(False) else: self.loggapAuto.setChecked(True) self.numbinsTB.setValue(defaultsettings[2]) self.downtimeCBall.setChecked(Qt.Checked) self.downtimechecked = 4 for cb in self.downtimeCBs: cb.setChecked(True) for cb in self.cutbackCBs: cb.setChecked(False) for cb in self.defaultcutbacks: self.cutbackCBs[self.cutbackCBtexts.index(cb)].setChecked(True) self.resetbutton.setVisible(False) def onCutbackCB(self, state): self.showResetButton() def onDowntimeAll(self, state): self.showResetButton() if state == Qt.Unchecked: for cb in self.downtimeCBs: cb.setChecked(False) elif state == Qt.Checked: for cb in self.downtimeCBs: cb.setChecked(True) elif state == Qt.PartiallyChecked and self.downtimechecked == 0: for cb in self.downtimeCBs: cb.setChecked(True) def onDowntimeCB(self, state): self.showResetButton() if state == Qt.Checked: self.downtimechecked += 1 else: self.downtimechecked -= 1 if self.downtimechecked == len(self.downtimeCBs): self.downtimeCBall.setCheckState(Qt.Checked) elif self.downtimechecked == 0: self.downtimeCBall.setCheckState(Qt.Unchecked) else: self.downtimeCBall.setCheckState(Qt.PartiallyChecked) def onLogGapAuto(self, state): self.showResetButton() self.loggapTB.setDisabled(state) def showResetButton(self): self.resetbutton.setVisible(True) def setupReadOnly(self): self.highspeedRB.setDisabled(True) self.lowspeedRB.setDisabled(True) self.autospeedRB.setDisabled(True) self.customspeedRB.setDisabled(True) self.customspeedTB.setDisabled(True) self.loggapAuto.setDisabled(True) self.loggapTB.setDisabled(True) self.loggapTB.setStyleSheet('') self.numbinsTB.setDisabled(True) for cb in self.downtimeCBs: cb.setDisabled(True) self.downtimeCBall.setDisabled(True) for cb in self.cutbackCBs: cb.setDisabled(True) self.resetbutton.setVisible(False) def retranslateUi(self, Form): _translate = QCoreApplication.translate self.titlelabel.setText(_translate('Form', 'Settings')) self.resetbutton.setText(_translate('Form', 'Reset to Default')) self.generalGB.setTitle(_translate('Form', 'General')) self.linespeedGB.setTitle(_translate('Form', 'Line Speed')) self.highspeedRB.setText(_translate('Form', '55 m/min')) self.lowspeedRB.setText(_translate('Form', '35 m/min')) self.autospeedRB.setText(_translate('Form', 'Auto')) self.customspeedRB.setText('') self.customspeedTB.setSuffix(_translate('Form', ' m/min')) self.loggaplabel.setText(_translate('Form', 'Log Gap: ')) self.loggapTB.setValue(defaultsettings[0]) self.loggapTB.setSuffix(_translate('Form', ' m')) self.loggapAuto.setText(_translate('Form', 'Auto')) self.numbinslabel.setText(_translate('Form', 'Number\nof Bins: ')) self.downtimeGB.setTitle(_translate('Form', 'Simulated Downtime')) for i in range(len(self.downtimeCBtexts)): self.downtimeCBs[i].setText( _translate('Form', self.downtimeCBtexts[i])) self.downtimeCBall.setText(_translate('Form', 'All')) self.cutbackGB.setTitle(_translate('Form', 'Cutbacks')) for i in range(len(self.cutbackCBtexts)): self.cutbackCBs[i].setText( _translate('Form', self.cutbackCBtexts[i]))
class Inputwindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle('Input File Creator') self.directory_label = QLabel('Directory:') self.directory_line = QLineEdit() self.browse_button = QPushButton('Browse') self.input_label = QLabel('Input file name: ') self.input_line = QLineEdit() self.output_label = QLabel('Output file name: ') self.output_line = QLineEdit() self.x_profile_check = QRadioButton('x- profile') self.y_profile_check = QRadioButton('y- profile') self.xy_profiles_check = QRadioButton('x- and y- profiles') self.dose_map_check = QRadioButton('xy 2D dose map') self.z_PDD_check = QRadioButton('z- PDD') self.detector_check = QRadioButton('W-1 detector') self.lattice_size_label = QLabel('Lattice size (cm):') self.lattice_size_line = QLineEdit() self.depth_label = QLabel('Depth (cm):') self.depth_line = QLineEdit() self.x_offaxis_label = QLabel('x- off axis (cm)') self.x_offaxis_line = QLineEdit() self.y_offaxis_label = QLabel('y- off axis (cm)') self.y_offaxis_line = QLineEdit() self.x1_label = QLabel('X1:') self.x1_line = QLineEdit() self.x2_label = QLabel('X2:') self.x2_line = QLineEdit() self.y1_label = QLabel('Y1:') self.y1_line = QLineEdit() self.y2_label = QLabel('Y2:') self.y2_line = QLineEdit() self.mlc_checkbox_1 = QRadioButton('No MLC') self.mlc_checkbox_2 = QRadioButton('Standard MLC') self.mlc_checkbox_3 = QRadioButton('Simplified MLC') self.mlc_x_label = QLabel('MLC x opening:') self.mlc_x_line = QLineEdit() self.mlc_y_label = QLabel('MLC y opening:') self.mlc_y_line = QLineEdit() self.mlc_customize_button = QPushButton('Customize field') self.machine_label = QLabel('Machine') self.machine_combo = QComboBox() self.beam_lable = QLabel('Beam') self.beam_combo = QComboBox() self.beam_button = QPushButton('Choose File') self.tally_label = QLabel('Tally:') self.tally_combo = QComboBox() self.nps_label = QLabel('nps:') self.nps_line = QLineEdit() self.randseed_label = QLabel('Random Seed:') self.randseed_line = QLineEdit() self.randseed_button = QPushButton('Random') self.cutoff_p_label = QLabel('cutoff:p (MeV)') self.cutoff_p_line = QLineEdit() self.cutoff_e_label = QLabel('cutoff:e (MeV)') self.cutoff_e_line = QLineEdit() self.comment_box = QTextEdit() self.print_button = QPushButton('Print', self) self.check_length_button = QPushButton('Check Lines Length', self) self.beam_window = Beam() # default values as validators self.directory_line.setText(os.getcwd()) self.lattice_size_line.setValidator(QDoubleValidator(self)) self.lattice_size_line.setText('0.2') self.depth_line.setValidator(QDoubleValidator(self)) self.depth_line.setText('10') self.x_offaxis_line.setValidator((QDoubleValidator(self))) self.x_offaxis_line.setText('0') self.y_offaxis_line.setValidator(QDoubleValidator(self)) self.y_offaxis_line.setText('0') self.x1_line.setValidator(QDoubleValidator(self)) self.x2_line.setValidator(QDoubleValidator(self)) self.y1_line.setValidator(QDoubleValidator(self)) self.y2_line.setValidator(QDoubleValidator(self)) self.mlc_x_line.setText('0') self.mlc_x_line.setValidator(QDoubleValidator(self)) self.mlc_y_line.setText('0') self.mlc_y_line.setValidator(QDoubleValidator(self)) self.nps_line.setValidator(QIntValidator(self)) self.randseed_line.setValidator(QIntValidator(self)) self.randseed_line.setText(str(randint(10 ** 12, 10 ** 13) * 2 + 1)) self.cutoff_p_line.setValidator(QDoubleValidator(self)) self.cutoff_p_line.setText('0.01') self.cutoff_e_line.setValidator(QDoubleValidator(self)) self.cutoff_e_line.setText('0.20') self.x1_line.setText('5') self.x2_line.setText('-5') self.y1_line.setText('5') self.y2_line.setText('-5') self.nps_line.setText('13000000000') self.comments_text = '' # layouts self.main_layout = QVBoxLayout() self.file_group = QGroupBox('File information') self.file_layout = QGridLayout() self.objective_group = QGroupBox('Objective') self.objective_layout = QGridLayout() self.jaws_group = QGroupBox('Jaws positions (cm)') self.jaws_layout = QGridLayout() self.mlc_group = QGroupBox('MLC opening field (cm), only symmetrical in current version.') self.mlc_layout = QGridLayout() self.simulation_group = QGroupBox('Simulation information') self.simulation_layout = QGridLayout() self.center_widget = QWidget() self.center_layout = QHBoxLayout() self.left_widget = QWidget() self.left_layout = QVBoxLayout() self.right_widget = QWidget() self.right_layout = QVBoxLayout() self.comments_group = QGroupBox('Comments (Please add \'c \' at the beginning of each line)') self.comments_layout = QVBoxLayout() self.cc = ContentCheck() self.layout_init() self.pushbutton_init() self.combobox_init() def layout_init(self): self.file_layout.addWidget(self.directory_label, 0, 0) self.file_layout.addWidget(self.directory_line, 0, 1) self.file_layout.addWidget(self.browse_button, 0, 2) self.file_layout.addWidget(self.input_label, 1, 0) self.file_layout.addWidget(self.input_line, 1, 1) self.file_layout.addWidget(self.output_label, 2, 0) self.file_layout.addWidget(self.output_line, 2, 1) self.file_group.setLayout(self.file_layout) self.objective_layout.addWidget(self.z_PDD_check, 0, 0) self.objective_layout.addWidget(self.xy_profiles_check, 1, 0) self.objective_layout.addWidget(self.x_profile_check, 2, 0) self.objective_layout.addWidget(self.y_profile_check, 3, 0) self.objective_layout.addWidget(self.detector_check, 4, 0) self.objective_layout.addWidget(self.dose_map_check, 5, 0) self.objective_layout.addWidget(self.lattice_size_label, 0, 1) self.objective_layout.addWidget(self.lattice_size_line, 0, 2) self.objective_layout.addWidget(self.depth_label, 1, 1) self.objective_layout.addWidget(self.depth_line, 1, 2) self.objective_layout.addWidget(self.x_offaxis_label, 2, 1) self.objective_layout.addWidget(self.x_offaxis_line, 2, 2) self.objective_layout.addWidget(self.y_offaxis_label, 3, 1) self.objective_layout.addWidget(self.y_offaxis_line, 3, 2) self.objective_group.setLayout(self.objective_layout) self.jaws_layout.addWidget(self.x1_label, 0, 0) self.jaws_layout.addWidget(self.x1_line, 0, 1) self.jaws_layout.addWidget(self.x2_label, 0, 2) self.jaws_layout.addWidget(self.x2_line, 0, 3) self.jaws_layout.addWidget(self.y1_label, 1, 0) self.jaws_layout.addWidget(self.y1_line, 1, 1) self.jaws_layout.addWidget(self.y2_label, 1, 2) self.jaws_layout.addWidget(self.y2_line, 1, 3) self.jaws_group.setLayout(self.jaws_layout) self.mlc_layout.addWidget(self.mlc_checkbox_1, 0, 0) self.mlc_layout.addWidget(self.mlc_checkbox_2, 0, 1) self.mlc_layout.addWidget(self.mlc_checkbox_3, 0, 2) self.mlc_layout.addWidget(self.mlc_x_label, 1, 0) self.mlc_layout.addWidget(self.mlc_x_line, 1, 1) self.mlc_layout.addWidget(self.mlc_y_label, 2, 0) self.mlc_layout.addWidget(self.mlc_y_line, 2, 1) self.mlc_layout.addWidget(self.mlc_customize_button, 3, 0) self.mlc_group.setLayout(self.mlc_layout) self.simulation_layout.addWidget(self.machine_label, 0, 0) self.simulation_layout.addWidget(self.machine_combo, 0, 1) self.simulation_layout.addWidget(self.beam_lable, 1, 0) self.simulation_layout.addWidget(self.beam_combo, 1, 1) self.simulation_layout.addWidget(self.beam_button, 1, 2) self.simulation_layout.addWidget(self.tally_label, 2, 0) self.simulation_layout.addWidget(self.tally_combo, 2, 1) self.simulation_layout.addWidget(self.nps_label, 3, 0) self.simulation_layout.addWidget(self.nps_line, 3, 1) self.simulation_layout.addWidget(self.randseed_label, 4, 0) self.simulation_layout.addWidget(self.randseed_line, 4, 1) self.simulation_layout.addWidget(self.randseed_button, 4, 2) self.simulation_layout.addWidget(self.cutoff_p_label, 5, 0) self.simulation_layout.addWidget(self.cutoff_p_line, 5, 1) self.simulation_layout.addWidget(self.cutoff_e_label, 6, 0) self.simulation_layout.addWidget(self.cutoff_e_line, 6, 1) self.simulation_group.setLayout(self.simulation_layout) self.center_layout.addWidget(self.left_widget) self.center_layout.addWidget(self.right_widget) self.center_widget.setLayout(self.center_layout) self.left_layout.addWidget(self.file_group) self.left_layout.addWidget(self.simulation_group) self.left_widget.setLayout(self.left_layout) self.right_layout.addWidget(self.objective_group) self.right_layout.addWidget(self.jaws_group) self.right_layout.addWidget(self.mlc_group) self.right_widget.setLayout(self.right_layout) self.comments_layout.addWidget(self.comment_box) self.comments_group.setLayout(self.comments_layout) self.main_layout.addWidget(self.center_widget) self.main_layout.addStretch(1) self.main_layout.addWidget(self.comments_group) self.main_layout.addWidget(self.print_button) self.main_layout.addWidget(self.check_length_button) self.setLayout(self.main_layout) def pushbutton_init(self): self.browse_button.clicked.connect(self.findd) self.mlc_checkbox_1.toggled.connect(self.mlc_x_line.setDisabled) self.mlc_checkbox_1.toggled.connect(self.mlc_y_line.setDisabled) self.mlc_checkbox_1.toggled.connect(self.mlc_x_label.setDisabled) self.mlc_checkbox_1.toggled.connect(self.mlc_y_label.setDisabled) self.mlc_checkbox_1.toggled.connect(self.mlc_state) self.mlc_checkbox_2.toggled.connect(self.mlc_state) self.mlc_checkbox_3.setDisabled(True) self.mlc_checkbox_1.setChecked(True) self.mlc_customize_button.setDisabled(True) self.x_profile_check.toggled.connect(self.objective_choice) self.x_profile_check.toggled.connect(self.x_offaxis_label.setDisabled) self.x_profile_check.toggled.connect(self.x_offaxis_line.setDisabled) self.y_profile_check.toggled.connect(self.objective_choice) self.y_profile_check.toggled.connect(self.y_offaxis_label.setDisabled) self.y_profile_check.toggled.connect(self.y_offaxis_line.setDisabled) self.z_PDD_check.toggled.connect(self.depth_line.setDisabled) self.z_PDD_check.toggled.connect(self.depth_label.setDisabled) self.z_PDD_check.toggled.connect(self.objective_choice) self.detector_check.toggled.connect(self.lattice_size_label.setDisabled) self.detector_check.toggled.connect(self.lattice_size_line.setDisabled) self.detector_check.toggled.connect(self.objective_choice) self.dose_map_check.setDisabled(True) self.randseed_button.clicked.connect(self.generate_randseed) self.print_button.clicked.connect(self.content_check) self.z_PDD_check.setChecked(True) # This setChecked statement has to be here. self.beam_button.setDisabled(False) self.beam_button.clicked.connect(self.change_beam) self.check_length_button.clicked.connect(self.input_length_check) def beam_combobox_init(self): self.beam_combo.clear() beam_list = beam_dict.list_beams() if len(beam_list) == 0: self.beam_combo.addItem('No commissioned beam') else: for i in range(len(beam_list)): self.beam_combo.addItem(beam_list[i]) glv.set_value('beam', beam_list[0]) self.beam_combo.addItem('Other (please choose files)') def combobox_init(self): # machine combo box self.machine_combo.addItem('Edge(HDMLC-120)') self.machine_combo.addItem('TrueBeam(MLC-120)-NOT COMMISSIONED') # tally combo box self.tally_combo.addItem('F8*') def beam_init(self): try: beam = glv.get_value('beam') beam_info = beam_dict.get_beam(beam) glv.set_value('spectrum file', beam_info[0]) glv.set_value('angular file', beam_info[1]) glv.set_value('spatial file', beam_info[2]) except KeyError: pass def variables_init(self): glv.set_value('directory', self.directory_line.text()) glv.set_value('input file name', self.input_line.text()) glv.set_value('output file name', self.output_line.text()) glv.set_value('e cutoff', self.cutoff_e_line.text()) glv.set_value('p cutoff', self.cutoff_p_line.text()) glv.set_value('nps', self.nps_line.text()) glv.set_value('randomseed', self.randseed_line.text()) glv.set_value('lattice size', self.lattice_size_line.text()) glv.set_value('depth', self.depth_line.text()) glv.set_value('x1 Jaw', self.x1_line.text()) glv.set_value('x2 Jaw', self.x2_line.text()) glv.set_value('y1 Jaw', self.y1_line.text()) glv.set_value('y2 Jaw', self.y2_line.text()) glv.set_value('mlc x', self.mlc_x_line.text()) glv.set_value('mlc y', self.mlc_y_line.text()) glv.set_value('x offaxis', self.x_offaxis_line.text()) glv.set_value('y offaxis', self.y_offaxis_line.text()) glv.set_value('mlc state', '') glv.set_value('objective', '') if self.comment_box.toPlainText() != '': self.comments_text = str('\n' + self.comment_box.toPlainText() + '\n') else: self.comments_text = '\n' glv.set_value('comments', self.comments_text) def findd(self): d = Finddir().find_dir() if d == '': pass else: self.directory_line.setText(d) def beam_choice(self): beam = self.beam_combo.currentText() if beam == 'Other (please choose files)': self.beam_button.setDisabled(False) else: glv.set_value('beam', beam) self.beam_init() def mlc_state(self): if self.mlc_checkbox_1.isChecked(): glv.set_value('mlc state', 'no mlc') elif self.mlc_checkbox_3.isChecked(): glv.set_value('mlc state', 'simplified mlc') elif self.mlc_checkbox_2.isChecked(): glv.set_value('mlc state', 'standard mlc') def objective_choice(self): if self.x_profile_check.isChecked(): glv.set_value('objective', 'x') elif self.y_profile_check.isChecked(): glv.set_value('objective', 'y') elif self.xy_profiles_check.isChecked(): glv.set_value('objective', 'xy') elif self.dose_map_check.isChecked(): glv.set_value('objective', 'dose map') elif self.z_PDD_check.isChecked(): glv.set_value('objective', 'z') elif self.detector_check.isChecked(): glv.set_value('objective', 'd') def change_beam(self): self.beam_window.show() def generate_randseed(self): random_number = str(randint(10 ** 12, 10 ** 13) * 2 + 1) self.randseed_line.setText(random_number) def content_check(self): self.variables_init() self.mlc_state() self.objective_choice() self.beam_choice() if ContentCheck().final_check(): file_print() else: pass # glv.clear_value() def input_length_check(self): self.variables_init() ContentCheck().length_check()