def evaluate_neighborhood_tabu(self, solution: Solution, mask_list1, value_list1, weight_list1, tabu_list) -> bool: solution_binary = "".join([str(item) for item in solution.item_list]) solution_number = int(solution_binary, 2) mask_list = deepcopy(mask_list1) mask_list.reverse() for mask in mask_list: # mask representa o movimento: quais bits serão flipados da solução if int(mask, 2) in tabu_list.keys(): continue # sem considerar aspiration masked_number = solution_number ^ int(mask, 2) masked_binary = bin(masked_number)[2:].zfill(solution.n) neighbor = [int(digit) for digit in masked_binary] neighbor_weight_list = [ a * b for a, b in zip(neighbor, weight_list1) ] if sum(neighbor_weight_list) <= solution.capacity: neighbor_value_list = [ a * b for a, b in zip(neighbor, value_list1) ] if sum(neighbor_value_list) > solution.value: solution.value = sum(neighbor_value_list) solution.weight = sum(neighbor_weight_list) solution.item_list = deepcopy(neighbor) return True return False
def random_neighbor(self, solution: Solution, distance: int, value_list1, weight_list1): mask_list1 = General.get_mask_list(solution.n, distance, climb=False) solution_binary = "".join([str(item) for item in solution.item_list]) solution_number = int(solution_binary, 2) mask_list = deepcopy(mask_list1) random.shuffle(mask_list) for mask in mask_list: masked_number = solution_number ^ int(mask, 2) masked_binary = bin(masked_number)[2:].zfill(solution.n) neighbor = [int(digit) for digit in masked_binary] neighbor_weight_list = [ a * b for a, b in zip(neighbor, weight_list1) ] if sum(neighbor_weight_list) <= solution.capacity: neighbor_value_list = [ a * b for a, b in zip(neighbor, value_list1) ] solution.value = sum(neighbor_value_list) solution.weight = sum(neighbor_weight_list) solution.item_list = deepcopy(neighbor) return solution return None
def evaluate_neighborhood(self, solution: Solution, mask_list1, value_list1, weight_list1) -> bool: solution_binary = "".join([str(item) for item in solution.item_list]) solution_number = int(solution_binary, 2) mask_list = deepcopy(mask_list1) mask_list.reverse() for mask in mask_list: masked_number = solution_number ^ int(mask, 2) masked_binary = bin(masked_number)[2:].zfill(solution.n) neighbor = [int(digit) for digit in masked_binary] neighbor_weight_list = [ a * b for a, b in zip(neighbor, weight_list1) ] if sum(neighbor_weight_list) <= solution.capacity: neighbor_value_list = [ a * b for a, b in zip(neighbor, value_list1) ] if sum(neighbor_value_list) > solution.value: solution.value = sum(neighbor_value_list) solution.weight = sum(neighbor_weight_list) solution.item_list = deepcopy(neighbor) return True return False
def __init__(self, name, config_src, job_id ): Solution.__init__(self,name=name) self.config_src = config_src self.config_params = [] self.sampling = "lin" self.kill_timeout = 10 #seconds self.job_id = job_id self.sobol = None
def get(self, project_id, solution_id): project = Project.find_project_with_id(project_id) user_id = get_jwt_identity() if not project or not project.belongs_to_user(user_id): return self.project_does_not_exist_response() solution = Solution.find_solution_with_id(project.type, solution_id) if not solution or not solution.if_belongs_to(project.id): return self.solution_does_not_exist_response() analytics = Analytics(solution) status = analytics.get_status() main_stats, secondary_stats = status["main_status"], status["secondary_status"] parameters = status["hyperparameters"] if not solution.analytics_filled(): if analytics.solution_has_completed(main_stats): solution.update_analytics(analytics.get_solution_metrics()) return { "type": project.type, "status": main_stats, "secondary_status": secondary_stats, "parameters": parameters, "solution": solution.json() }
def simulated_annealing(optimum_value: float, instance_dict: dict, output_filename: str): config = settings.EVALUATE_METHODS_SETTINGS max_iterations = config.get('sa', {}).get('max_iterations') distance = config.get('sa', {}).get('distance') initial_temperature = config.get('sa', {}).get('initial_temperature') best_solution = Solution( n=instance_dict.get('n'), capacity=instance_dict.get('capacity'), optimum=optimum_value ) best_solution.generate_starter_solution( item_list=instance_dict.get('item_list'), random_seed=RANDOM_SEED ) best_solution.print_solution() sa = SimulatedAnnealing( solution=deepcopy(best_solution), item_list=instance_dict.get('item_list'), distance=2, output_filename=f"{output_filename}_temp" ) current_solution = deepcopy(sa.solution) writer = FileWriter(file_name=f"{output_filename}_temp") for i in range(max_iterations): if i == 0: writer.write_line(output_filename.replace('TEMP-', '')) writer.write_line(str(current_solution.optimum)) writer.write_line(f"{i} {current_solution.value}") sa.solution = deepcopy(current_solution) # random neighbor test = sa.random_neighbor(distance=distance) if not test: print(f"ERROR ! Could not find a random neighbor") # if better set as best_solution if sa.solution.value > best_solution.value: best_solution = deepcopy(sa.solution) writer.write_line(f"{i} {best_solution.value}") # calculate diff diff = current_solution.value - sa.solution.value # calculate temp t = initial_temperature / float(i + 1) if diff < 0 or random() < exp(-diff / t): current_solution = deepcopy(sa.solution) print(f"ic| SA Optimum Solution") best_solution.print_solution(item_list=instance_dict.get('item_list')) return best_solution
def get(self, project_id): project = Project.find_project_with_id(project_id) user_id = get_jwt_identity() if not project or not project.belongs_to_user(user_id): return self.project_does_not_exist_response() return { "solution_ids": Solution.find_solutions_of_projects(project.type, project.id) }
def post(self, project_id): project = Project.find_project_with_id(project_id) user_id = get_jwt_identity() if not project or not project.belongs_to_user(user_id): return self.project_does_not_exist_response() # Check if user have enough tokens user = UserModel.find_user_with_id(user_id); if user.tokens == 0: return self.not_enough_tokens() algorithm_name, hyperparameters = self.parse_arguments() if not ModelCreator.if_algorithm_belongs_to_problem_type(project.type, algorithm_name): return self.wrong_class_of_algorithm() project_data = Dataset.find_data_by_id(project.id) ml_model = ModelCreator.create_model( algorithm_name, data_path=project_data.get_data_path(), hyperparameters=hyperparameters ) ml_model.fit() training_job_name = ml_model.get_training_name() ml_database_model = Solution( training_job_name=training_job_name, algorithm_name=algorithm_name, project_id=project_id, type=project.type ) ml_database_model.save() # One model trained -> Decrease user tokens by 1 user.increase_tokens(-1); return { "solution": ml_database_model.json() }, 201
def vns(optimum_value: float, instance_dict: dict, output_filename: str) -> Solution: config = settings.EVALUATE_METHODS_SETTINGS max_iterations = config.get('vns', {}).get('max_iterations') neighborhood_size = config.get('vns', {}).get('neighborhood_size') solution = Solution( n=instance_dict.get('n'), capacity=instance_dict.get('capacity'), optimum=optimum_value ) solution.generate_starter_solution( item_list=instance_dict.get('item_list'), random_seed=RANDOM_SEED ) #solution.print_solution() vns_method = Vns( item_list=instance_dict.get('item_list'), neighborhood_size=neighborhood_size ) vns_method.run_vns( solution=solution, item_list=instance_dict.get('item_list'), max_iterations=max_iterations, neighborhood_size=neighborhood_size, output_filename=output_filename ) print(f"ic| VNS Optimum Solution") solution.print_solution(item_list=instance_dict.get('item_list')) return solution
def multi_start_local_search(optimum_value: float, instance_dict: dict, output_filename: str) -> Solution: config = settings.EVALUATE_METHODS_SETTINGS max_iterations = config.get('msl', {}).get('max_iterations') best_solution = None counter = 0 msl = None for i in range(max_iterations): print(f"Iteration {i}") random_solution = Solution(n=instance_dict.get('n'), capacity=instance_dict.get('capacity'), optimum=optimum_value) random_solution.generate_starter_solution( item_list=instance_dict.get('item_list'), random_seed=(RANDOM_SEED + i)) #random_solution.print_solution() if i == 0: msl = MultiStartLocalSearch( solution=random_solution, item_list=instance_dict.get('item_list'), distance=2, output_filename=f"{output_filename}_temp") else: msl.solution = deepcopy(random_solution) msl.run(counter=counter) if best_solution is None or msl.solution.value > best_solution.value: counter += 1 msl.output_file.write_line(f"{counter} {msl.solution.value}") best_solution = deepcopy(msl.solution) print(f"ic| MSL Optimum Solution") best_solution.print_solution(item_list=instance_dict.get('item_list')) return best_solution
def nahrat_data_clicked(self, widget): file_chooser_dialog = gtk.FileChooserDialog( title="Zvolte soubor, ktery chcete otevrit", parent=None, buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL), ) # Vytvoreni a pridani filtru do filechooserdialogu def dialog_filtr(dialog, nazev, predloha): filtr = gtk.FileFilter() filtr.set_name(nazev) filtr.add_pattern(predloha) dialog.add_filter(filtr) dialog.set_filter(filtr) dialog_filtr(file_chooser_dialog, "Zdrojove kody v pythonu", "*.py") dialog_filtr(file_chooser_dialog, "Vsechny soubory", "*") dialog_filtr(file_chooser_dialog, "Textove soubory", "*.txt") # file_chooser_dialog.set_current_folder(solution) reakce_dialogu = file_chooser_dialog.run() nazev_souboru = file_chooser_dialog.get_filename() file_chooser_dialog.destroy() if reakce_dialogu == gtk.RESPONSE_OK: solution = Solution(name=nazev_souboru) solution.load() page = self.settings["notebook"].pridat_stranku_from_load(solution) page.settings["initdatapanel"].set_data(solution.get_init_data()) page.settings["matdatapanel"].set_data() page.settings["description"].nastav_init_data(solution.init_data.filepath) page.settings["description"].nastav_mat_data(solution.mat_data.filepath) page.settings["description"].nastav_opac_data(solution.opac_data) self.settings["notebook"].set_current_page(self.settings["notebook"].get_n_pages() - 1)
def assign_solutions(solutions): ''' Create list of Solution objs. Parameters: solutions : list of lists of str solutions_list : list of Solution objs. ''' solutions_list = [] for solution in solutions: new_solution = Solution.from_list(solution) solutions_list.append(new_solution) return solutions_list
def iterated_local_search(optimum_value: float, instance_dict: dict, output_filename: str) -> Solution: config = settings.EVALUATE_METHODS_SETTINGS max_iterations = config.get('ils', {}).get('max_iterations') best_solution = Solution(n=instance_dict.get('n'), capacity=instance_dict.get('capacity'), optimum=optimum_value) best_solution.generate_starter_solution( item_list=instance_dict.get('item_list'), random_seed=RANDOM_SEED) counter = 0 for i in range(max_iterations): perturbed_solution = deepcopy(best_solution) perturbed_solution.perturb_solution( item_list=instance_dict.get('item_list')) print(f"Iteration {i}") if i == 0: ils = IteratedLocalSearch( solution=perturbed_solution, item_list=instance_dict.get('item_list'), distance=2, output_filename=f"{output_filename}_temp") else: ils.solution = deepcopy(perturbed_solution) ils.run(counter) while not ils.check_acceptance_criteria(best_solution): ils.solution.perturb_solution( item_list=instance_dict.get('item_list')) ils.run(counter) if ils.solution.value > best_solution.value: counter += 1 best_solution = deepcopy(ils.solution) best_solution.print_solution() ils.output_file.write_line(f"{counter} {ils.solution.value}") print(f"ic| ILS Optimum Solution") best_solution.print_solution(item_list=instance_dict.get('item_list')) return best_solution
def __solve_lp__(self, __solver__=None): if self.current_iteration >= self.max_iterations: raise TimeoutError("Phase1 has reached the maximum number of {0} iterations".format(self.max_iterations)) # Trick to speed things up and avoid calculating A, and b over and over again if __solver__ is None: solver = SimplexSolver(linear_model=self.model, base_variables=self.base_indexes,non_base_variables=self.non_base_variables) else: solver = __solver__ # Who should join the base? relative_costs = [self.model.fo.coefficients[i] - np.dot(solver.simplex_multiplierT, solver.N[:, index]) for index, i in enumerate(solver.N_variables)] negative_relative_costs = [i for i in relative_costs if i < 0] variable_join_N_index = None if len(negative_relative_costs) > 0: variable_join_N_index = relative_costs.index(min(negative_relative_costs)) # Is my base optimal? if variable_join_N_index is None: self.solution = Solution(solver=solver) return # Who should I take out from base? simplex_direction = np.dot(solver.B_inv, solver.N[:, [variable_join_N_index]]) y = [i for i in simplex_direction] # Unlimited solutions check y_sanity_check = [i for i in simplex_direction if i > 0] if not y_sanity_check or len(y_sanity_check) <= 0: raise InterruptedError("The model is unbounded and has unlimited solutions") steps = [item / y[index] if y[index] != 0 else -1 for index, item in enumerate(solver.xb)] steps_excluding_negative = [i for i in steps if i >= 0] if len(steps_excluding_negative) <= 0: raise InterruptedError("Only negative steps...") min_step = min(steps_excluding_negative) variable_leave_B_index = steps.index(min_step) # Updating Base and Non Base variable_leave_B = solver.B_variables[variable_leave_B_index] variable_join_N = solver.N_variables[variable_join_N_index] solver.B_variables[variable_leave_B_index] = variable_join_N solver.N_variables[variable_join_N_index] = variable_leave_B self.current_iteration = self.current_iteration + 1 self.__solve_lp__(__solver__=solver)
def assign_assignments_to_new_student(): ''' Fallows adding student. Creates Solution objs. for all assignemts stored in system Paramaters: None Returns: None Updates: Solution, Assignment class data ''' for assignment in Assignment.list_of_assignments: assignment.solutions.append(Solution(0, '0', '0')) Assignment.save_assignments_to_file('assignments.csv')
def tabu_search(optimum_value: float, instance_dict: dict, output_filename: str): config = settings.EVALUATE_METHODS_SETTINGS max_iterations = config.get('tabu', {}).get('max_iterations') best_solution = Solution( n=instance_dict.get('n'), capacity=instance_dict.get('capacity'), optimum=optimum_value ) best_solution.generate_starter_solution( item_list=instance_dict.get('item_list'), random_seed=RANDOM_SEED ) best_solution.print_solution() tabu_list = {} tabu_tenure = config.get('tabu', {}).get('tenure') tabu_search = TabuSearch( solution=deepcopy(best_solution), item_list=instance_dict.get('item_list'), distance=2, output_filename=f"{output_filename}_temp" ) for _ in range(max_iterations): tabu_search.run(tabu_list=tabu_list) if tabu_search.solution.value > best_solution.value: best_solution = deepcopy(tabu_search.solution) # decrement tenure, removes if 0 for solution in tabu_list.copy(): tabu_list[solution] -= 1 if tabu_list[solution] == 0: del tabu_list[solution] # add new solution to list number = int(''.join([str(x) for x in tabu_search.solution.item_list]), 2) tabu_list[number] = tabu_tenure print(f"ic| Tabu Optimum Solution") best_solution.print_solution(item_list=instance_dict.get('item_list')) return best_solution
def get(self, project_id, solution_id): # Check if project belongs to correct user project = Project.find_project_with_id(project_id) user_id = get_jwt_identity() if not project or not project.belongs_to_user(user_id): return self.project_does_not_exist_response() # Check if solution belongs to project solution = Solution.find_solution_with_id(project.type, solution_id) if not solution or not solution.if_belongs_to(project.id): return self.solution_does_not_exist_response() # Get download link downloader = SolutionDownloader(solution) download_url = downloader.get_solution_url() # Return return { "url": download_url }, 201 # Created URL
def get_assignment_data(): ''' Gets valid data for all data necessery to create new Assignment obj. Parameters: None Returns: name : str add_date : str deadline : str max_grade : int solutions : str ''' add_date = get_today_date() name, deadline, max_grade = get_valid_inputs() deadline = format_date(deadline) solutions = [] for index in range(len(Student.list_of_students)): solutions.append(Solution(0, '0', '0')) return name, add_date, deadline, max_grade, solutions
def single_start_local_search(optimum_value: float, instance_dict: dict, output_filename: str) -> Solution: solution = Solution(n=instance_dict.get('n'), capacity=instance_dict.get('capacity'), optimum=optimum_value) solution.generate_starter_solution( item_list=instance_dict.get('item_list'), random_seed=RANDOM_SEED) #solution.print_solution() local_search = LocalSearch(solution=solution, item_list=instance_dict.get('item_list'), distance=2, output_filename=output_filename, improved=True) local_search.run() print(f"ic| SSL Optimum Solution") solution.print_solution(item_list=instance_dict.get('item_list')) return solution
def evaluate_neighborhood(self, solution: Solution, item_list: list, distance: int) -> bool: optimum_value = solution.value optimum_weight = solution.weight pos1 = -1 pos2 = -1 posd1 = -1 has_improved = False if distance == 1: for i in range(solution.n): if solution.item_list[i] == 0: aux_weight = solution.weight + item_list[i].weight aux_value = solution.value + item_list[i].value else: aux_weight = solution.weight - item_list[i].weight aux_value = solution.value - item_list[i].value if aux_weight <= solution.capacity and aux_value > optimum_value: pos1 = i optimum_value = aux_value optimum_weight = aux_weight if pos1 != -1: solution.item_list[pos1] = (solution.item_list[pos1] + 1) % 2 solution.value = optimum_value solution.weight = optimum_weight return True return False elif distance == 2: for i in range(solution.n): if solution.item_list[i] == 0: aux_weight = solution.weight + item_list[i].weight aux_value = solution.value + item_list[i].value else: aux_weight = solution.weight - item_list[i].weight aux_value = solution.value - item_list[i].value if aux_weight <= solution.capacity and aux_value > optimum_value: posd1 = i optimum_value = aux_value optimum_weight = aux_weight if posd1 != -1: has_improved = True for i in range(solution.n - 1): if solution.item_list[i] == 0: aux_weight = solution.weight + item_list[i].weight aux_value = solution.value + item_list[i].value else: aux_weight = solution.weight - item_list[i].weight aux_value = solution.value - item_list[i].value for j in range(i + 1, solution.n): if solution.item_list[j] == 0: aux_weight2 = aux_weight + item_list[j].weight aux_value2 = aux_value + item_list[j].value else: aux_weight2 = aux_weight - item_list[j].weight aux_value2 = aux_value - item_list[j].value if aux_weight2 <= solution.capacity and aux_value2 > optimum_value: pos1 = i pos2 = j optimum_value = aux_value2 optimum_weight = aux_weight2 if pos1 != -1: solution.item_list[pos1] = (solution.item_list[pos1] + 1) % 2 solution.item_list[pos2] = (solution.item_list[pos2] + 1) % 2 solution.value = optimum_value solution.weight = optimum_weight return True if has_improved: solution.item_list[posd1] = (solution.item_list[posd1] + 1) % 2 solution.value = optimum_value solution.weight = optimum_weight return True return False return False
def _find_calculated_solutions(self): database_solutions = Solution.find_by_n(self.n) if database_solutions: return True return False
def _save_solutions(self, solutions): for sol in solutions: s = Solution(self.n, str(sol).strip('[]')) s.save()
class AblatorPage(gtk.VBox): def __init__(self, parent_notebook, solution=None): gtk.VBox.__init__(self, False, 0) self.notebook = parent_notebook if solution == None: self.solution = Solution() else: self.solution = solution self.settings = {} self.settings["initdatapanel"] = AblatorInitdataPanel(self.solution, self.settings) self.settings["matdatapanel"] = AblatorMatdataPanel(self.solution, self.settings) self.settings["opacdatacesta"] = "" self.settings["solution"] = self.solution self.settings["description"] = AblatorSolutionDescription(self.settings) self.Init_tlacitko = gtk.Button("Init Data..") self.Init_tlacitko.connect("clicked", self.cteni_initdat_clicked) self.tlacitko_smazat_page = gtk.Button("Zavřít záložku", stock=gtk.STOCK_CLOSE) self.tlacitko_smazat_page.connect("clicked", self.smazat_page_clicked) self.Mat_tlacitko = gtk.Button("Mat Data..") self.Mat_tlacitko.connect("clicked", self.cteni_matdata_clicked) self.Opac_tlacitko = gtk.Button("Opac Data..") self.Opac_tlacitko.connect("clicked", self.cteni_opacdata_clicked) self.tlacitko_vypocet = gtk.Button("Vypocet", stock=gtk.STOCK_EXECUTE) self.tlacitko_vypocet.connect("clicked", self.spustit_vypocet_clicked) self.tlacitko_otevrit_slozku = gtk.Button("Otevřít složku s řešením") self.tlacitko_otevrit_slozku.connect("clicked", self.otevrit_slozku_clicked) self.tlacitko_ulozit_data = gtk.Button("Ulozit data..", stock=gtk.STOCK_SAVE) self.tlacitko_ulozit_data.connect("clicked", self.ulozit_data_clicked) self.combobox = gtk.combo_box_new_text() self.combobox.append_text("Ablator - 1.0") self.combobox.append_text("Ablator - 2.0") self.combobox.set_active(0) # spojeni tlacitek do hboxu self.hbox_zalozka_tlacitka = gtk.HBox() self.hbox_zalozka_tlacitka.pack_start(self.Init_tlacitko, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.Mat_tlacitko, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.Opac_tlacitko, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.tlacitko_otevrit_slozku, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.tlacitko_ulozit_data, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.tlacitko_smazat_page, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.tlacitko_vypocet, False, True, 0) # self.hbox_zalozka_tlacitka.pack_start(self.combobox, False, True,0) # spojeni initdata a matdata do hboxu self.hbox_initdata_matdata_opacdata = gtk.HBox() self.hbox_initdata_matdata_opacdata.pack_start(self.settings["initdatapanel"], True, True, 0) self.hbox_initdata_matdata_opacdata.pack_start(self.settings["matdatapanel"], True, True, 0) # self.hbox_initdata_matdata_opacdata.pack_start(self.settings["opacdatapanel"], True, True,0) self.pack_start(self.hbox_zalozka_tlacitka, False, False, 0) self.pack_start(self.hbox_initdata_matdata_opacdata, False, False, 0) self.pack_end(self.settings["description"], False, True, 0) def cteni_initdat_clicked(self, widget): file_chooser_dialog = gtk.FileChooserDialog( title="Zvolte soubor, který chcete otevřít", parent=None, buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL), ) # Vytvoreni a pridani filtru do filechooserdialogu def dialog_filtr(dialog, nazev, predloha): filtr = gtk.FileFilter() filtr.set_name(nazev) filtr.add_pattern(predloha) dialog.add_filter(filtr) dialog.set_filter(filtr) dialog_filtr(file_chooser_dialog, "Zdrojové kódy v pythonu", "*.py") dialog_filtr(file_chooser_dialog, "Textové soubory", "*.txt") dialog_filtr(file_chooser_dialog, "Všechny soubory", "*") # file_chooser_dialog.set_current_folder(data) reakce_dialogu = file_chooser_dialog.run() nazev_souboru = file_chooser_dialog.get_filename() file_chooser_dialog.destroy() if reakce_dialogu == gtk.RESPONSE_OK: # try: # self.init_data = InitData(nazev_souboru) self.solution.set_init_data(nazev_souboru) self.settings["description"].nastav_init_data(nazev_souboru) if self.solution.ablator_exe == "Ablator.exe": self.settings["initdatapanel"].set_data(self.solution.init_data) else: self.settings["initdatapanel"].set_data2(self.solution.init_data) self.solution.set_init_data(nazev_souboru) # except: # self.settings["description"].nastav_init_data("Nepovedlo se nacist initdata") def cteni_matdata_clicked(self, widget): file_chooser_dialog = gtk.FileChooserDialog( title="Zvolte soubor, který chcete otevřít", parent=None, buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL), ) # Vytvoreni a pridani filtru do filechooserdialogu def dialog_filtr(dialog, nazev, predloha): filtr = gtk.FileFilter() filtr.set_name(nazev) filtr.add_pattern(predloha) dialog.add_filter(filtr) dialog.set_filter(filtr) dialog_filtr(file_chooser_dialog, "Zdrojové kódy v pythonu", "*.py") dialog_filtr(file_chooser_dialog, "Textové soubory", "*.txt") dialog_filtr(file_chooser_dialog, "Všechny soubory", "*") # file_chooser_dialog.set_current_folder(data) reakce_dialogu = file_chooser_dialog.run() nazev_souboru = file_chooser_dialog.get_filename() file_chooser_dialog.destroy() if reakce_dialogu == gtk.RESPONSE_OK: # try: self.solution.set_mat_data(nazev_souboru) self.settings["description"].nastav_mat_data(nazev_souboru) self.settings["matdatapanel"].set_data() # except: # self.settings["description"].nastav_mat_data("Nepovedlo se nacist matdata") def cteni_opacdata_clicked(self, widget): file_chooser_dialog = gtk.FileChooserDialog( title="Zvolte soubor, ktery chcete otevrit", parent=None, buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL), ) # Vytvoreni a pridani filtru do filechooserdialogu def dialog_filtr(dialog, nazev, predloha): filtr = gtk.FileFilter() filtr.set_name(nazev) filtr.add_pattern(predloha) dialog.add_filter(filtr) dialog.set_filter(filtr) dialog_filtr(file_chooser_dialog, "Zdrojové kódy v pythonu", "*.py") dialog_filtr(file_chooser_dialog, "Textové soubory", "*.txt") dialog_filtr(file_chooser_dialog, "Všechny soubory", "*") # file_chooser_dialog.set_current_folder(data) reakce_dialogu = file_chooser_dialog.run() nazev_souboru = file_chooser_dialog.get_filename() file_chooser_dialog.destroy() if reakce_dialogu == gtk.RESPONSE_OK: # try: self.solution.set_opac_data(nazev_souboru) self.settings["description"].nastav_opac_data(nazev_souboru) # except: # self.settings["description"].nastav_opac_data("Nepovedlo se nacist opacdata") def spustit_vypocet_clicked(self, widget): # s = Solution("Kremik","data/initdata","data/matdata-Si","data/opacdata-PMMA","Ablator2.exe") # model = self.combobox.get_model() # active = self.combobox.get_active() # item = model[active][0] # if(item == "Ablator - 1.0"): # self.solution.set_ablator_exe("Ablator.exe") # else: # self.solution.set_ablator_exe("Ablator2.exe") try: self.solution.run() self.solution.open_folder() except Exception, e: md = gtk.MessageDialog( None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, "Nejdříve řešení uložte." ) md.run() md.destroy()
def __init__(self, parent_notebook, solution=None): gtk.VBox.__init__(self, False, 0) self.notebook = parent_notebook if solution == None: self.solution = Solution() else: self.solution = solution self.settings = {} self.settings["initdatapanel"] = AblatorInitdataPanel(self.solution, self.settings) self.settings["matdatapanel"] = AblatorMatdataPanel(self.solution, self.settings) self.settings["opacdatacesta"] = "" self.settings["solution"] = self.solution self.settings["description"] = AblatorSolutionDescription(self.settings) self.Init_tlacitko = gtk.Button("Init Data..") self.Init_tlacitko.connect("clicked", self.cteni_initdat_clicked) self.tlacitko_smazat_page = gtk.Button("Zavřít záložku", stock=gtk.STOCK_CLOSE) self.tlacitko_smazat_page.connect("clicked", self.smazat_page_clicked) self.Mat_tlacitko = gtk.Button("Mat Data..") self.Mat_tlacitko.connect("clicked", self.cteni_matdata_clicked) self.Opac_tlacitko = gtk.Button("Opac Data..") self.Opac_tlacitko.connect("clicked", self.cteni_opacdata_clicked) self.tlacitko_vypocet = gtk.Button("Vypocet", stock=gtk.STOCK_EXECUTE) self.tlacitko_vypocet.connect("clicked", self.spustit_vypocet_clicked) self.tlacitko_otevrit_slozku = gtk.Button("Otevřít složku s řešením") self.tlacitko_otevrit_slozku.connect("clicked", self.otevrit_slozku_clicked) self.tlacitko_ulozit_data = gtk.Button("Ulozit data..", stock=gtk.STOCK_SAVE) self.tlacitko_ulozit_data.connect("clicked", self.ulozit_data_clicked) self.combobox = gtk.combo_box_new_text() self.combobox.append_text("Ablator - 1.0") self.combobox.append_text("Ablator - 2.0") self.combobox.set_active(0) # spojeni tlacitek do hboxu self.hbox_zalozka_tlacitka = gtk.HBox() self.hbox_zalozka_tlacitka.pack_start(self.Init_tlacitko, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.Mat_tlacitko, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.Opac_tlacitko, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.tlacitko_otevrit_slozku, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.tlacitko_ulozit_data, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.tlacitko_smazat_page, False, True, 0) self.hbox_zalozka_tlacitka.pack_start(self.tlacitko_vypocet, False, True, 0) # self.hbox_zalozka_tlacitka.pack_start(self.combobox, False, True,0) # spojeni initdata a matdata do hboxu self.hbox_initdata_matdata_opacdata = gtk.HBox() self.hbox_initdata_matdata_opacdata.pack_start(self.settings["initdatapanel"], True, True, 0) self.hbox_initdata_matdata_opacdata.pack_start(self.settings["matdatapanel"], True, True, 0) # self.hbox_initdata_matdata_opacdata.pack_start(self.settings["opacdatapanel"], True, True,0) self.pack_start(self.hbox_zalozka_tlacitka, False, False, 0) self.pack_start(self.hbox_initdata_matdata_opacdata, False, False, 0) self.pack_end(self.settings["description"], False, True, 0)