def main(): while True: prob = Problem() #create problem size = prob.loadData( "data01.in") #load data of problem, return board size x = Individ([0] * size) pop = Population(x) alg = Algorithm(pop) alg.readParameters("param.in") printMainMenu() x = input() if x == "1": bestX, sample = alg.run() print(bestX) print(bestX.fitness()) plt.plot(sample) # function to show the plot plt.show() if x == "2": alg.run() sd, m = alg.statistics() print("Standard deviation " + str(sd)) print("Mean " + str(m)) if x == "0": return
def SelectProblemAndSearchAlgorithm(): print("Select the problem type:") print(" 1. Numerical Optimization") print(" 2. TSP") type1 = int(input("Enter the number: ")) if type1 == 1: p = Problem.Numeric() else: p = Problem.Tsp() p.createProblem() print("Select the search algorithm:") print(" 1. Steepest-Ascent") print(" 2. First-Choice") print(" 3. Gradient Descent") type2 = int(input("Enter the number: ")) if type1 == 1: if type2 == 1: o = optimizer.steepestAscentNumeric(algorithm="Steepest-Ascent") elif type2 == 2: o = optimizer.firstChoiceNumeric(algorithm="First-Choice") else: o = optimizer.gradient(algorithm="Gradient Descent") else: if type2 == 1: o = optimizer.steepestAscentTsp(algorithm="Steepest-Ascent") else: o = optimizer.firstChoiceTsp(algorithm="First-Choice") return p, o
def post(self, request, *args, **kwargs): front_url = get_front_url() user = self.get_object() username_field = self.model.USERNAME_FIELD impersonator_user_id = request.user.pk if not front_url: raise Problem(_("No shop configured.")) if user == request.user: raise Problem(_("You are already logged in.")) if not getattr(request.user, "is_superuser", False): raise PermissionDenied if getattr(user, "is_superuser", False) or getattr(user, "is_staff", False): raise PermissionDenied if not getattr(user, "is_active", False): raise Problem(_("This user is not active.")) if not hasattr(user, 'backend'): for backend in django_settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break login(request, user) request.session["impersonator_user_id"] = impersonator_user_id message = _("You're now logged in as {username}").format(username=user.__dict__[username_field]) messages.success(request, message) return HttpResponseRedirect(front_url)
def main(): # Parsing user input parser = ap.ArgumentParser() parser.add_argument('-i', '--input_problem', nargs='?', required=True, help='Input problem file (YAML filename).') parser.add_argument('-s', '--input_solution', nargs='?', required=True, help='Input solution file (HDF5 filename).') parser.add_argument('-o', '--output', nargs='?', required=True, help='Output policy file (YAML filename).') args = parser.parse_args() mdp = Mdp() mdp.load_policy(args.input_solution) raw_policy = mdp.p problem = Problem(args.input_problem) policy = problem.parse_policy(raw_policy) with open(args.output, 'w') as f: yaml.dump(policy, f)
class Controller: def __init__(self): self.swarm = Swarm() self.problem = Problem() def loadParameters(self): self.problem.LoadData() for i in range(0, 50): self.swarm.v.append(Particle(self.problem)) for k in range(0, len(self.problem.getA())): self.swarm.v[i].data.append(randint(0, 1)) self.swarm.v[i].velocity.append(0) self.swarm.v[i].evaluate() self.swarm.noOfParticles += 1 def iterate(self): gBest = self.swarm.getBest()[0] for i in range(0, self.swarm.noOfParticles): lBest = self.swarm.getBestNeighbourhood(i) self.swarm.v[i].bestPosition = gBest.data self.swarm.v[i].update(lBest) def run(self): for i in range(0, 100): self.iterate() print(self.swarm.getBest()[0].data)
def main(): # Parsing user input parser = ap.ArgumentParser() parser.add_argument('-i', '--input_problem', nargs='?', required=True, help='Input problem file (YAML filename).') parser.add_argument('-s', '--input_solution', nargs='?', required=True, help='Input solution file (YAML filename).') parser.add_argument('-o', '--output', nargs='?', required=True, help='Output image file (directory and file prefix).') args = parser.parse_args() with open(args.input_solution, 'r') as f: policy = yaml.load(f.read()) problem = Problem(args.input_problem) problem.plot(policy, args.output)
def search_alg(problem, search): itera = 0 node = MyNode(problem.InitialState) open_list = [node] #list of nodes closed_list = [] #list of nodes while True: itera += 1 if open_list == []: return pp.solution(False) node = open_list.pop() # pop node from open_list if problem.goaltest(node.state): return pp.solution(node.path, node.cost, itera) closed_list.append(node) #add current node to explored list # action is a list of components that can be launched for action in problem.action_func(node.state): child = problem.childnode(node, action, search) existent = pp.check_list(child.state, open_list) aux = pp.check_list(child.state, closed_list) if not existent and not aux: open_list.append(child) # push into open list elif existent: if child.cost < existent.cost: open_list.remove(existent) open_list.append(child) # order open list by evaluation function f=g+h open_list = sorted(open_list, key=lambda MyNode: MyNode.f, reverse=True)
def createInstances(self): for n in range(1,5): p=Problem(n,[0][0],[0][0]) for i in range (1, 5): for j in range (i+2, 5): s=State(4) s.matrix[i][j]=1 p.expand(p) self.listOfInstances.append(p)
def Main(filename, features_file, Algorithms, number_of_features, filter_target, list_features=None): print("\n---------------------------------\n") print("Load Data", end="") DATA = Load_Data.load_data(filename, ALGORITHMS, filter_target=filter_target) print(" [OK]\nLoad ELA Features", end="") P, D, F = Load_Data.load_ELA_features(features_file) print(" [OK]\nLink ELA Features to problems", end="") Problem.link_all_features(DATA, P, D, F) print(" [OK]\nInitialize Empirical Performance Model", end="") model = epm.EmpiricalPerformanceModel( number_of_parameters, number_of_features, len(ALGORITHMS), input_type="parameters", selector=Selector.Random_selector(probability=0.7), list_features=list_features) print(" [OK]\nFix Training and Testing sets", end="") model.build_training_and_testing_sets(DATA) print("\nNumber of problems : " + str(len(model.get_results())) + "\n") ''' print(" [OK]\nTrain EPM",end="") model.train_model() print(" [OK]\nTest EPM",end="") model.test_model() print(" [OK]\n") SBS=Statistic.SingleBestSolver(model) VBS=Statistic.VirtualBestSolver(model) RS=Statistic.RealSolver(model) Merit=Statistic.Merit(SBS,VBS,RS) print("SBS "+str(SBS)) print("VBS "+str(VBS)) print("RS "+str(RS)) print("Merit "+str(Merit)) ''' model.reset_model() model.set_input_type('features') print("Train EPM", end="") model.train_model() print(" [OK]\nTest EPM", end="") model.test_model() print(" [OK]\n") SBS = Statistic.SingleBestSolver(model) VBS = Statistic.VirtualBestSolver(model) RS = Statistic.RealSolver(model) Merit = Statistic.Merit(SBS, VBS, RS) print("SBS " + str(SBS)) print("VBS " + str(VBS)) print("RS " + str(RS)) print("Merit " + str(Merit))
def process_user(self, user): if "E-Commerce.front.apps.auth" not in settings.INSTALLED_APPS: raise Problem(_(u"The `E-Commerce.front.apps.auth` app needs to be enabled for password reset.")) r = RecoverPasswordForm() r.request = self.request if r.process_user(user): messages.success(self.request, _(u"Password recovery email sent to %(email)s") % {"email": getattr(user, 'email', '')}) else: raise Problem(_(u"Sending the password recovery email failed."))
def get_problem_config(problem_name): if problem_name == "simple": problem = Problem.simple() elif problem_name == "simple_multi": problem = Problem.simple_multi() elif problem_name == "quadratic": problem = Problem.quadratic() elif problem_name == "mnist": problem = Problem.mnist() elif problem_name == "cifar10": problem = Problem.cifar10() return problem
def main(): parser = argparse.ArgumentParser( description='''The driver Script for the Explanation generation''', epilog= "Usage >> ./Explainer.py -d ../test_domain/original_domain.pddl -p" + " ../test_domain/original_problem.pddl -f ../test_domain/plan_file -e ../test_domain/explanation_actions -m 2" ) ''' # Flags --generate_lattice ''' parser.add_argument('-d', '--domain_model', type=str, help="Domain file with real PDDL model of robot.", required=True) parser.add_argument('-p', '--problem', type=str, help="Problem file for robot.", required=True) parser.add_argument('-f', '--plan_file', type=str, help="Plan file for robot.", required=True) parser.add_argument('-e', '--explanatory_actions_file', type=str, help="Explanatory actions", required=True) parser.add_argument('-m', '--max_length', type=str, help="Max length", required=True) if not sys.argv[1:] or '-h' in sys.argv[1:]: print(parser.print_help()) sys.exit(1) args = parser.parse_args() problem = Problem(args.domain_model, args.problem, args.plan_file, args.explanatory_actions_file, int(args.max_length)) st_time = time.time() pl = problem.explain() print("Explanation", pl) print("Explanation Size >>>", len(pl)) print("Total time >>>", time.time() - st_time)
def _handle_set_is_active(self): state = bool(int(self.request.POST["set_is_active"])) if not state: if (getattr(self.object, 'is_superuser', False) and not getattr(self.request.user, 'is_superuser', False)): raise Problem(_("You can not deactivate a superuser.")) if self.object == self.request.user: raise Problem(_("You can not deactivate yourself.")) self.object.is_active = state self.object.save(update_fields=("is_active",)) messages.success(self.request, _("%(user)s is now %(state)s.") % { "user": self.object, "state": _("active") if state else _("inactive") }) return HttpResponseRedirect(self.request.path)
def greedySearch(state): heap = [] heap.extend(Problem.getSuccessors(state)) heapq.heapify(heap) while len(heap) > 0: currentState = heapq.heappop(heap) if Problem.isGoal(currentState): return currentState else: heap.extend(Problem.getSuccessors(currentState)) return None
def algorithm(problem_type, algorithm_type, n, val, var): N = n matrix = np.empty(shape=(N, N), dtype=object) variables = [] constraints = [] value_heuristics = [ InOrderValueHeuristic(), LeastConstrainedValueHeuristic() ] variable_heuristics = [ InOrderVariableHeuristic(), MostConstrainedVariableHeuristic(), MostConstrainingVariableHeuristic(), MostConstrainingOfMostConstrainedVariableHeuristic() ] if problem_type == 'graph': constraints += [ AdjacentNeighboursConstraint(), DiagonalNeighboursConstraint(), NonAdjacentNeighboursConstraint() ] domain = list(range(1, 4)) else: constraints += [RowEqualityConstraint(), ColumnEqualityConstraint()] domain = list(range(1, N + 1)) index = 0 for i in range(N): for j in range(N): variables.append(Variable(i, j, c.copy(domain))) matrix[i][j] = variables[index] index += 1 value_heuristic = value_heuristics[val] variable_heuristic = variable_heuristics[var] value_heuristic.set_constraints(constraints) variable_heuristic.set_constraints(constraints) problem = Problem(matrix, variables, constraints, value_heuristic, variable_heuristic) if algorithm_type == 'forward': res = problem.forward_checking() else: res = problem.backtracking() # draw_matrix(matrix) return res
def post(self, request, *args, **kwargs): order = self.object = self.get_object() new_status = OrderStatus.objects.get(pk=int(request.POST["status"])) old_status = order.status if new_status.role == OrderStatusRole.COMPLETE and not order.can_set_complete(): raise Problem(_("Unable to set order as completed at this point")) if new_status.role == OrderStatusRole.CANCELED and not order.can_set_canceled(): raise Problem(_("Paid, shipped, or canceled orders cannot be canceled")) order.status = new_status order.save(update_fields=("status",)) message = _("Order status changed: {old_status} to {new_status}").format( old_status=old_status, new_status=new_status) order.add_log_entry(message, user=request.user, identifier="status_change") messages.success(self.request, message) return HttpResponseRedirect(get_model_url(self.get_object()))
def main(): # Parsing user input parser = ap.ArgumentParser() parser.add_argument('-i', '--input_problem', nargs='?', required=True, help='Input problem file (YAML filename).') parser.add_argument('-s', '--input_sols', nargs='*', required=True, help='Input policy files (YAML filename).') parser.add_argument('-o', '--output', nargs='?', required=True, help='Output policy file (YAML filename).') args = parser.parse_args() # Loading problem problem = Problem(args.input_problem) # Loading solutions sols = {s: None for s in args.input_sols} for sol_filename in sols: with open(sol_filename, 'r') as f: sols[sol_filename] = yaml.load(f.read()) # For each state pol = [] for s in problem.s: action = {} state = {} # For each agent for agent_idx, loc_idx in enumerate(s): # Agent and agent location agent = problem.agents[agent_idx] loc = problem.locs[loc_idx] # Agent state state[agent] = ['at', loc] # Agent Action for sol in sols.values(): for p in sol: if agent in p['action'] and agent in p[ 'state'] and loc in p['state'][agent]: action[agent] = p['action'][agent] # Appending policy entry: new state and corresponding action pol.append({'action': deepcopy(action), 'state': deepcopy(state)}) # Storing merged policy with open(args.output, 'w') as f: yaml.dump(pol, f)
def jobs_load(file_path='./ta000.txt'): """ Load jobs from file.txt in format: 1 2 4 4 6 8 1 3 4 :param file_path: path to .txt file :return: list(Job) """ with open(file_path, 'r') as f: jobs_list = [] lines = [] '''Load NAME and PARAMETERS''' for line in f: lines.append(line) name = lines.pop(0) param = lines.pop(0).rstrip().split(' ') jobs = int(param[0]) machines = int(param[1]) del param """Load times""" for line in lines: if 'str' in line: break values = [int(i) for i in line.split()] jobs_list.append(values) problem = Problem(machines, jobs, jobs_list) return problem
def post(self, request, *args, **kwargs): # doccov: ignore command = request.POST.get("command") if command: dispatcher = getattr(self, "dispatch_%s" % command, None) if not callable(dispatcher): raise Problem(_("Unknown command %s") % command) dispatch_kwargs = dict(request.POST.items()) rv = dispatcher(**dispatch_kwargs) if rv: return rv self.request.method = "GET" # At this point, we won't want to cause form validation self.build_form() # and it's not a bad idea to rebuild the form return super(EditorView, self).get(request, *args, **kwargs) if request.POST.get("save") and self.form and self.form.is_valid(): self.form.save() self.save_layout() # after we save the new layout configs, make sure to reload the saved data in forms # so the returned get() response contains updated data self.build_form() if request.POST.get("publish") == "1": return self.dispatch_publish() return self.get(request, *args, **kwargs)
def save_problem(): if not request.json or not 'title' in request.json: abort(400) json_response = Problem.save_problem(conn, request.json) return jsonify(json_response)
def createRobotanikGraphViewer(problem: Problem, data, title, filename_suffix=""): puzzles_data_json = json.dumps([{ 'title': problem.title, 'about': problem.about, 'robotCol': problem.robotCol, 'robotRow': problem.robotRow, 'robotDir': problem.robotDir, 'subs': json.loads(problem.subs), 'allowedCommands': problem.allowedCommands, 'board': problem.board_str }]) with open( 'generated_html/{}{}.html'.format(problem.getFirstId(), filename_suffix), 'w') as output: with open('createRobotanikGraphViewer_template.html') as template: replaced = template.read() replaced = replaced.replace('__TEMPLATE_TITLE', title) replaced = replaced.replace('__TEMPLATE_PUZZLES', puzzles_data_json) replaced = replaced.replace('__TEMPLATE_DATA', json.dumps(data)) replaced = replaced.replace('./', '../html_src/') output.write(replaced)
def add_pheromone_by_ant(self, ant): subpaths = Problem.split_path(self.problem.center_position, ant.path) subpaths_length = [] for i in range(len(subpaths)): subpaths_length.append(self.problem.get_path_length(subpaths[i])) subpaths_rate = np.array(subpaths_length) average = np.mean(subpaths_rate) subpaths_rate -= average divider = max(subpaths_rate) if divider != 0: subpaths_rate /= divider else: print("死亡蚂蚁,不添加信息素...") return # 每段路径根据Rate来进行更新 base_pheromone = self.pheromone_add_function(ant) # base_pheromone = 1.0 / (self.problem.get_path_length(ant.path)) for i in range(len(subpaths)): subpath = subpaths[i] subpath_size = len(subpath) add_pheromone = base_pheromone * average_level_rate( subpaths_rate[i]) for j in range(subpath_size): m = subpath[j - 1] n = subpath[j] self.city_pheromone_array[m][n] += add_pheromone self.city_pheromone_array[n][m] = self.city_pheromone_array[m][ n] return
def save(self): parent_product = self.parent_product current_products = set(parent_product.variation_children.all()) selected_products, unlinked_products = self.get_selected_and_unlinked() with atomic(): products_to_add = selected_products - current_products products_to_remove = current_products & unlinked_products for child_product in products_to_remove: child_product.unlink_from_parent() for child_product in products_to_add: try: child_product.link_to_parent(parent_product) except ImpossibleProductModeException as ipme: six.raise_from( Problem( _("Unable to link %(product)s: %(error)s") % {"product": child_product, "error": ipme} ), ipme ) message_parts = [] if products_to_add: message_parts.append(_("New: %d") % len(products_to_add)) if products_to_remove: message_parts.append(_("Removed: %d") % len(products_to_remove)) if message_parts and self.request: messages.success(self.request, ", ".join(message_parts))
def save_problem(): if not request.json or 'title' not in request.json: json_response = {"result": "Title must be specified"} else: json_response = Problem.save_problem(conn, request.json) return jsonify(json_response)
def get_problem(id): print(id) problem, error = Problem.get_problem(conn, id) json_response = dict() json_response["problem"] = problem json_response["error"] = error return jsonify(json_response)
def add_pheromone_by_ant(self, ant): subpaths = Problem.split_path(self.problem.center_position, ant.path) subpaths_length = [] for i in range(len(subpaths)): subpaths_length.append(self.problem.get_path_length(subpaths[i])) subpaths_rate = np.array(subpaths_length) average = np.mean(subpaths_rate) subpaths_rate -= average divider = max(subpaths_rate) if divider != 0: subpaths_rate /= divider else: print("死亡蚂蚁,不添加信息素..."); return; # 每段路径根据Rate来进行更新 base_pheromone = self.pheromone_add_function(ant) # base_pheromone = 1.0 / (self.problem.get_path_length(ant.path)) for i in range(len(subpaths)): subpath = subpaths[i] subpath_size = len(subpath) add_pheromone = base_pheromone * average_level_rate(subpaths_rate[i]) for j in range(subpath_size): m = subpath[j - 1] n = subpath[j] self.city_pheromone_array[m][n] += add_pheromone; self.city_pheromone_array[n][m] = self.city_pheromone_array[m][n]; return
def ship_products(self, shipment, product_quantities): # stocks are managed, do stocks check if self.supplier.stock_managed: insufficient_stocks = {} for product, quantity in product_quantities.items(): if quantity > 0: stock_status = self.get_stock_status(product.pk) if stock_status.stock_managed and stock_status.physical_count < quantity: insufficient_stocks[product] = stock_status.physical_count if insufficient_stocks: formatted_counts = [ _("%(name)s (physical stock: %(quantity)s)") % { "name": force_text(name), "quantity": force_text(quantity) } for (name, quantity) in insufficient_stocks.items() ] raise Problem( _("Insufficient physical stock count for following products: %(product_counts)s") % { "product_counts": ", ".join(formatted_counts) } ) for product, quantity in product_quantities.items(): if quantity == 0: continue sp = shipment.products.create(product=product, quantity=quantity) sp.cache_values() sp.save() shipment.cache_values() shipment.save()
def getTSPfromFile(self, filename): try: fh = open(filename, mode='r') except IOError: print("File " + filename + " does not exist, exiting.") exit(0) ncs = False # in node_coord_section of file problem = Problem.Problem() problem.setFilename(filename) for line in fh: if line.startswith("NODE_COORD_SECTION\n"): # Set flag for node coord data follows ncs = True elif line.startswith("NAME"): n = line.rsplit(":") name = str(n[1]).strip() problem.setName(name) elif line.startswith("COMMENT"): l = line.rsplit(":") desc = str(l[1]).strip() problem.setDescription(desc) elif line.startswith("EOF\n"): ncs = False elif ncs: # parse coordinates node = line.split() obj = Node.TSPNode(node[0], node[1], node[2]) problem.addNodeObj(obj) fh.close() return problem
def save(self): parent_product = self.parent_product current_products = set(parent_product.get_package_child_to_quantity_map()) selected_products, removed_products, selected_quantities = self.get_selected_and_removed() with atomic(): try: clear_existing_package(parent_product) parent_product.make_package(package_def=selected_quantities) except ImpossibleProductModeException as ipme: six.raise_from( Problem( _("Unable to make package %(product)s: %(error)s") % {"product": parent_product, "error": ipme} ), ipme ) products_to_add = selected_products - current_products products_to_remove = current_products & removed_products message_parts = [] if products_to_add: message_parts.append(_("New: %d") % len(products_to_add)) if products_to_remove: message_parts.append(_("Removed: %d") % len(products_to_remove)) if message_parts and self.request: messages.success(self.request, ", ".join(message_parts))
def dispatch_command(self, request, command): product = self.object if command == "clear_package": clear_existing_package(product) messages.success(self.request, _("Package cleared.")) else: raise Problem("Unknown command: %s" % command) return HttpResponseRedirect(self.get_success_url())
def get_problems(columns): problems, error = Problem.get_problems(conn, columns) print(problems) d = {} d["problems"] = problems d["error"] = error return jsonify(d)
def do_search(self): # first_time() for i in range(ITERATION): # 产生下一代个体,并且将个体加入population中 self.add_next_generation() # 淘汰产生的个体到population_size的数量 self.selection_sort() print("第%d代生成:" % i) print("最优解:%s, 路径:%s" % (self.population[0].result, Problem.split_path(self.problem.center_position,self.population[0].gene))) self.problem.update_best_result(self.population[0].gene)
def split_path(self, center): return Problem.split_path(center, self.gene)