def start_gravity(self): """ Запустить расчёт взаимодействия вершин """ if self.gravity_timer \ or not SupremeSettings()['graphmodule_gravity_enabled']: return self.gravity_timer = QTimer(self.widget) self.gravity_timer.start( SupremeSettings()['graphmodule_timer_interval']) self.gravity_timer.timeout.connect(self._process_gravity)
class App: class SetupThread(LoadingThread): def __init__(self, parent=None): super().__init__(parent) self.operation = 'Установка языковых пакетов' def run(self): do_setup() self.loadingDone.emit() def __init__(self): super().__init__() self.app = QApplication(sys.argv) self.settings = SupremeSettings() self.settings.check_settings() logging.config.dictConfig(Config.LOGGING_CONFIG) self.log = logging.getLogger('root') self.tempdir = tempfile.TemporaryDirectory() self.log.debug(f'Temporary Directory is {self.tempdir}') self.settings['tempdir'] = self.tempdir.name self.window = None self.login = None self.log.debug(f'Main thread {QThread.currentThread()}') def start(self): if self.settings['setup']: self.thread = self.SetupThread() self.loading = LoadingWrapper(self.thread) self.loading.loadingDone.connect(self.show_login) self.loading.start() else: self.show_login() exit_code = self.app.exec_() sys.exit(exit_code) def show_login(self): if self.window: self.window.close() self.login = LoginWindow() self.login.loginSuccesful.connect(self.show_main_window) self.login.show() def show_main_window(self): self.window = MainWindow() self.window.actionChangeDB.triggered.connect(self.show_login) self.window.show() def on_exception_caught(self, type_, value, traceback): self.exception = ExceptionDialog(type_, value, traceback) self.exception.show()
def __init__(self): super().__init__() self.app = QApplication(sys.argv) self.settings = SupremeSettings() self.settings.check_settings() logging.config.dictConfig(Config.LOGGING_CONFIG) self.log = logging.getLogger('root') self.tempdir = tempfile.TemporaryDirectory() self.log.debug(f'Temporary Directory is {self.tempdir}') self.settings['tempdir'] = self.tempdir.name self.window = None self.login = None self.log.debug(f'Main thread {QThread.currentThread()}')
def test_global(self): settings = {'a': 'kek', 'b': 'foo', 'c': 12345} for key, value in settings.items(): self.supremeSettingsClass[key] = value for key, value in settings.items(): self.assertEqual(SupremeSettings()[key], value)
def relayout_graph(self, name: str): """Расположить вершины графа по какому-то алгоритму. Алгоритмы: * circular - по кругу * kamada_kawai - Kamada-Kawai Algorithm * planar - без пересечений ребер * random - рандом * shell - пока то же, что circular * spring - Fruchterman-Reingold Algorithm :param name: :type name: str """ def kamada_kawai(G): return nx.kamada_kawai_layout(G, weight=1) # def spectral(G): # return nx.spectral_layout(G, scale=20) func_dict = { 'circular': nx.circular_layout, 'kamada_kawai': kamada_kawai, 'planar': nx.planar_layout, 'random': nx.random_layout, 'shell': nx.shell_layout, # TODO 'spring': nx.spring_layout, # 'spectral': spectral } scale_dict = { 'circular': 0.5, 'random': 0.3 } self.calculate_matrix() matrix = np.array(self.matrix) G = nx.from_numpy_matrix(matrix) # Получить networkx-граф из матрицы try: pos = func_dict[name](G) except nx.exception.NetworkXException: self.box = QMessageBox.critical(self.widget, 'Ошибка', 'Граф не планарен') return # Расчехлить позиции pos = np.array([pos[i] for i in range(len(pos))]) # Масштабировать scale = SupremeSettings()['graphmodule_graph_scale'] try: pos = nx.rescale_layout(pos, scale=scale * scale_dict[name]) except KeyError: pos = nx.rescale_layout(pos, scale=scale) # Применить позиции for index, position in enumerate(pos): x, y = position node = self._nodes[self.head[index]] if node != self.widget.scene().mouseGrabberItem(): node.setX(x) node.setY(y) self._adjust_scene()
def __init__(self, graph_widget, label=None, info=None, color=QColor(Qt.yellow), id=0): """Создание вершины :param graph_widget: объект класса GraphWidget :param label: Надпись на вершине :param info: HTML-текст, который будет открываться при ПКМ :param color: Цвет """ super(Node, self).__init__() self.graph = graph_widget self.label = label self.info = info self.size_value = SupremeSettings()['vertex_size_value'] self.id = id self.size = QRect(-self.size_value, -self.size_value, self.size_value * 2, self.size_value * 2) self.setFlag(self.ItemIsMovable) self.setFlag(self.ItemSendsGeometryChanges) self.setAcceptHoverEvents(True) self.setZValue(1) self.color = color self.edge_list = []
def __init__(self, processor: TextProcessor, algorithm=None, parent=None): super().__init__(parent) self.setupUi(self) self.graph = GraphModule(self) self.graph.get_relation_text = self._describe_relation self.graphWidgetLayout.addWidget(self.graph.widget) self.processor = processor self.setupAlgorithms(algorithm) self.describer = Describer(self.algorithm, processor) self.populateGraph() self.actionSaveGraph.triggered.connect(self.saveGraph) self.excludeZerosCheckBox.stateChanged.connect( self.updateGraph) self.thresholdSlider.valueChanged.connect( self.updateGraph) self.algorithmComboBox.currentIndexChanged.connect(self.updateGraph) self.relayoutButton.clicked.connect( lambda: self.graph.relayout_graph( self.layoutComboBox.currentText())) self.gravityCheckBox.stateChanged.connect(self.toggle_gravity) self.gravityCheckBox.setChecked( SupremeSettings()['graphmodule_gravity_enabled']) self.graph.start_gravity()
def run(self): min_intersection = SupremeSettings()['processor_min_intersection'] log.info('Started processing') if self.analyze: accs = [None for _ in range(len(self.proc.algorithms))] self.accs = accs for i in range(len(self.proc.analyzer)): node1 = self.proc.analyzer[i] self.stats = self.proc._get_stats(node1, self.stats) for index, algorithm in enumerate(self.proc.algorithms): if self.analyze: accs[index] = algorithm.analyze( node1.alg_results, accs[index]) for j in range(i + 1, len(self.proc.analyzer)): node2 = self.proc.analyzer[j] result = algorithm.compare(node1.alg_results, node2.alg_results) if result["intersection"] > min_intersection: node1.link.connect( node2, { "algorithm_name": algorithm.name, "intersection": result["intersection"], "data": result["data"] }) if self.analyze: accs[index] = algorithm.analyze_comparison( node1.alg_results, node2.alg_results, result, accs[index]) self.check_percent(i) if self.analyze: self.proc._upload_results(self.accs, self.stats) self.loadingDone.emit()
def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget=None): if not self.source or not self.dest: return line = QLineF(self.source_point, self.dest_point) if line.length() == 0.0: return color = self.get_color() width = SupremeSettings()['edge_width'] if option.state & QStyle.State_Sunken: color, width = Qt.red, 2 painter.setPen(QPen(Qt.black, 2, Qt.DashLine)) painter.drawPolygon(self.getSelectionPolygon()) elif option.state & QStyle.State_MouseOver: color, width = Qt.blue, 2 painter.setPen( QPen(color, width, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(line) angle = math.acos(line.dx() / line.length()) if line.dy() >= 0: angle = math.pi * 2 - angle if self.arrow_size > 0: dest_arrow_p1 = self.dest_point + QPointF( math.sin(angle - math.pi / 3) * self.arrow_size, math.cos(angle - math.pi / 3) * self.arrow_size) dest_arrow_p2 = self.dest_point + QPointF( math.sin(angle - math.pi + math.pi / 3) * self.arrow_size, math.cos(angle - math.pi + math.pi / 3) * self.arrow_size) painter.setBrush(color) painter.drawPolygon( QPolygonF([line.p2(), dest_arrow_p1, dest_arrow_p2])) self.draw_animated_objects()
def toggle_gravity(self, state): state = state != 0 SupremeSettings()['graphmodule_gravity_enabled'] = state if state is False: self.graph.stop_gravity() else: self.graph.start_gravity()
def __init__(self, algorithm: AbstractAlgorithm, processor, parent=None): super().__init__(parent) self.setupUi(self) self.settings = SupremeSettings() self.textBrowser = TextBrowser(self) self.textBrowserLayout.addWidget(self.textBrowser) self.algorithm = algorithm self.processor = processor self.elementsLabel.setText(str(len(self.processor.analyzer)**2)) self.describer = Describer(algorithm, processor) self.plotter = Plotter(self.processor, self.algorithm) self.result_matrix = None self.hide_empty = False self.thresholdSlider.valueChanged.connect( self._on_threshold_slider_value_changed) self.hideEmptyCheckBox.stateChanged.connect( self._on_hide_empty_checkbox_state_changed) self.graphButton.clicked.connect(self._on_show_graph) self.splitter.setStretchFactor(0, 1) self.splitter.setStretchFactor(1, 2) self.exportButton.clicked.connect(self._on_export) self.updateButton.clicked.connect(self.update_results)
def __init__(self, parent=None): super().__init__(parent) self.setupUi(self) self.textBrowser = TextBrowser(self) self.textBrowserLayout.addWidget(self.textBrowser) self.settings = SupremeSettings() self.actionCloseProject.triggered.connect(self.remove_project) self.actionNew.triggered.connect(self.set_new_project) self.actionChangeFragments.triggered.connect(self.edit_fragments) self.actionClear.triggered.connect(self.clear_results) self.actionStartProcess.triggered.connect(self.start_algorithm) self.actionUpdateResults.triggered.connect(self.update_results) self.actionOpenParams.triggered.connect(self.open_settings) self.actionClearDB.triggered.connect(self.clear_db) self.actionOpen.triggered.connect(self.on_import) self.actionSave.triggered.connect(self.on_export) self.actionReport.triggered.connect(self.on_report) self.en_project = [ # Включить, когда есть проект self.actionCloseProject, self.actionSave, self.actionChangeFragments, self.actionClear, self.actionReport ] self.en_algorithm_results = [ # Включить, когда есть результаты ] self.en_process_fragments = [ # Включить, когда загружены фрагменты self.actionStartProcess, self.actionClear, self.startProcessButton, self.actionUpdateResults ] self.processor = None # Обработчик текста self.fragments_list = None # Виджет с фрагментами self.tabs = [] # Вкладки с результатами алгоритмов self.auto_update = SupremeSettings()['result_auto_update'] self.remove_project()
def __init__(self, algorithm_classes=None): super().__init__() self.algorithms: List[AbstractAlgorithm] = [] # Включенные self.all_algorithms: List[AbstractAlgorithm] = [] # Все self.init_algorithm_classes = algorithm_classes self.analyzer = FragmentsAnalyzer() self.settings = SupremeSettings() self.accs = None self.stats = None self.analyzer.download_db() self._download_results() self.set_up_algorithms()
def __init__(self, processor, parent=None): super().__init__(parent) self.processor = processor self.settings = SupremeSettings() self._report_items = {} self._file_name = None self.setupUi(self) self.splitter.setStretchFactor(0, 1) self.splitter.setStretchFactor(1, 3) self.actionUpdate.triggered.connect(self._create_report) self.usedList.doubleClicked.connect( lambda i: self.usedList.takeItem(i.row())) self._setup_text_editor() self._setup_text_connections() self._init_report_items()
class SupremeSettingsTest(unittest.TestCase): supremeSettingsClass = SupremeSettings() startingSettings = {'size_value': 20, 'vertex_weight': 250, 'n': 100} @unittest.skip('?') def test_initialization(self): self.assertEqual(self.startingSettings, self.supremeSettingsClass.settings) def test_get_settings(self): keys = ['vertex_weight', 'size_value', 'n'] for key in keys: self.supremeSettingsClass[key] = self.startingSettings[key] self.assertEqual(self.startingSettings[key], self.supremeSettingsClass[key]) @unittest.skip('Not works for now') def test_set_settings(self): keys = ['page_count', 'war_and_peace'] values = [18, 'best'] for key, value in zip(keys, values): self.supremeSettingsClass[key] = value self.assertEqual(self.supremeSettingsClass[[key]], {key: value}) def test_global(self): settings = {'a': 'kek', 'b': 'foo', 'c': 12345} for key, value in settings.items(): self.supremeSettingsClass[key] = value for key, value in settings.items(): self.assertEqual(SupremeSettings()[key], value) def test_check(self): self.supremeSettingsClass.check_settings() self.supremeSettingsClass.settings_gui['kek'] = {'lol': 'musor'} self.assertRaises(KeyError, self.supremeSettingsClass.check_settings)
def __init__(self): self.dmp = dmp_module.diff_match_patch() self.settings = SupremeSettings()
def __init__(self, parent=None): settings = SupremeSettings() super().__init__(settings, settings.settings_gui, parent)
def setUpClass(cls): SupremeSettings()['dictionary_words_num'] = 10 cls.algorithm = DictionaryAlgorithm()
import setup_ from ui import SettingsDialog from PyQt5.QtWidgets import QApplication import sys from supremeSettings import SupremeSettings if __name__ == "__main__": app = QApplication(sys.argv) settings = SettingsDialog() settings.show() settings.accepted.connect(lambda: print(str(SupremeSettings()))) sys.exit(app.exec_())
def _auto_update_results(self): [item.setEnabled(True) for item in self.en_algorithm_results] self._make_global_description() if SupremeSettings()['result_auto_update']: [tab.update_results() for tab in self.tabs]