Пример #1
0
 def __new_workbook(self):
     """Create (Clean) a new workbook."""
     if self.check_file_changed():
         return
     self.clear()
     self.database_widget.reset()
     logger.info("Created a new workbook.")
Пример #2
0
 def __algorithm(self) -> Dict[str, Any]:
     """Get the algorithm result."""
     t0 = time()
     expression, tf = self.__generate_process()
     time_spend = time() - t0
     cpu = numpy.distutils.cpuinfo.cpu.info[0]
     last_gen = tf[-1][0]
     mechanism = {
         'Algorithm': self.type_num.value,
         'time': time_spend,
         'last_gen': last_gen,
         'last_fitness': tf[-1][1],
         'interrupted': str(last_gen) if self.is_stop else 'False',
         'settings': self.settings,
         'hardware_info': {
             'os': f"{system()} {release()} {machine()}",
             'memory': f"{virtual_memory().total / (1 << 30):.04f} GB",
             'cpu': cpu.get("model name", cpu.get('ProcessorNameString',
                                                  '')),
         },
         'time_fitness': tf,
     }
     mechanism.update(self.mech_params)
     mechanism['Expression'] = expression
     logger.info(f"cost time: {time_spend:.02f} [s]")
     return mechanism
Пример #3
0
    def __path_dlg(self, item: QListWidgetItem):
        """View path data."""
        name = item.text().split(":")[0]
        try:
            data = self.__path_data[name]
        except KeyError:
            return

        points_text = ", ".join(f"Point{i}" for i in range(len(data)))
        if QMessageBox.question(
            self,
            "Path data",
            f"This path data including {points_text}.",
            (QMessageBox.Save | QMessageBox.Close),
            QMessageBox.Close
        ) != QMessageBox.Save:
            return

        file_name = self.output_to(
            "path data",
            ["Comma-Separated Values (*.csv)", "Text file (*.txt)"]
        )
        if not file_name:
            return

        with open(file_name, 'w', encoding='utf-8', newline='') as stream:
            writer = csv.writer(stream)
            for point in data:
                for coordinate in point:
                    writer.writerow(coordinate)
                writer.writerow(())
        logger.info(f"Output path data: {file_name}")
Пример #4
0
 def __console_disconnect(self):
     """Turn the console log to OS command line (stdout)."""
     logger.info("Disconnect from GUI console.")
     XStream.back()
     self.console_connect_button.setEnabled(True)
     self.console_disconnect_button.setEnabled(False)
     logger.info("Disconnect from GUI console.")
Пример #5
0
 def __console_connect(self):
     """Turn the OS command line (stdout) log to console."""
     logger.info("Connect to GUI console.")
     XStream.stdout().message_written.connect(self.__append_to_console)
     self.console_connect_button.setEnabled(False)
     self.console_disconnect_button.setEnabled(True)
     logger.info("Connect to GUI console.")
Пример #6
0
 def closeEvent(self, event):
     """Close event to avoid user close the window accidentally."""
     if self.check_file_changed():
         event.ignore()
         return
     if self.inputs_widget.inputs_play_shaft.isActive():
         self.inputs_widget.inputs_play_shaft.stop()
     self.save_settings()
     XStream.back()
     logger.info("Exit")
     event.accept()
Пример #7
0
 def save_reply_box(self, title: str, file_name: str):
     """Show message when successfully saved."""
     size = QFileInfo(file_name).size()
     logger.debug("Size: " + (
         f"{size / 1024 / 1024:.02f} MB"
         if size / 1024 // 1024 else
         f"{size / 1024:.02f} KB"
     ))
     QMessageBox.information(
         self,
         f"Initial Saved: {title}",
         f"Successfully saved:\n{file_name}"
     )
     logger.info(f"Initial saved: [\"{file_name}\"]")
Пример #8
0
 def __delete_branch(self):
     """Delete all commits in the branch."""
     if not self.BranchList.currentRow() > -1:
         return
     branch_name = self.BranchList.currentItem().text()
     if branch_name == self.branch_current.text():
         QMessageBox.warning(self, "Warning",
                             "Cannot delete current branch.")
         return
     file_name = self.file_name.absoluteFilePath()
     # Connect on database to remove all the commit in this branch.
     with _db.atomic():
         CommitModel.delete().where(
             CommitModel.branch.in_(BranchModel.select().where(
                 BranchModel.name == branch_name))).execute()
         BranchModel.delete().where(
             BranchModel.name == branch_name).execute()
     _db.close()
     logger.info(f"Branch {branch_name} was deleted.")
     # Reload database.
     self.read(file_name)
Пример #9
0
 def load_example(self, is_import: bool = False) -> bool:
     """Load example to new workbook."""
     if self.__check_file_changed():
         return False
     # load example by expression.
     example_name, ok = QInputDialog.getItem(self, "Examples",
                                             "Select an example to load:",
                                             sorted(example_list), 0, False)
     if not ok:
         return False
     expr, inputs = example_list[example_name]
     if not is_import:
         self.reset()
         self.__clear_func()
     self.__parse_func(expr)
     if not is_import:
         # Import without input data.
         self.__load_inputs_func(inputs)
     self.file_name = QFileInfo(example_name)
     self.__workbook_saved()
     logger.info(f"Example \"{example_name}\" has been loaded.")
     return True
Пример #10
0
 def run(self):
     """Start the algorithm loop."""
     for name, path in self.mech_params['Target'].items():
         logger.debug(f"- [P{name}] ({len(path)})")
     t0 = time()
     for self.current_loop in range(self.loop):
         logger.info(
             f"Algorithm [{self.current_loop + 1}]: {self.type_num}")
         if self.is_stop:
             # Cancel the remaining tasks.
             logger.info("Canceled.")
             continue
         self.result.emit(self.__algorithm())
     logger.info(f"total cost time: {time() - t0:.02f} [s]")
     self.finished.emit()
Пример #11
0
 def __import_commit(self, commit: CommitModel):
     """Just load the expression. (No clear step!)"""
     self.__parse_func(_decompress(commit.mechanism))
     logger.info("The specified phase has been merged.")