def testMain(self): self.assertEqual(solver.main("a b c"), [['b', 'c', 'a']]) self.assertEqual(solver.main("?? ( a b c )"), [['-b', '-c', '-a'], ['-b', '-c', 'a'], ['-b', 'c', '-a'], ['b', '-c', '-a']]) self.assertEqual(solver.main("a !b ^^ (b c) ?? (c d)"), [['-d', '-b', 'c', 'a']])
def get_oplossingen(self): afstandsmatrix = np.zeros( [len(self.points), len(self.points)], dtype=object) coordinaten = [] self.sol = None for index_x, x in enumerate(self.points): for index_y, y in enumerate(self.points): if x == y: continue afstandsmatrix[index_x, index_y] = hypot(abs(x[0] - y[0]), abs(x[1] - y[1])) afstandsmatrix[0][0] = float('inf') solver.afstandsmatrix = afstandsmatrix solver.main([x for x in range(len(afstandsmatrix))]) for _ in range(5): # try it 10 times app.processEvents() sol = solver.solver.solveOnce() app.processEvents() if not self.sol: self.sol = sol elif sol[1] < self.sol[1]: self.sol = sol print(self.sol) self.update()
def trial_5(file_list): """BT+FC+MRV+DH+LCV""" settings.fc = True settings.mrv = True settings.dh = True settings.lcv = True settings.acp = False settings.ac = False settings.solver_display_realtime = False settings.solver_display_verbose = False for each in file_list: solver.main(each)
def trial_1(file_list): """BT only""" settings.fc = False settings.mrv = False settings.dh = False settings.lcv = False settings.acp = False settings.ac = False settings.solver_display_realtime = False settings.solver_display_verbose = False for each in file_list: solver.main(each)
def main (type) : """ """ solver.main(gbdt_solver, 1, type, feature_reduction.undo) solver.main(gbdt_solver, 2, type, feature_reduction.undo) return processes = [] process1 = Process(target = solver.main, args = (gbdt_solver, 1, type, feature_reduction.undo)) process1.start() processes.append(process1) process2 = Process(target = solver.main, args = (gbdt_solver, 2, type, feature_reduction.undo)) process2.start() processes.append(process2) for process in processes: process.join() evaluate.mergeoutput()
def get_use_combinations(use_flags, req_use): """ For given use flags and required use combination It uses random methods to generate valid yet random combinations of USE flags to build/test the package """ # use_flags is a string by default use_flags = [ k.replace('-', '').replace('+', '') for k in use_flags.split() ] # List to store final generated USE flag combinations final_combinations = [] # Absolute values of flags from the required use variable req_flags = [] # Sat solver determines all valid combinations of req_use req_solns = solver.main(req_use) # Fill in req_flags from any of the solutions([] in case of # no req_use variable) for signed_flag in req_solns[0]: req_flags.append(abs_flag(signed_flag)) # Sort all cmbinations on the number of enabled USE flags for i, soln in enumerate(req_solns): req_solns[i] = (sum(1 for k in soln if k[0] != '-'), soln) req_solns.sort(key=lambda tup: tup[0]) # use_flags are those that weren't in req_flags, thus both # sets are now mutually exclusive req_flags = set(req_flags) use_flags = set(use_flags) - req_flags # Combination number one: Minimum possible USE flags enabled tmp_use = ["-" + k for k in use_flags] + req_solns[0][1] final_combinations.append(tmp_use) # Combination number two: Maximum possible USE flags enabled tmp_use = [k for k in use_flags] + req_solns[-1][1] final_combinations.append(tmp_use) # Combination number three: Random + Random bias = random.randrange(0, 10) # Number between 0 and 9 tmp_use = [("-" if random.randrange(0, 10) <= bias else "") + k for k in use_flags] tmp_use += req_solns[random.randrange(0, len(req_solns))][1] final_combinations.append(tmp_use) # Combination number three: Random + Random bias = random.randrange(0, 10) # Number between 0 and 9 tmp_use = [("-" if random.randrange(0, 10) <= bias else "") + k for k in use_flags] tmp_use += req_solns[random.randrange(0, len(req_solns))][1] final_combinations.append(tmp_use) # Remove repeated sets by using a set of sets return set(frozenset(k) for k in final_combinations)
def t(self, testname, type): output = str(main([1, type, "../testFiles/" + testname + ".txt"])) cost = float(output.split("\n")[-1]) with open("../testFiles/" + testname + ".out", 'r') as f: expected = f.readlines() expected_cost = float(expected[-1]) self.assertEqual(cost, expected_cost)
def animation(): solver.main() draw_unsolved(grid) screen.blit(title, (width / 2 - title.get_width() / 2, 25)) load_text = "Solving..." loading = load_font.render(load_text, True, BLACK) screen.blit(loading, (352.5, 735)) for run in solver.solved_values: for cell in run: draw_board() row = cell.column col = cell.row value = my_font.render(str(cell.value), True, BLUE) screen.blit(value, (125 + (row * 600 / 9), 110 + (col * 600 / 9))) pygame.draw.rect(screen, RED, (100 + (row * 600 / 9), 100 + (col * 600 / 9), 66, 66), 2) pygame.display.flip() sleep(0.25)
def get_use_combinations(use_flags, req_use): """ For given use flags and required use combination It uses random methods to generate valid yet random combinations of USE flags to build/test the package """ # use_flags is a string by default use_flags = [k.replace('-', '').replace('+', '') for k in use_flags.split()] # List to store final generated USE flag combinations final_combinations = [] # Absolute values of flags from the required use variable req_flags = [] # Sat solver determines all valid combinations of req_use req_solns = solver.main(req_use) # Fill in req_flags from any of the solutions([] in case of # no req_use variable) for signed_flag in req_solns[0]: req_flags.append(abs_flag(signed_flag)) # Sort all cmbinations on the number of enabled USE flags for i, soln in enumerate(req_solns): req_solns[i] = (sum(1 for k in soln if k[0] != '-'), soln) req_solns.sort(key=lambda tup: tup[0]) # use_flags are those that weren't in req_flags, thus both # sets are now mutually exclusive req_flags = set(req_flags) use_flags = set(use_flags) - req_flags # Combination number one: Minimum possible USE flags enabled tmp_use = ["-" + k for k in use_flags] + req_solns[0][1] final_combinations.append(tmp_use) # Combination number two: Maximum possible USE flags enabled tmp_use = [k for k in use_flags] + req_solns[-1][1] final_combinations.append(tmp_use) # Combination number three: Random + Random bias = random.randrange(0, 10) # Number between 0 and 9 tmp_use = [("-" if random.randrange(0, 10) <= bias else "") + k for k in use_flags] tmp_use += req_solns[random.randrange(0, len(req_solns))][1] final_combinations.append(tmp_use) # Combination number three: Random + Random bias = random.randrange(0, 10) # Number between 0 and 9 tmp_use = [("-" if random.randrange(0, 10) <= bias else "") + k for k in use_flags] tmp_use += req_solns[random.randrange(0, len(req_solns))][1] final_combinations.append(tmp_use) # Remove repeated sets by using a set of sets return set(frozenset(k) for k in final_combinations)
def get_json_response(cfg): addresses = cfg['addresses'] cfg['addresses'] = [(float(x), float(y)) for (x, y) in addresses] cfg['depot'] = int(cfg['depot']) cfg['num_vehicles'] = int(cfg['num_vehicles']) demands = cfg['demands'] cfg['demands'] = list(map(int, cfg['demands'])) cfg['vehicle_capacities'] = list(map(int, cfg['vehicle_capacities'])) result = sv.main(cfg) json_response = json.dumps(result, sort_keys=True) return json_response
def timeOut(num_list, target, solution_generator): has_Quit = input( "\n\n\t\t\tEnter to play again, S to solve, \n\tD to find a solution that you missed, or any other key to quit. " ).lower() if has_Quit == "": main() return if has_Quit == "d": answer = "" while answer == "": answer = next(solution_generator) print(answer) timeOut(num_list, target, solution_generator) return if has_Quit == "s": solver.main(num_list, target) timeOut(num_list, target, solution_generator) return os.system('clear')
def solve(board): drawboard(solver.main(board))
print "not zero label train data : %d" % sum(train_y!=0) print "total number of validation data : %d" % validation_y.shape[0] print "not zero label validation data : %d" % sum(validation_y!=0) return best_val_y, test_y if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], 'hj:t:', ['type=', 'jobs=', 'help']) except getopt.GetoptError, err: print str(err) usage() sys.exit(2) n_jobs = 1 type = 'unit' for o, a in opts: if o in ('-h', '--help') : usage() sys.exit(1) elif o in ('-t', '--type') : type = a else: print 'invalid parameter:', o usage() sys.exit(1) solver.main(nn_solver, type = type, dimreduce_func = feature_reduction.undo) solver.main(nn_solver, gap_month=2, type=type, dimreduce_func = feature_reduction.undo) evaluate.mergeoutput()
def test_main_returns_1_if_error_solving_equation(self): self.mock_solve.side_effect = ValueError('foo') found = MOD.main('bar') # should not raise! expected = 1 self.assertEqual(found, expected)
from solvers.justApartments import setup, take_turn from solver import main if __name__ == "__main__": main("training1", setup, take_turn)
def test_main_prints_ValueError_message_if_solve_fails(self): self.mock_solve.side_effect = ValueError('foo') with mock.patch.object(MOD, 'print') as mock_print: MOD.main('bar') # should not raise! mock_print.assert_called_once_with('foo', file=sys.stderr)
def test_main_returns_0_if_equation_solved(self): found = MOD.main('1 + 1') # should not raise! expected = 0 self.assertEqual(found, expected)
def test_main_prints_solve_output(self): with mock.patch.object(MOD, 'print') as mock_print: MOD.main('foo') mock_print.assert_called_once_with(self.mock_solve.return_value)
from tkinter import * from tkinter import ttk import timer import solver if __name__ == "__main__": window = Tk() window.title("Rubik Cube") window.geometry("1366x768") tabctrl = ttk.Notebook(window) tabA = ttk.Frame(tabctrl) tabB = ttk.Frame(tabctrl) solver.main(tabA) x = Frame(tabB, width=950, height=670) x.place(relx=0.5, rely=0.5, anchor="center") timer.main(x) tabctrl.add(tabA, text="Solver") tabctrl.add(tabB, text="Timer") tabctrl.pack() window.mainloop()
from solvers.utilities import setup, take_turn, SETTINGS from solver import main, pretty_print if __name__ == "__main__": SETTINGS.BUILDING.REQ_MAX_VACANCIES = 14 SETTINGS.BUILDING.REQ_MIN_HOUSING_QUEUE = 5 SETTINGS.UPGRADE.FUNDS_THRESHOLD = 23000 SETTINGS.UPGRADE.WAIT_FOR_UPGRADE = False SETTINGS.UPGRADE.PRIORITY = { 'Apartments': ['SolarPanel', 'Insulation', 'Caretaker', 'Playground', 'Charger'], 'ModernApartments': ['Insulation', 'Playground', 'SolarPanel', 'Caretaker', 'Charger'], 'EnvironmentalHouse': ['SolarPanel', 'Insulation', 'Caretaker'], 'LuxuryResidence': ['SolarPanel', 'Caretaker', 'Regulator', 'Playground'], 'Cabin': [], 'HighRise': ['Playground', 'Charger', 'Caretaker', 'Insulation'] } SETTINGS.UPGRADE.CHARGER_ONLY_ON_MALL = True scores = [main("training2", setup, take_turn) for i in range(5)] print(' ') pretty_print() print(' ') print('Max: {}\tAvg: {}'.format(max(scores), sum(scores) / len(scores)))
skipped = 0 total = 0 for i in range(len(files)): file = files[i] # print(file) if file[:-3] in firstPositions: skipped += 1 total += scores[file[:-3]] continue try: count += 1 for _ in range(4): sys.stdout.write("\b") sys.stdout.write(str(count).zfill(4)) sys.stdout.flush() res = solver.main(file) total += res[2] if res[1]: if res[0] not in updates: updates[res[0]] = 0 updates[res[0]] += 1 improved += 1 except KeyboardInterrupt: stored_exception = sys.exc_info() i -= 1 count -= 1 for _ in range(13): sys.stdout.write("\b") sys.stdout.write("Interrupted - Started: 0000") sys.stdout.flush() for _ in range(13):
def testMain(self): self.assertEqual(solver.main("a b c"), [['b', 'c', 'a']]) self.assertEqual(solver.main("?? ( a b c )"), [ ['-b', '-c', '-a'], ['-b', '-c', 'a'], ['-b', 'c', '-a'], ['b', '-c', '-a'] ]) self.assertEqual(solver.main("a !b ^^ (b c) ?? (c d)"), [['-d', '-b', 'c', 'a']])
#strategy.diversify() strategy.fill_up(11, 'ModernApartments') strategy.cold() strategy.closed() def bottom(scores): return 'Max: {}\tAvg: {:10.2f}'.format(max(scores), sum(scores) / len(scores)) def nop(): pass def alt(): SETTINGS.UPGRADE.SAVE_FOR_UPGRADE = True def reprio(): name = 'HighRise' SETTINGS.UPGRADE.LOW_PRIORITY[name].insert(0, SETTINGS.UPGRADE.PRIORITY[name].pop()) def reset(): SETTINGS.MAINTENANCE.THRESHOLD['Other'] = 37 def grow(): SETTINGS.MAINTENANCE.THRESHOLD['Other'] += 1 version = [nop] + [add('Apartments')] * 5 output = [] for v in version: v() output += ['--------------------- {} ---------------------'.format(v.__name__)] scores = [main(MAP_NAME, setup, take_turn) for i in range(RUNS)] output += [' ', pretty(), ' ', bottom(scores)] forget() print('\n'.join(output))
def test_main_calls_solve_with_input(self): MOD.main('foo') self.mock_solve.assert_called_once_with('foo')
def btnSimulate_clicked(self): n = float(self.box_n.text()) A = float(self.box_A.text()) E0 = float(self.box_E0.text()) COb = float(self.box_COb.text()) CRb = float(self.box_CRb.text()) DO = float(self.box_DO.text()) DR = float(self.box_DR.text()) ks = float(self.box_ks.text()) alpha = float(self.box_alpha.text()) Cd = float(self.box_Cd.text()) Ru = float(self.box_Ru.text()) params = [n, A, E0, COb, CRb, DO, DR, ks, alpha] CdRu = [Cd, Ru] self.progressBar.setEnabled(True) if self.Et_type == "SCV": nt = self.t.shape[0] # number of time elements nE = self.E.shape[ 1] # number of potential waveforms (E for SCV or scan rates for CVs) self.i = np.zeros([nt, nE]) self.statusBar().showMessage("Simulating") for e in range(0, nE): self.progressBar.setValue(0) self.i[:, e], self.x, self.cR, self.cO = sol.main( self.t, self.E[:, e], self.bc_type, params, CdRu, self.progressBar) self.progressBar.setValue(100) self.statusBar().showMessage("Simulation " + str(e + 1) + "/" + str(nE) + " finished") self.statusBar().showMessage("Simulation finished") self.btnPlot.setEnabled(True) self.btnAnimate.setEnabled(True) self.actionSave_Current.setEnabled(True) self.actionSave_Waveform.setEnabled(True) self.actionSave_O.setEnabled(False) self.actionSave_R.setEnabled(False) self.actionSave_x.setEnabled(False) return if self.multSR == True: # To simulate CVs with multiple scan rates nt = self.t.shape[0] nsr = np.size(self.sr) self.i = np.zeros([nt, nsr]) self.statusBar().showMessage("Simulating") for e in range(0, nsr): self.progressBar.setValue(0) self.i[:, e], self.x, self.cR, self.cO = sol.main( self.t[:, e], self.E, self.bc_type, params, CdRu, self.progressBar) self.progressBar.setValue(100) self.statusBar().showMessage("Simulation " + str(e + 1) + "/" + str(nsr) + " finished") self.statusBar().showMessage("Simulation finished") self.btnPlot.setEnabled(True) self.btnAnimate.setEnabled(True) self.actionSave_Current.setEnabled(True) self.actionSave_Waveform.setEnabled(True) self.actionSave_O.setEnabled(False) self.actionSave_R.setEnabled(False) self.actionSave_x.setEnabled(False) return self.statusBar().showMessage("Simulating.") self.i, self.x, self.cR, self.cO = sol.main(self.t, self.E, self.bc_type, params, CdRu, self.progressBar) self.statusBar().showMessage("Simulation finished") self.progressBar.setValue(100) self.btnPlot.setEnabled(True) self.btnAnimate.setEnabled(True) self.actionSave_Current.setEnabled(True) self.actionSave_Waveform.setEnabled(True) self.actionSave_O.setEnabled(True) self.actionSave_R.setEnabled(True) self.actionSave_x.setEnabled(True) self.multSR = False
def test_joins_argv_input_into_equation_str_if_no_input(self): with mock.patch.object(MOD, 'sys') as mock_sys: mock_sys.argv = ['script.py', 'foo'] MOD.main() self.mock_solve.assert_called_once_with('foo')