diff --git a/pymead/gui/dockable_tab_widget.py b/pymead/gui/dockable_tab_widget.py index 78c34c28..90e863bf 100644 --- a/pymead/gui/dockable_tab_widget.py +++ b/pymead/gui/dockable_tab_widget.py @@ -55,6 +55,9 @@ def add_new_tab_widget(self, widget, name): self.setCentralWidget(dw) def on_tab_closed(self, name: str, event: QCloseEvent): + if name == "Geometry": + event.ignore() + return idx = self.names.index(name) self.names.pop(idx) self.dock_widgets.pop(idx) diff --git a/pymead/gui/gui.py b/pymead/gui/gui.py index 34d83286..3b3bc751 100644 --- a/pymead/gui/gui.py +++ b/pymead/gui/gui.py @@ -91,6 +91,9 @@ def __init__(self, path=None, parent=None): # super().__init__(flags=Qt.FramelessWindowHint) super().__init__(parent=parent) # self.setWindowFlags(Qt.CustomizeWindowHint) + print(f"Running GUI with {os.getpid() = }") + self.pool = None + self.current_opt_folder = None self.menu_bar = None self.path = path # single_element_inviscid(np.array([[1, 0], [0, 0], [1, 0]]), 0.0) @@ -137,7 +140,7 @@ def __init__(self, path=None, parent=None): self.n_analyses = 0 self.n_converged_analyses = 0 self.threadpool = QThreadPool().globalInstance() - self.threadpool.setMaxThreadCount(2) + self.threadpool.setMaxThreadCount(4) self.pens = [('#d4251c', Qt.SolidLine), ('darkorange', Qt.SolidLine), ('gold', Qt.SolidLine), ('limegreen', Qt.SolidLine), ('cyan', Qt.SolidLine), ('mediumpurple', Qt.SolidLine), ('deeppink', Qt.SolidLine), ('#d4251c', Qt.DashLine), ('darkorange', Qt.DashLine), @@ -272,8 +275,6 @@ def closeEvent(self, a0) -> None: a0.ignore() break - # TODO: Make an "abort" button for optimization - def on_tab_closed(self, name: str, event: QCloseEvent): if name == "Geometry": event.ignore() # Do not allow user to close the geometry window @@ -282,12 +283,15 @@ def on_tab_closed(self, name: str, event: QCloseEvent): self.n_converged_analyses = 0 elif name == "Opt. Airfoil": self.opt_airfoil_graph = None + self.opt_airfoil_plot_handles = [] elif name == "Drag": self.drag_graph = None elif name == "Parallel Coordinates": self.parallel_coords_graph = None + self.parallel_coords_plot_handles = [] elif name == "Cp": self.Cp_graph = None + self.Cp_graph_plot_handles = [] @pyqtSlot(str) def setStatusBarText(self, message: str): @@ -702,10 +706,14 @@ def add_airfoil(self, airfoil: Airfoil): def disp_message_box(self, message: str, message_mode: str = 'error'): disp_message_box(message, self, message_mode=message_mode) - def output_area_text(self, text: str, mode: str = 'plain'): + def output_area_text(self, text: str, mode: str = 'plain', mono: bool = True): + prepend_html = f"
" \ + f"
" previous_cursor = self.text_area.textCursor() self.text_area.moveCursor(QTextCursor.End) if mode == 'plain': + if mode == "plain" and mono: + self.text_area.insertHtml(prepend_html) self.text_area.insertPlainText(text) elif mode == 'html': self.text_area.insertHtml(text) @@ -1202,6 +1210,7 @@ def optimization_accepted(self): opt_settings['Genetic Algorithm']['opt_dir_name']) param_dict['opt_dir'] = opt_dir + self.current_opt_folder = opt_dir.replace(os.sep, "/") name_base = 'ga_airfoil' name = [f"{name_base}_{i}" for i in range(opt_settings['Genetic Algorithm']['n_offspring'])] @@ -1219,6 +1228,8 @@ def optimization_accepted(self): if opt_settings['General Settings']['warm_start_active']: param_dict['warm_start_generation'] = calculate_warm_start_index( opt_settings['General Settings']['warm_start_generation'], opt_dir) + if param_dict['warm_start_generation'] == 0: + opt_settings['General Settings']['warm_start_active'] = False param_dict_save = deepcopy(param_dict) if not opt_settings['General Settings']['warm_start_active']: save_data(param_dict_save, os.path.join(opt_dir, 'param_dict.json')) @@ -1252,26 +1263,64 @@ def run_shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict self.worker.signals.result.connect(self.shape_opt_result_callback_fn) self.worker.signals.finished.connect(self.shape_opt_finished_callback_fn) self.worker.signals.error.connect(self.shape_opt_error_callback_fn) + self.worker.signals.message.connect(self.message_callback_fn) + self.worker.signals.text.connect(self.text_area_callback_fn) + self.worker.signals.pool.connect(self.set_pool) self.threadpool.start(self.worker) + def stop_optimization(self): + if self.pool is not None: + self.pool.terminate() + self.output_area_text("Optimization terminated. ") + self.output_area_text(self.generate_output_folder_link_text(self.current_opt_folder), mode="html") + self.pool = None + self.current_opt_folder = None + + @staticmethod + def generate_output_folder_link_text(folder: str): + return f"Open output folder\n" + + def set_pool(self, pool_obj: object): + print(f"Setting pool! {pool_obj = }") + self.pool = pool_obj + @staticmethod def shape_opt_progress_callback_fn(progress_object: object): if isinstance(progress_object, OptCallback): progress_object.exec_callback() def shape_opt_finished_callback_fn(self): - self.output_area_text("Completed aerodynamic shape optimization.\n\n") + self.forces_dict = {} + self.pool = None + self.status_bar.showMessage("Optimization Complete!", 3000) + self.output_area_text("Completed aerodynamic shape optimization. ") + self.output_area_text(self.generate_output_folder_link_text(self.current_opt_folder), mode="html") + self.output_area_text("\n\n") + self.current_opt_folder = None + self.status_bar.showMessage("") # self.finished_optimization = True def shape_opt_result_callback_fn(self, result_object: object): pass + def message_callback_fn(self, message: str): + self.status_bar.showMessage(message) + + def text_area_callback_fn(self, message: str): + self.output_area_text(message) + def shape_opt_error_callback_fn(self, error_tuple: tuple): self.output_area_text(f"Error. Error = {error_tuple}\n") - def shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict, progress_callback): - self.output_area_text(f"\nBeginning aerodynamic shape optimization with " - f"{param_dict['num_processors']} processors...\n") + def shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict, + progress_callback): + def start_message(warm_start: bool): + first_word = "Resuming" if warm_start else "Beginning" + return f"\n{first_word} aerodynamic shape optimization with {param_dict['num_processors']} processors...\n" + + self.worker.signals.text.emit(start_message(opt_settings["General Settings"]["warm_start_active"])) + Config.show_compile_hint = False forces = [] ref_dirs = get_reference_directions("energy", param_dict['n_obj'], param_dict['n_ref_dirs'], @@ -1279,6 +1328,8 @@ def shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict, pr mea_object = MEA.generate_from_param_dict(mea) parameter_list, _ = mea_object.extract_parameters() num_parameters = len(parameter_list) + self.worker.signals.text.emit(f"Number of active and unlinked design variables: {num_parameters}\n") + # self.output_area_text(f"Number of active and unlinked design variables: {num_parameters}\n") problem = TPAIOPT(n_var=param_dict['n_var'], n_obj=param_dict['n_obj'], n_constr=param_dict['n_constr'], xl=param_dict['xl'], xu=param_dict['xu'], param_dict=param_dict) @@ -1296,7 +1347,7 @@ def shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict, pr population = Population(param_dict=param_dict, generation=0, parents=parents, mea=mea, verbose=param_dict['verbose']) - population.eval_pop_fitness() + population.eval_pop_fitness(sig=self.worker.signals.message, pool_sig=self.worker.signals.pool) print(f"Finished evaluating population fitness. Continuing...") new_X = None @@ -1330,7 +1381,7 @@ def shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict, pr G = np.row_stack((G, np.array([ constraint.value for constraint in self.constraints]))) - print(f"{J = }, {self.objectives = }") + # print(f"{J = }, {self.objectives = }") if new_X.ndim == 1: new_X = np.array([new_X]) @@ -1423,7 +1474,7 @@ def shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict, pr genes=individual) for idx, individual in enumerate(X)] population = Population(problem.param_dict, generation=n_generation, parents=parents, verbose=param_dict['verbose'], mea=mea) - population.eval_pop_fitness() + population.eval_pop_fitness(sig=self.worker.signals.message, pool_sig=self.worker.signals.pool) for chromosome in population.converged_chromosomes: forces.append(chromosome.forces) @@ -1449,7 +1500,7 @@ def shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict, pr G = np.row_stack((G, np.array([ constraint.value for constraint in self.constraints]))) - print(f"{J = }, {self.objectives = }") + # print(f"{J = }, {self.objectives = }") algorithm.evaluator.n_eval += param_dict['num_processors'] @@ -1490,8 +1541,12 @@ def shape_optimization(self, param_dict: dict, opt_settings: dict, mea: dict, pr # print(f"{algorithm.opt.get('F') = }") + warm_start_gen = None + if opt_settings["General Settings"]["warm_start_active"]: + warm_start_gen = param_dict["warm_start_generation"] + progress_callback.emit(TextCallback(parent=self, text_list=algorithm.display.progress_dict, - completed=not algorithm.has_next())) + completed=not algorithm.has_next(), warm_start_gen=warm_start_gen)) if len(self.objectives) == 1: if n_generation > 1: diff --git a/pymead/gui/gui_settings/buttons.json b/pymead/gui/gui_settings/buttons.json index dd76ae87..4feb1fcc 100644 --- a/pymead/gui/gui_settings/buttons.json +++ b/pymead/gui/gui_settings/buttons.json @@ -38,6 +38,13 @@ "checked-by-default": false, "function": "on_pos_constraint_pressed" }, + "stop-optimization": { + "icon": "stop.png", + "status_tip": "Terminate optimization", + "checkable": false, + "checked-by-default": false, + "function": "on_stop_button_pressed" + }, "template": { "icon": "picture.png", "status_tip": "A helpful hint", diff --git a/pymead/gui/main_icon_toolbar.py b/pymead/gui/main_icon_toolbar.py index d9293dab..28edf595 100644 --- a/pymead/gui/main_icon_toolbar.py +++ b/pymead/gui/main_icon_toolbar.py @@ -53,6 +53,10 @@ def add_all_buttons(self): button.toggle() self.addWidget(button) + def on_stop_button_pressed(self): + if hasattr(self.parent, "pool") and self.parent.pool is not None: + self.parent.stop_optimization() + def on_grid_button_pressed(self): # import pyqtgraph as pg if hasattr(self.parent.dockable_tab_window, "current_dock_widget"): diff --git a/pymead/gui/text_area.py b/pymead/gui/text_area.py index be754894..6821fe9f 100644 --- a/pymead/gui/text_area.py +++ b/pymead/gui/text_area.py @@ -1,8 +1,8 @@ -from PyQt5.QtWidgets import QTextEdit +from PyQt5.QtWidgets import QTextEdit, QTextBrowser from PyQt5.QtGui import QTextCursor, QColor, QFontDatabase -class ConsoleTextArea(QTextEdit): +class ConsoleTextArea(QTextBrowser): def __init__(self, parent=None): super().__init__(parent) self.setReadOnly(True) @@ -16,3 +16,5 @@ def __init__(self, parent=None): self.moveCursor(QTextCursor.End) # self.setTextColor(QColor("#13294B")) self.setFixedHeight(200) + self.setOpenLinks(True) + self.setOpenExternalLinks(True) diff --git a/pymead/gui/worker.py b/pymead/gui/worker.py index ea424bad..33bfda57 100644 --- a/pymead/gui/worker.py +++ b/pymead/gui/worker.py @@ -1,4 +1,5 @@ from PyQt5.QtCore import QObject, QRunnable, pyqtSignal, pyqtSlot +from multiprocessing.pool import Pool import traceback import sys @@ -11,6 +12,9 @@ class WorkerSignals(QObject): error = pyqtSignal(tuple) result = pyqtSignal(object) progress = pyqtSignal(object) + message = pyqtSignal(str) + text = pyqtSignal(str) + pool = pyqtSignal(object) class Worker(QRunnable): diff --git a/pymead/icons/stop.png b/pymead/icons/stop.png new file mode 100644 index 00000000..0d15abdc Binary files /dev/null and b/pymead/icons/stop.png differ diff --git a/pymead/optimization/opt_callback.py b/pymead/optimization/opt_callback.py index ed4ad8a8..94d2f05a 100644 --- a/pymead/optimization/opt_callback.py +++ b/pymead/optimization/opt_callback.py @@ -22,7 +22,8 @@ def exec_callback(self): class TextCallback(OptCallback): - def __init__(self, parent, text_list: typing.List[list], completed: bool = False): + def __init__(self, parent, text_list: typing.List[list], completed: bool = False, + warm_start_gen: int or None = None): super().__init__(parent=parent) self.parent = parent self.text_list = text_list @@ -30,6 +31,7 @@ def __init__(self, parent, text_list: typing.List[list], completed: bool = False self.widths = [attr[2] for attr in self.text_list] self.values = [attr[1] for attr in self.text_list] self.completed = completed + self.warm_start_gen = warm_start_gen def generate_header(self): t = "" @@ -52,7 +54,7 @@ def stringify_text_list(self): t += f"{v.center(w + 2)}|" if idx == len(self.widths) - 1: t += "|" - print(f"Row length = {len(t)}") + # print(f"Row length = {len(t)}") return t @staticmethod @@ -60,7 +62,7 @@ def generate_closer(length: int): return "="*length def exec_callback(self): - if self.values[0] == 1: + if self.values[0] == 1 or (self.warm_start_gen is not None and self.values[0] == self.warm_start_gen + 1): # font = self.parent.text_area.font() # print(QFontDatabase().families()) # # font.setFamily("DejaVu Sans Mono") @@ -159,7 +161,6 @@ def __init__(self, parent, background_color: str = 'w', design_idx: int = 0): self.Cd = self.forces['Cd'] self.Cdp = self.forces['Cdp'] self.Cdf = self.forces['Cdf'] - print(f"{self.Cd = }") self.design_idx = design_idx def exec_callback(self): diff --git a/pymead/optimization/opt_setup.py b/pymead/optimization/opt_setup.py index 49f95058..5b9522e0 100644 --- a/pymead/optimization/opt_setup.py +++ b/pymead/optimization/opt_setup.py @@ -128,7 +128,11 @@ def calculate_warm_start_index(warm_start_generation: int, warm_start_directory: if warm_start_generation not in generations and warm_start_generation != -1: raise ValueError(f'Invalid warm start generation. A value of {warm_start_generation} was input, and the valid ' f'generations in the directory are {generations}') - warm_start_index = generations[warm_start_generation] + if len(generations) > 0: + warm_start_index = generations[warm_start_generation] + else: + warm_start_index = 0 + return warm_start_index diff --git a/pymead/optimization/pop_chrom.py b/pymead/optimization/pop_chrom.py index 740a2555..0dbfd5ae 100644 --- a/pymead/optimization/pop_chrom.py +++ b/pymead/optimization/pop_chrom.py @@ -1,3 +1,4 @@ +import os import typing from multiprocessing import Pool from copy import deepcopy @@ -86,7 +87,7 @@ def generate(self): Chromosome generation flow :return: """ - print(f"Generating {self.population_idx} from param_dict...") + print(f"Generating {self.population_idx} with {os.getpid() = } from param_dict...") self.mea_object = MEA.generate_from_param_dict(self.mea) if self.verbose: print(f'Generating chromosome idx = {self.population_idx}, gen = {self.generation}') @@ -139,6 +140,8 @@ def generate_airfoil_sys_from_genes(self) -> dict: return self.param_set def update_param_dict(self): + if self.param_set["tool"] != "MSES": + return dben = benedict(self.mea_object.param_dict) for idx, from_geometry in enumerate(self.param_set['mses_settings']['from_geometry']): for k, v in from_geometry.items(): @@ -437,33 +440,49 @@ def generate_chromosomes_parallel(self): self.population = [chromosome if c.population_idx == chromosome.population_idx else c for c in self.population] - def eval_pop_fitness(self): + def eval_pop_fitness(self, sig=None, pool_sig=None): """ Evaluates the fitness of the population using parallel processing """ - print("Evaluating chromosomes in parallel using multiprocessing.Pool.map_async()...") + # print("Evaluating chromosomes in parallel using multiprocessing.Pool.map_async()...") with Pool(processes=self.param_set['num_processors']) as pool: - result = pool.imap(self.eval_chromosome_fitness, self.population) + pool_sig.emit(pool) + result = pool.imap_unordered(self.eval_chromosome_fitness, self.population) if self.verbose: print(f'result = {result}') - print(f"{pool = }") + # print(f"{pool = }") for chromosome in result: if chromosome.fitness is not None: self.converged_chromosomes.append(chromosome) n_converged_chromosomes = len(self.converged_chromosomes) - print(f"{n_converged_chromosomes = }") + + gen = 1 if self.generation == 0 else self.generation + status_bar_message = f"Generation {gen}/{self.param_set['n_max_gen']}: Converged " \ + f"{n_converged_chromosomes}/{self.param_set['population_size']} chromosomes\n" + + if sig is not None: + sig.emit(status_bar_message) + else: + print(status_bar_message) + + # if self.conn is not None: + # self.conn.send(status_bar_message) + if n_converged_chromosomes >= self.param_set["population_size"]: - # if n_converged_chromosomes >= 2: - print(f"Converged enough chromosomes (at least population_size = {self.param_set['population_size']}." - f"Closing pool. {len(self.converged_chromosomes) = }") + # print(f"Converged enough chromosomes (at least population_size = {self.param_set['population_size']}. " + # f"Closing pool. {len(self.converged_chromosomes) = }") break - else: - print(f"Haven't yet converged enough chromosomes. {len(self.converged_chromosomes) = }.") + # else: + # print(f"Haven't yet converged enough chromosomes. {len(self.converged_chromosomes) = }.") for chromosome in self.converged_chromosomes: - print(f"Chromosome index {chromosome.population_idx} is converged. Setting it to the population") + # print(f"{chromosome.population_idx = }") + # print(f"Chromosome index {chromosome.population_idx} is converged. Setting it to the population") + + # Re-write the population such that the order of the results from the multiprocessing.Pool does not + # matter self.population = [chromosome if c.population_idx == chromosome.population_idx else c for c in self.population] - print("Done writing converged chromosomes to the population.") + # print("Done writing converged chromosomes to the population.") def all_chromosomes_fitness_converged(self): for chromosome in self.population: diff --git a/pymead/resources/cascadia-code/Cascadia.ttf b/pymead/resources/cascadia-code/Cascadia.ttf deleted file mode 100644 index 7f248125..00000000 Binary files a/pymead/resources/cascadia-code/Cascadia.ttf and /dev/null differ diff --git a/pymead/resources/cascadia-code/SIL Open Font License.txt b/pymead/resources/cascadia-code/SIL Open Font License.txt deleted file mode 100644 index 29bc7d45..00000000 --- a/pymead/resources/cascadia-code/SIL Open Font License.txt +++ /dev/null @@ -1,44 +0,0 @@ -Copyright (c) 2019 - Present, Microsoft Corporation, -with Reserved Font Name Cascadia Code. - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. - -The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the copyright statement(s). - -"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. - -"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. - -5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/pymead/version.py b/pymead/version.py index f07c9dd0..01b7c8a7 100644 --- a/pymead/version.py +++ b/pymead/version.py @@ -1 +1 @@ -__version__ = '2.0.0-alpha.9' +__version__ = '2.0.0-alpha.10'