def __init__(self, ui_filename): # Load UI self.dialog = loader.load( os.path.join(os.path.dirname(__file__), ui_filename), None) self.dialog.show() # Set title image pixmap = QtGui.QPixmap( os.path.join(os.path.dirname(__file__), 'title.png')) self.dialog.label.setPixmap(pixmap) # Button actions self.dialog.btn_getrecipes.clicked.connect(self.btn_getrecipe) self.dialog.btn_resetquery.clicked.connect(self.btn_resetquery) self.dialog.btn_rate.clicked.connect(self.btn_rate) # Menu actions self.dialog.actionAbout.triggered.connect(self.about) self.dialog.actionConstraints.triggered.connect( self.load_constraints_file) self.dialog.actionLibrary.triggered.connect(self.load_library_file) self.dialog.actionExport.triggered.connect( self.export_constraints_file) self.dialog.actionUser_Manual.triggered.connect(self.open_user_manual) # Slider action self.dialog.slider_evaluation.valueChanged.connect(self.slider_change) # Init CBR self.cbr = CBR(os.path.join(DATA_PATH, 'case_library.xml'), verbose=True)
def load_library_file(self): library_file, _ = QtWidgets.QFileDialog.getOpenFileName( self.dialog, "Open Library", DATA_PATH, 'XML Files (*.xml)') print(f'Load CBR library from: {library_file} ...') try: # Init CBR self.cbr = CBR(library_file, verbose=True) except Exception as e: # Prompt error message button = QtWidgets.QMessageBox.critical( self.dialog, "Library error!", f'Library error. Choose a valid case library.\nException:{str(e)}', buttons=QtWidgets.QMessageBox.Close, defaultButton=QtWidgets.QMessageBox.Close)
def get_curs(start_date, end_date): start_date = datetime.datetime.strptime(start_date, '%Y-%m-%dT00:00:00') end_date = datetime.datetime.strptime(end_date, '%Y-%m-%dT00:00:00') days = [start_date + datetime.timedelta(days=x) for x in range((end_date - start_date).days + 1)] cbr = CBR() for day in days: curs = cbr.get_curs_on_date(day.strftime('%Y-%m-%d')) for c in curs['curs']: if db.session.query(Valuta).get({'id': c['Vcode']}) is None: valuta = Valuta(id=int(c['Vcode']), ch_code=c['VchCode'], name=c['Vname']) db.session.add(valuta) db.session.commit() if db.session.query(Curs).filter(Curs.code == c['Vcode']).filter( Curs.date == day.strftime('%Y-%m-%d')).first() is None: curs_record = Curs(code=int(c['Vcode']), date=day, nom=c['Vnom'], curs=c['Vcurs']) db.session.add(curs_record) db.session.commit()
import random import os import json import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from cbr import CBR DATA_PATH = '../Data' # Create cocktails CBR cocktails_cbr = CBR(os.path.join(DATA_PATH, 'case_library.xml'), verbose=True) number_of_tests = [100, 500, 1000] n_constraints = 8 for n_tests in number_of_tests: names = [f"cocktail_{i}" for i in range(n_tests)] all_tests = {} for i in range(n_tests): my_dict = {"name": names[i]} n_categories, n_glasses, n_alc_types, n_basic_tastes, n_ingredients, n_exc_ingredients, n_exc_alc_types, \ n_exc_basic_tastes = [random.randint(0, 3) for i in range(n_constraints)] my_dict["category"] = random.sample(cocktails_cbr.categories, n_categories)
positional arguments: caselibrary Filepath of the XML case library optional arguments: -h, --help show this help message and exit --verbosity VERBOSITY Output verbosity level. Set to 1 to print debug messages. -c CONSTRAINTS, --constraints CONSTRAINTS Filepath of the JSON constraints file """ # Input arguments args = parse_arguments() # Initialize CBR cbr = CBR(args.caselibrary, verbose=args.verbosity) # Get user constraints constraints = get_constraints(args, cbr) # Get new case retrieved_case, adapted_case, original = cbr.get_new_case(constraints) # Print retrieved case print('\n=====================================================================') print(f'Retrieved cocktail: {retrieved_case.find("name").text}') print('\nIngredients:') cbr.print_ingredients(retrieved_case) print('\nPreparation:') cbr.print_preparation(retrieved_case)
def perform_tests(args): # Convert CSV to xml to make sure that case_library.xml only contains original recipes xml_file = os.path.join(DATA_PATH, 'case_library.xml') create_xml_library(args.path, xml_file) cbr = CBR(xml_file) get_new_case_times = [] evaluated_learn_new_case_times = [] with open(args.tests) as json_file: data = json.load(json_file) for key, value in data.items(): # Get test constraints of each case constraints = value # Get new case start_ra = time.time() retrieved_case, adapted_case, original = cbr.get_new_case( constraints) end_ra = time.time() get_new_case_times.append(end_ra - start_ra) # Evaluate if cocktail is derived (not original) start_el = time.time() if not original: cbr.evaluate_new_case(retrieved_case, adapted_case, 8.0) end_el = time.time() evaluated_learn_new_case_times.append(end_el - start_el) total_times = np.array(get_new_case_times) + np.array( evaluated_learn_new_case_times) mean_ra_time = np.mean(np.array(get_new_case_times)) mean_el_time = np.mean(np.array(evaluated_learn_new_case_times)) mean_total_time = np.mean(total_times) print( f"The average time needed for retrieval and adaptation steps is : {mean_ra_time}" ) print( f"The average time needed for evaluation and adaptation steps is: {mean_el_time}" ) print( f"The average total time for the complete CBR cycle over a new case is : {mean_total_time}" ) experiments = [i for i in range(len(total_times))] plt.plot(experiments, total_times, color="red", label="Total Time") plt.plot(experiments, np.array(get_new_case_times), color="green", label="Retrieval and Adaptation") plt.plot(experiments, np.array(evaluated_learn_new_case_times), color="blue", label="Evaluation and Learning") plt.plot([0, len(total_times)], [mean_total_time, mean_total_time], "--", color="red", label="Average Total Time") plt.title( f"Times needed for each phase for {len(total_times)} experiments") plt.xlabel("Queries performed") plt.ylabel("Time in seconds") plt.legend(loc="upper left") plt.savefig(f"{len(total_times)}_results.png") plt.show() with open(f"./{len(total_times)}_results.txt", 'w') as output: print(get_new_case_times, file=output) print(evaluated_learn_new_case_times, file=output)