def on_match_button_clicked(self): """Fitting function.""" l = len(self.path) if l==0: return index = list(range(l)) def polyfit(x: Sequence[float], y: Sequence[float], d: int): """Return a 2D fitting equation.""" coeffs = np.polyfit(x, y, d) #Fit values and mean. yhat = np.poly1d(coeffs)(x) ybar = np.sum(y)/len(y) return ( lambda t: sum(c * t**pow for pow, c in enumerate(reversed(coeffs))), np.sum((yhat - ybar)**2) / np.sum((y - ybar)**2) ) x_func, x_accuracy = polyfit(index, [x for x, y in self.path], 4) y_func, y_accuracy = polyfit(index, [y for x, y in self.path], 4) QMessageBox.information(self, "Curve fitting", "Accuracy:\nx: {:.02f}%\ny: {:.02f}%".format(x_accuracy, y_accuracy), QMessageBox.Ok, QMessageBox.Ok ) m = self.match_num.value() self.r_path = [(x_func(i/m*l), y_func(i/m*l)) for i in range(m)] self.accept()
def on_expression_auto_clicked(self): """Auto configure the solutions.""" if not self.driver_list.count(): QMessageBox.information(self, "Auto configure", "Please setting the driver joint(s).") return reply = QMessageBox.question( self, "Auto configure", "This function can detect the structure " + "to configure the solutions.\n" + "The current settings will be cleared.") if ((reply != QMessageBox.Yes) or (not self.on_expression_clear_clicked())): return exprs = vpoints_configure( graph2vpoints(self.PreviewWindow.G, self.PreviewWindow.pos, self.PreviewWindow.cus, self.PreviewWindow.same), [ eval(item.text().replace('P', '')) for item in list_items(self.driver_list) ], self.PreviewWindow.status) for expr in exprs: self.__addSolution(*expr) self.__hasSolution() self.__setWarning(self.expression_list_label, not self.PreviewWindow.isAllLock()) self.PreviewWindow.update()
def __match(self): """Fitting function.""" length = len(self.path) if length == 0: return index = list(range(length)) def poly_fit(x: List[float], y: List[float], d: int): """Return a 2D fitting equation.""" coefficient = np.polyfit(x, y, d) # Fit values and mean. y_hat = np.poly1d(coefficient)(x) y_bar = np.sum(y) / len(y) def func(t: float) -> float: """Return y(x) function.""" return sum(c * t**p for p, c in enumerate(reversed(coefficient))) yh_yb = y_hat - y_bar y_yb = y - y_bar return func, np.sum(yh_yb * yh_yb) / np.sum(y_yb * y_yb) x_func, x_accuracy = poly_fit(index, [x for x, y in self.path], 4) y_func, y_accuracy = poly_fit(index, [y for x, y in self.path], 4) QMessageBox.information( self, "Curve fitting", f"Accuracy:\nx: {x_accuracy:.02f}%\ny: {y_accuracy:.02f}%") m = self.match_num.value() self.r_path = [(x_func(i / m * length), y_func(i / m * length)) for i in range(m)] self.accept()
def __find_project(self): """Find in all project.""" self.find_list.clear() self.find_list_node.clear() node_current = self.tree_main.currentItem() if node_current is None: return root = _get_root(node_current) text, _, flags = self.__search_option() def find_in_nodes(node: QTreeWidgetItem, last_name: str = ''): """Find the word in all nodes.""" last_name += node.text(0) if node.childCount(): last_name += '->' code = int(node.text(2)) doc = self.data[code] pattern = re.compile(text.encode('utf-8'), flags) for m in pattern.finditer(doc.encode('utf-8')): start, end = m.span() item = QListWidgetItem(last_name) item.setToolTip(f"{code}:{start}:{end}") self.find_list_node[code] = node self.find_list.addItem(item) for i in range(node.childCount()): find_in_nodes(node.child(i), last_name) find_in_nodes(root) find_in_nodes = None count = self.find_list.count() QMessageBox.information(self, "Find in project", f"Found {count} result.")
def saveReplyBox(self, title: str, file_name: str): """Show message when successfully saved.""" size = QFileInfo(file_name).size() print("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}") print(f"Initial saved: [\"{file_name}\"]")
def __save_picture_clipboard(self): """Capture the canvas image to clipboard.""" QApplication.clipboard().setPixmap(self.main_canvas.grab()) QMessageBox.information( self, "Captured!", "Canvas widget picture is copy to clipboard." )
def saveReplyBox(self, title: str, file_name: str): """Show message when successfully saved.""" size = QFileInfo(file_name).size() print("Size: {}".format("{} MB".format(round(size / 1024 / 1024, 2)) if size / 1024 // 1024 else "{} KB".format(round(size / 1024, 2)))) QMessageBox.information(self, title, "Successfully converted:\n{}".format(file_name)) print("Successful saved: [\"{}\"]".format(file_name))
def on_Expression_auto_clicked(self): """Auto configure the solutions.""" if not self.Driver_list.count(): QMessageBox.information(self, "Auto configure", "Please setting the driver joint(s).") return reply = QMessageBox.question( self, "Auto configure", "This function can detect the structure to configure the solutions.\n" + "The current settings will be cleared.") if reply == QMessageBox.Yes and self.on_Expression_clear_clicked(): self.auto_configure_expression()
def savePMKS(self): """Output to PMKS as URL.""" url = "http://designengrlab.github.io/PMKS/pmks.html?mech=" url_table = [] for row in range(self.EntitiesPoint.rowCount()): type_and_angle = self.EntitiesPoint.item(row, 2).text().split(':') point_data = [ self.EntitiesPoint.item(row, 1).text(), type_and_angle[0], self.EntitiesPoint.item(row, 4).text(), self.EntitiesPoint.item(row, 5).text(), ] if len(type_and_angle) == 2: point_data.append(type_and_angle[1]) point_data.append('tfff') url_table.append(','.join(point_data)) url += '|'.join(url_table) + '|' text = '\n'.join( ("Copy and past this link to web browser:\n", url + '\n', "If you have installed Microsoft Silverlight in " "Internet Explorer as default browser, " "just click \"Open\" button to open it in PMKS website.")) reply = QMessageBox.information( self, "PMKS web server", text, (QMessageBox.Save | QMessageBox.Open | QMessageBox.Close), QMessageBox.Save) if reply == QMessageBox.Open: _open_url(url) elif reply == QMessageBox.Save: QApplication.clipboard().setText(url)
def on_record_start_toggled(self, toggled): """Save to file path data.""" if toggled: self.MainCanvas.recordStart(int(360 / self.record_interval.value())) return path = self.MainCanvas.getRecordPath() name, ok = QInputDialog.getText(self, "Recording completed!", "Please input name tag:") if (not name) or (name in self.pathData): i = 0 while "Record_{}".format(i) in self.pathData: i += 1 QMessageBox.information(self, "Record", "The name tag is being used or empty.") name = "Record_{}".format(i) self.addPath(name, path)
def __find_text(self, forward: bool): """Find text by options.""" if not self.search_bar.text(): self.search_bar.setText(self.search_bar.placeholderText()) pos = self.text_editor.positionFromLineIndex( *self.text_editor.getCursorPosition()) if not self.text_editor.findFirst( self.search_bar.text(), self.re_option.isChecked(), self.match_case_option.isChecked(), self.whole_word_option.isChecked(), self.wrap_around.isChecked(), forward, *self.text_editor.lineIndexFromPosition( pos if forward else pos - 1)): QMessageBox.information( self, "Text not found.", "\"{}\" is not in current document".format( self.search_bar.text()))
def on_action_Check_update_triggered(self): """Check for update.""" progdlg = QProgressDialog("Checking update ...", "Cancel", 0, 3, self) progdlg.setAttribute(Qt.WA_DeleteOnClose, True) progdlg.setWindowTitle("Check for update") progdlg.resize(400, progdlg.height()) progdlg.setModal(True) progdlg.show() url = check_update(progdlg) if not url: QMessageBox.information(self, "Pyslvs is up to date", "You are using the latest version of Pyslvs.") return reply = QMessageBox.question(self, "Pyslvs has update", "Do you want to get it from Github?", (QMessageBox.Ok | QMessageBox.Cancel), QMessageBox.Ok) if reply == QMessageBox.Ok: _openURL(url)
def __start_record(self, toggled: bool): """Save to file path data.""" if toggled: self.MainCanvas.record_start(int( self.dial_spinbox.maximum() / self.record_interval.value() )) return path = self.MainCanvas.get_record_path() name, ok = QInputDialog.getText( self, "Recording completed!", "Please input name tag:" ) i = 0 name = name or f"Record_{i}" while name in self.__path_data: name = f"Record_{i}" i += 1 QMessageBox.information( self, "Record", "The name tag is being used or empty." ) self.add_path(name, path)
def __edges2atlas(self): """Turn the text files into a atlas image. This operation will load all edges to list widget first. """ file_names = self.inputFrom("Edges data", ["Text file (*.txt)"], multiple=True) if not file_names: return read_data = [] for file_name in file_names: with open(file_name) as f: for line in f: read_data.append(line) answer = [] for edges in read_data: try: g = Graph(eval(edges)) except (SyntaxError, TypeError): QMessageBox.warning(self, "Wrong format", "Please check text format.") else: answer.append(g) if not answer: QMessageBox.information(self, "No data", "The graph data is empty.") return self.answer = answer self.__reload_atlas() self.save_edges_auto.setChecked(False) self.__save_atlas() self.save_edges_auto.setChecked(self.save_edges_auto.isChecked())
def __check_update(self): """Check for update.""" progress_dlg = QProgressDialog("Checking update ...", "Cancel", 0, 3, self) progress_dlg.setAttribute(Qt.WA_DeleteOnClose) progress_dlg.setWindowTitle("Check for update") progress_dlg.resize(400, progress_dlg.height()) progress_dlg.setModal(True) progress_dlg.show() url = check_update(progress_dlg) progress_dlg.deleteLater() if not url: QMessageBox.information( self, "Pyslvs is up to date", "You are using the latest version of Pyslvs." ) return if QMessageBox.question( self, "Pyslvs has update", "Do you want to get it from Github?" ) == QMessageBox.Yes: self.__open_url(url)
def on_generate_button_clicked(self): """Start synthesis.""" #Check if the number of target points are same. leng = -1 for path in self.path.values(): if leng<0: leng = len(path) if len(path)!=leng: QMessageBox.warning(self, "Target Error", "The length of target paths should be the same." ) return #Get the algorithm type. if self.type0.isChecked(): type_num = AlgorithmType.RGA elif self.type1.isChecked(): type_num = AlgorithmType.Firefly elif self.type2.isChecked(): type_num = AlgorithmType.DE #Deep copy it so the pointer will not the same. mechanismParams = deepcopy(self.mechanismParams) mechanismParams['Target'] = deepcopy(self.path) for key in ('Driver', 'Follower'): for name in mechanismParams[key]: row = name_in_table(self.ground_joints, name) mechanismParams[key][name] = ( self.ground_joints.cellWidget(row, 2).value(), self.ground_joints.cellWidget(row, 3).value(), self.ground_joints.cellWidget(row, 4).value() ) for name in ['IMax', 'IMin', 'LMax', 'LMin', 'FMax', 'FMin', 'AMax', 'AMin']: mechanismParams[name] = self.Settings[name] setting = {'report': self.Settings['report']} if 'maxGen' in self.Settings: setting['maxGen'] = self.Settings['maxGen'] elif 'minFit' in self.Settings: setting['minFit'] = self.Settings['minFit'] elif 'maxTime' in self.Settings: setting['maxTime'] = self.Settings['maxTime'] setting.update(self.Settings['algorithmPrams']) #Start progress dialog. dlg = Progress_show( type_num, mechanismParams, setting, self ) dlg.show() if not dlg.exec_(): return for m in dlg.mechanisms: self.mechanism_data.append(m) self.add_result(m) self.setTime(dlg.time_spand) self.unsaveFunc() QMessageBox.information(self, "Dimensional Synthesis", "Your tasks is all completed.", QMessageBox.Ok ) print("Finished.")
def on_action_Output_to_Picture_clipboard_triggered(self): """Capture the canvas image to clipboard.""" QApplication.clipboard().setPixmap(self.MainCanvas.grab()) QMessageBox.information(self, "Captured!", "Canvas widget picture is copy to clipboard.")