def p_plan_problem(p): '''plan_problem : LPAREN DEFINE_KEY plan_problem_def domain_def objects_def init_def goal_def RPAREN | LPAREN DEFINE_KEY plan_problem_def domain_def init_def goal_def RPAREN''' if len(p) == 9: p[0] = Problem(p[3], p[4], p[5], p[6], p[7]) elif len(p) == 8: p[0] = Problem(p[3], p[4], {}, p[5], p[6])
def main(params, data_path, save_path): conf = ModelConf("cache", params.conf_path, version, params) if ProblemTypes[conf.problem_type] == ProblemTypes.sequence_tagging: problem = Problem(conf.problem_type, conf.input_types, conf.answer_column_name, source_with_start=True, source_with_end=True, source_with_unk=True, source_with_pad=True, target_with_start=True, target_with_end=True, target_with_unk=True, target_with_pad=True, same_length=True, with_bos_eos=conf.add_start_end_for_seq, tagging_scheme=conf.tagging_scheme, remove_stopwords=conf.remove_stopwords, DBC2SBC=conf.DBC2SBC, unicode_fix=conf.unicode_fix) elif ProblemTypes[conf.problem_type] == ProblemTypes.classification \ or ProblemTypes[conf.problem_type] == ProblemTypes.regression: problem = Problem(conf.problem_type, conf.input_types, conf.answer_column_name, source_with_start=True, source_with_end=True, source_with_unk=True, source_with_pad=True, target_with_start=False, target_with_end=False, target_with_unk=False, target_with_pad=False, same_length=True, with_bos_eos=conf.add_start_end_for_seq, remove_stopwords=conf.remove_stopwords, DBC2SBC=conf.DBC2SBC, unicode_fix=conf.unicode_fix) if os.path.isfile(conf.problem_path): problem.load_problem(conf.problem_path) logging.info("Cache loaded!") logging.debug("Cache loaded from %s" % conf.problem_path) else: raise Exception("Cache does not exist!") data, length, target = problem.encode(data_path, conf.file_columns, conf.input_types, conf.file_with_col_header, conf.object_inputs, conf.answer_column_name, conf.min_sentence_len, extra_feature=conf.extra_feature, max_lengths=conf.max_lengths, file_format='tsv') if not os.path.isdir(os.path.dirname(save_path)): os.makedirs(os.path.dirname(save_path)) dump_to_pkl({'data': data, 'length': length, 'target': target}, save_path)
def test_greedy(self): # choose best path not first path p = Problem('greedy', 5, 10, 10, [('+', 1), ('+', 5)]) r = (10, 1) TestGreedy._test_greedy(self, p, r) # choose a path that works p1 = Problem('greedy', 5, 10, 10, [('+', 1), ('*', 3)]) r1 = (10, 5) TestGreedy._test_greedy(self, p1, r1)
def run_requested_algorithm(problem): output = None algorithm_name = problem[0] if algorithm_name == 'UCS': output = UCS(Problem(problem)).run() if algorithm_name == "ASTAR": output = AStar(Problem(problem)).run() if algorithm_name == "IDS": output = IDS(Problem(problem), 20).run() if algorithm_name == "IDASTAR": output = IDAStar(Problem(problem)).run() write_output(output)
def initBattleSimulation(self, player1Algo, player2Algo, opponent, player2CuttingDepth): nextState = self.initialState player = self.player INFINITY = float('inf') outFile = open("trace_state.txt", "w") while not Problem.goalTest(nextState): if player == self.player: #first player if int(player1Algo) == 1: nextState = self.greedyBFSBattle(nextState, player) elif int(player1Algo) == 2: problemObj = Problem(nextState, self.boardValue, player) node = Node(nextState, None, self.cuttingDepth, -INFINITY, "root", problemObj, player) bestValue = self.minimaxBattle(node, self.cuttingDepth, True, problemObj) nextState = self.getNextState(node, bestValue) elif int(player1Algo) == 3: problemObj = Problem(nextState, self.boardValue, player) node = Node(nextState, None, self.cuttingDepth, -INFINITY, "root", problemObj, player) bestValue = self.alphabetaBattle(node, self.cuttingDepth, -INFINITY, INFINITY, True, problemObj) nextState = self.getNextState(node, bestValue) else: #opponent player if int(player2Algo) == 1: nextState = self.greedyBFSBattle(nextState, opponent) elif int(player2Algo) == 2: problemObj = Problem(nextState, self.boardValue, opponent) node = Node(nextState, None, player2CuttingDepth, -INFINITY, "root", problemObj, opponent) bestValue = self.minimaxBattle(node, player2CuttingDepth, True, problemObj) nextState = self.getNextState(node, bestValue) elif int(player2Algo) == 3: problemObj = Problem(nextState, self.boardValue, opponent) node = Node(nextState, None, player2CuttingDepth, -INFINITY, "root", problemObj, opponent) bestValue = self.alphabetaBattle(node, player2CuttingDepth, -INFINITY, INFINITY, True, problemObj) nextState = self.getNextState(node, bestValue) # self.printState(nextState) for x in nextState: outFile.write(''.join(x)) outFile.write("\n") player = self.player if player == opponent else opponent outFile.close()
def main(): problem = Problem("data01.in") algoritm = Algorithm(problem, "param.in") #start_time = time.time() algoritm.statistics()
def Main(): myMap = map.readFromFile(sys.argv[1]) print("Map:", sys.argv[1]) print("Map read in successfully") p = Problem(myMap) startTime = time.process_time() BFS(p) endTime = time.process_time() duration = endTime - startTime print("time spent with BFS: ", duration, "seconds") print("BFS completed successfully") print("") startTime = time.process_time() UCS(p) endTime = time.process_time() duration = endTime - startTime print("time spent with UCS: ", duration, "seconds") print("UCS completed successfully") print("") startTime = time.process_time() aStar(p) endTime = time.process_time() duration = endTime - startTime print("time spent with A*: ", duration, "seconds") print("A* completed successfully")
def select_problem_by_id(self, file_id): with self.connection: problem_data = self.cursor.execute( '''SELECT * FROM problems WHERE file_id = ?''', (file_id, )).fetchall()[0] problem = Problem(*problem_data) return problem
def main(): # instantiate dynamics dyn = Dynamics() # instantiate leg leg = Leg(dyn, alpha=0, bound=True) # set boudaries t0 = 0 s0 = np.array([1000, 1000, *np.random.randn(4)], dtype=float) l0 = np.random.randn(len(s0)) tf = 1000 sf = np.zeros(len(s0)) leg.set(t0, s0, l0, tf, sf) # define problem udp = Problem(leg, atol=1e-8, rtol=1e-8) prob = pg.problem(udp) # instantiate algorithm uda = pg7.snopt7(True, "/usr/lib/libsnopt7_c.so") uda.set_integer_option("Major iterations limit", 4000) uda.set_integer_option("Iterations limit", 40000) uda.set_numeric_option("Major optimality tolerance", 1e-2) uda.set_numeric_option("Major feasibility tolerance", 1e-4) algo = pg.algorithm(uda) # instantiate population with one chromosome pop = pg.population(prob, 1) #pop = pg.population(prob, 0) #pop.push_back([1000, *l0]) # optimise pop = algo.evolve(pop)
def translate(problem, arglist): x = arglist[0] y = arglist[1] print "translate: ", type(problem) assert (type(problem) == Problem) assert (type(x) == Fraction) assert (type(y) == Fraction) #new_polys = deepcopy(problem.plist) #new_lines = deepcopy(problem.slist) new_polys = [] new_lines = [] for polygon in problem.plist: vlist = [] for vertex in polygon: vlist.append(Segment(vertex[0] + x, vertex[1] + y)) new_polys.append(vlist) for line in problem.slist: #for line in s: a = line[0] b = line[1] print(a, b) new_lines.append(Segment(a[0] + x, a[1] + y, b[0] + x, b[1] + y)) # Note that Problem construtor wants tuples, not Fractions return Problem(new_polys, new_lines)
def test_init_invalid_name(): invalid = ['', 'a', 'a-', '-a', '!', 'ab!c'] for i in invalid: with pytest.raises(ValueError, match=r'invalid name ".*"'): args = Problem.default_args() args.name = i p = Problem(args)
def callbackPSO(b, c, d): self.__n = d self.__problem = Problem(self.__n) self.__controller = Controller(self.__problem) #startClock = time() noIteratii = c dimPopulation = b # numbers for permutations will be in interval [1, n] vmin = 1 vmax = self.__n # maximum fitness possible maximumFitness = 4 * vmax # specific parameters for PSO w = 1.0 c1 = 1. c2 = 2.5 sizeOfNeighborhood = 20 optimIndividual, fitnessOptim = self.__controller.ParticleSwarmOptimization( noIteratii, dimPopulation, vmin, vmax, w, c1, c2, sizeOfNeighborhood) # output of the optim individual print("This is the best individual I could find: \n") print(str(optimIndividual)) # output of the fitness of the individuali ratio = str(fitnessOptim) + '/' + str(maximumFitness) print(ratio)
def build_problem(name, get_pfront=False): ''' Build optimization problem Input: name: problem name get_pfront: if return predefined true Pareto front of the problem Output: problem: the optimization problem pareto_front: the true Pareto front of the problem (if defined, otherwise None) ''' problem = None # build problem python_problems, yaml_problems = find_all_problems() if name in python_problems: problem = python_problems[name]() elif name in yaml_problems: full_prob_cfg = load_config(yaml_problems[name]) problem = Problem(config=full_prob_cfg) else: raise Exception(f'Problem {name} not found') # get true pareto front if get_pfront: try: pareto_front = problem.pareto_front() except: pareto_front = None return problem, pareto_front else: return problem
def __init__(self): self.__problem = Problem() self.__controller = Controller(self.__problem) super().__init__() #self.validation() self.initUI()
def HillClimbing(self, n): p = Problem(n) queue = p.getMatrix() listOfPermutations = p.getListOfPermutations() print("I am going to print the best solution found: ") possible_solution = [] row = 1 while queue: row_state = queue.pop() next_state, listOfPermutations = p.expand(row_state, listOfPermutations, row) possible_solution.append(next_state) print(possible_solution) time.sleep(0.5) row += 1 fitnessOptim = p.fitness(possible_solution, n) p = PrettyTable() for row in possible_solution: p.add_row(row) pretty = p.get_string(header=False, border=False) return pretty, fitnessOptim
def main(params): conf = ModelConf('predict', params.conf_path, version, params, mode=params.mode) problem = Problem('predict', conf.problem_type, conf.input_types, None, with_bos_eos=conf.add_start_end_for_seq, tagging_scheme=conf.tagging_scheme, tokenizer=conf.tokenizer, remove_stopwords=conf.remove_stopwords, DBC2SBC=conf.DBC2SBC, unicode_fix=conf.unicode_fix) if os.path.isfile(conf.saved_problem_path): problem.load_problem(conf.saved_problem_path) logging.info("Problem loaded!") logging.debug("Problem loaded from %s" % conf.saved_problem_path) else: raise Exception("Problem does not exist!") if len(conf.predict_fields_post_check) > 0: for field_to_chk in conf.predict_fields_post_check: field, target = field_to_chk.split('@') if not problem.output_dict.has_cell(target): raise Exception("The target %s of %s does not exist in the training data." % (target, field_to_chk)) lm = LearningMachine('predict', conf, problem, vocab_info=None, initialize=False, use_gpu=conf.use_gpu) lm.load_model(conf.previous_model_path) logging.info('Predicting %s with the model saved at %s' % (conf.predict_data_path, conf.previous_model_path)) lm.predict(conf.predict_data_path, conf.predict_output_path, conf.predict_file_columns, conf.predict_fields) logging.info("Predict done! The predict result: %s" % conf.predict_output_path)
def run(self): self.run = True self.done = False self.problem = Problem("") self.speak("Hello, how may I help you today?") while self.run: print("How may I help you?") question = self.recognize_speech_from_mic() # If we asked "Can I help you with anything else?" and the # answer is "no" then exit. if self.done and re.match(".*no.*", question): self.speak("Goodbye, have a pleasant day.") break else: self.done = False self.problem.content = question self.classify() success = self.assess() if not success: self.speak("I'm sorry, I don't know how to help with that.")
def program(app): while True: print() print('Please select an operation.') print() print('1. Add') print('2. Subtract') print('3. Multiply') print('4. Divide') option = get_integer_from_user('> ') operation = OPERATIONS.get(option, None) if operation: left = get_operand() right = get_operand() problem = Problem(operation(), left, right) result = str.format('{} = ?', problem.displayWithoutAnswer()) print('Problem:', result) if app: app.memoryBank.add(problem) else: print('Please select a valid option.') if not get_should_continue('Do you wish to continue? [Y]es/[N]o: '): break
def __init__(self, configuration = {}, refTime = 0): self.unprocessedProblems = {} self.processedProblems = {} self.complete = False # Initialize the number of problems (excluding the expected root node) self.n = -1 # Initialize upper bound problem (dummy with indefinite upper bound) self.upperBoundProblem = Problem(upperBound = float('inf')) # Initialize lower bound (negative infinite objective value) self.lowerBound = -float('inf') # Calculate optimality gap self.gap = float('inf') # Initialize gap history self.gapHistory = {0: self.gap} # Initialize time spent in tree '{Level: {Code chunk: Time spent in chunk}}' self.times = {'refTime': refTime, 'Total': 0, 'Branch and price': {'Initializations': 0, 'Construction heuristic': 0, 'Solve node': 0, 'Branch': 0, 'Search': 0, 'Other': 0}, 'Node': {'Column generation': 0, 'Other': 0}, 'Column generation': {'Solve RMP': 0, 'Update RMP': 0, 'Solve SP': 0, 'Construction heuristic': 0, 'SP order selection': 0, 'Other': 0} } # Initialize model configuration self.configuration = configuration
def parse_args(): parser = initialize_parser() if len(sys.argv[1:]) == 0: parser.print_help() print( "\nNote: *either* --dir *or* (--phi, --P, --Q, and --IO) is " + "required. This is an exclusive-or *either*." ) parser.exit() args = parser.parse_args() if not (args.dir or (args.phi and args.Q and args.model and args.IO)): print( "\nNote: *either* --dir *or* (--phi, --P, --Q, and --IO) is " + "required. This is an exclusive-or *either*." ) parser.exit() check_args(args) return Problem( args.P, args.Q, args.IO, args.phi, args.max_attacks, args.characterize, args.recovery, args.name, )
def callbackEA(a, b, c, d): self.__n = d self.__problem = Problem(self.__n) self.__controller = Controller(self.__problem) #startClock = time() noIteratii = c dimPopulation = b # numbers for permutations will be in interval [1, n] vmin = 1 vmax = self.__n # the mutation probability pM = a # maximum fitness possible maximumFitness = 4 * vmax optimIndividual, fitnessOptim = self.__controller.EvolutionaryAlgorithm( noIteratii, dimPopulation, vmin, vmax, pM) # output of the optim individual print("This is the best individual I could find: \n") print(optimIndividual) # output of the fitness of the individuali ratio = str(fitnessOptim) + '/' + str(maximumFitness) print(ratio)
def solve(self, expr: str = ""): """solve cryptarithm problem""" print("Problem: {}".format(expr)) p = Parser(tokenize(expr)) pr = Problem(p.parse()) print(pr.search_all_solution())
def test_init_happy_path(): args = Problem.default_args() args.name = '3sum' p = Problem(args) # misc attributes assert (p._verbose == False) # leetcode attributes assert (p._name == args.name) assert (p._url == problem.LEETCODE_URL_BASE + '/' + args.name) # github attributes assert (p._issue == -1) # problem attributes #assert(p._leetcode_number == -1) assert (p._problem_template == '') assert (p._difficulty == Difficulty.INVALID) assert (p._time == -1) assert (p._time_rank == -1) assert (p._time_complexity == '') assert (p._space == -1) assert (p._space_rank == -1) assert (p._space_complexity == '')
def run(): with open("data/graph.json") as data_file: data = json.load(data_file) graph = graph_from_json(data) with open("data/orders15.json") as data_file: data = json.load(data_file) orders = orders_from_json(data) with open("data/bikers10.json") as data_file: data = json.load(data_file) bikers = bikers_from_json(data) print("GRAPH") for node in graph.nodes(): print("\nNode {} has the following neighbours:".format(node.name())) for neighbour in graph.neighbours(node): print(neighbour.name()) print("BIKERS") for key in bikers.keys(): print("Id: {id}. Location: {node}".format(id=key, node=bikers[key].name())) print("ORDERS") for key in orders.keys(): print("Id: {id}. From: {from_node}, To: {to_node}".format( id=key, from_node=orders[key][0].name(), to_node=orders[key][1].name())) print("-------------\n") problem = Problem(graph, bikers, orders) solver = SimulatedAnnealing(problem, True) solver.runSA() #print("Found solution: ", solver.bestSolution) #print("Solution cost: ", solver.bestCost) #print("Cost for all bikers: ", solver.bestCostOfRoutes) return problem, solver
def generate(players_file, data_file): # Reads the players from the instance file players = [] roles = [] teams = [] with open(players_file) as file: for line in file: role, name, salary, team, projection, duplicateCode = ( s for s in line.split()) if role not in roles: roles.append(role) if team not in teams: teams.append(team) salary = float(salary) projection = float(projection) duplicateCode = int(duplicateCode) players.append( Player(name, role, salary, team, projection, duplicateCode)) problem = None with open(data_file) as file: # Skips the first line file.readline() nLineUps, nDifferences, budget, nPlayers, gks, dfs, mfs, fws, extras, maxPerTeam, minTeams = ( int(s) for s in file.readline().split()) playersPerRole = {} playersPerRole['GK'] = gks playersPerRole['D'] = dfs playersPerRole['M'] = mfs playersPerRole['F'] = fws problem = Problem(nLineUps, nDifferences, players, roles, teams, budget, nPlayers, playersPerRole, extras, maxPerTeam, minTeams) return problem
def __init__(self, t, NS, tp, computer, historydb: HistoryDB = None, options: Options = None, niter=1, *args, **kwargs): super().__init__(*args, **kwargs) self.myworker_id = kwargs['id'] self.tp = tp self.computer = computer self.problem = Problem(tp, driverabspath=None, models_update=None) self.t = t self.NS = NS self.niter = niter self.count_runs = 0 self.timefun = 0 if (options is None): options = Options() self.options = options if (historydb is None): historydb = HistoryDB() self.historydb = historydb
def artificial_basis(problem): """ Find reference vector using method of artificial basis """ msg = None own_A = problem.A.copy() own_b = problem.b.copy() b_negative_indexes = is_not_valid(problem.b) if b_negative_indexes: own_A[b_negative_indexes] *= -1 own_b[b_negative_indexes] *= -1 # End if own_A = np.hstack((own_A, np.eye(problem.num_cond))) own_c = np.hstack((np.zeros(problem.num_var), np.ones(problem.num_cond))) own_problem = Problem(own_A, own_b, own_c) artificial_vector = np.hstack( (np.zeros(problem.num_var), problem.b.copy())) tmp, _ = simplex_method(own_problem, artificial_vector) if tmp is None: return None, "Could not find the reference vector." # End if x = tmp[range(problem.num_var)] y = tmp[range(problem.num_var, problem.num_var + problem.num_cond)] if is_positive(y): msg = "Solution: empty set" x = np.array([]) # End if return x, msg
def generate_fake(self, paper): for i in range(3000): model = Problem() model.id = i model.difficulty = random.random() if i < 1001: model.type = 1 model.score = paper.each_type_score[model.type-1] / \ paper.each_type_count[model.type-1] if i > 1000 and i < 2001: model.type = 2 model.score = paper.each_type_score[model.type-1] / \ paper.each_type_count[model.type-1] if i > 2000 and i < 3001: model.type = 3 model.score = paper.each_type_score[model.type-1] / \ paper.each_type_count[model.type-1] points = [] # count = random.randint(1, 2) count = 1 for j in range(count): points.append(random.randint(1, 10)) model.points = points self.problem_db.append(model)
def get_sub_problem(self, edges_subset): sub_graph = self.problem.partial_order.subgraph(edges_subset) sub_hypergraph = self.problem.hypergraph.subgraph( self.problem.ground_set | set(edges_subset)).copy() extra = list(nx.isolates(sub_hypergraph)) sub_hypergraph.remove_nodes_from(extra) sub_vars = [ n for n, d in sub_hypergraph.nodes(data=True) if d['bipartite'] == 1 ] edges = { edge.name: edge for edge in self.problem.edges.values() if edge.name in edges_subset } vert = { var.name: var for var in self.problem.variables.values() if var.name in sub_vars } second_problem = Problem([], [], 1, edges=edges, variables=vert, hypergraph=sub_hypergraph, partial_order=sub_graph) return second_problem
def get_sub_problem(prob, sub_hypergraph, sub_graph): extra = list(nx.isolates(sub_hypergraph)) sub_hypergraph.remove_nodes_from(extra) vars = [ n for n, d in sub_hypergraph.nodes(data=True) if d['bipartite'] == 1 ] edges = { edge.name: edge for edge in prob.edges.values() if edge.name in sub_graph.nodes } vert = { var.name: var for var in prob.variables.values() if var.name in vars } input_vars = [x for x in prob.input_vars if x in vars] sub_problem = Problem([], [], 1, edges=edges, variables=vert, hypergraph=sub_hypergraph, partial_order=sub_graph, input_vars=input_vars) return sub_problem