def loadLevelPushButtonClicked(self): levelPathText = self.levelPathLineEdit.text() newProblem = Problem( '/Users/so/Desktop/Y2S2/AI/Lab1 - UnblockMe/Levels/' + levelPathText) self._controller.setProblem(newProblem) self.drawTable(newProblem.getInitialState())
def plotACO(self): p = Problem() controller = Controller(self.__nrOfIndividuals, p.getSize(), self.__nrOfEvaluations) fitnesses = [] for i in range(self.__nrOfRuns): sol = controller.runAlgorithm() permSolution = sol[0] print(sol[1]) fitnesses.append(sol[1]) m = np.mean(fitnesses, axis=0) std = np.std(fitnesses, axis=0) means = [] stddev = [] for i in range(self.__nrOfRuns): means.append(m) stddev.append(std) plt.plot(range(self.__nrOfRuns), means) plt.plot(range(self.__nrOfRuns), stddev) plt.plot(range(self.__nrOfRuns), fitnesses) plt.show()
def verifyConfiguration(self): """ Verify compatibility of configuration. """ Problem.verifyConfiguration(self) self.formulation.verifyConfiguration() return
def __initUI(self): self.parent.title("AI: Sudoku Solver") self.pack(fill=BOTH) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT + 10) self.easy_problem = Problem(self.canvas, 0, DELAY, random.randint(0, 1), setting = "easy") self.hard_problem = Problem(self.canvas, 0, DELAY, random.randint(0, 1), setting = "hard") self.problem = None # Set this by click button # Initialize each cell in the puzzle for i in range(1, 10): for j in range(1, 10): self.item = self.canvas.create_text( MARGIN + (j - 1) * SIDE + SIDE / 2, MARGIN + (i - 1) * SIDE + SIDE / 2, text='', tags="numbers", fill="black", font=("Helvetica", 12) ) self.item = self.canvas.create_text(40, 490, text='Count :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(95, 490, text='', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(170, 490, text='Average :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(225, 490, text='',fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(320, 490, text='Ranking :',fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(370, 490, text='', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(420, 490, text='Total :', fill="black", font=("Helvetica", 13)) self.item = self.canvas.create_text(460, 490, text='', fill="black", font=("Helvetica", 13)) self.canvas.pack(fill=BOTH, side=TOP) self.start_button1 = Button(self, text="__Hard__", command=self.__start_hard_solver) self.start_button2 = Button(self, text="__Easy__", command=self.__start_easy_solver) self.start_button2.pack(side=LEFT) self.start_button1.pack(side=RIGHT) #self.start_button2.config(state="disabled") self.__draw_grid()
def main(): theta = np.random.randn(6, 1) p = Problem("database.txt") #x = p.getX() y = p.getY() c = Controller(10, p) #x_b = np.c_[np.ones((len(x), 1)), x] ''' #theta, cost_history, theta_history = c.gradientDescent(theta, x_b) theta, cost_history = c.stochasticGradientDescent(theta) error = c.getError(theta) print("Theta:") print(theta[0][0]) print("Theta1:") print(theta[1][0]) print("Theta2:") print(theta[2][0]) print("Theta3:") print(theta[3][0]) print("Theta4:") print(theta[4][0]) print("Error:") print(error) ''' X = 2 * np.random.rand(100, 5) #y = 4 +3 * X+np.random.randn(100,1) print(X) print("bine") print("bine") print("bine") print(y)
def check(self, input): self.lbl_message.clear() self.edit_input.clear() self.problem.check(input) if self.problem.result == "ValueError": message = "Error: Bad input." if self.problem.attempt > -1: message += (" " * 5 + "Attempt " + str(self.problem.attempt + 1) + "/" + str(MAX_ATTEMPTS) + "." + " " * 5 + "Previous answers: " + ", ".join(self.problem.previous_answers)) self.lbl_message.setText(message) elif self.problem.result == "correct": self.lbl_message.setText("Correct! Moving to next question.") self.problem = Problem() self.lbl_statement.setText(self.problem.statement) elif self.problem.result == "incorrect": if self.problem.attempt == MAX_ATTEMPTS - 1: self.problem.pose() self.lbl_statement.setText(self.problem.statement) self.lbl_message.setText( "Incorrect. All attempts used. Numbers changed.") else: self.lbl_message.setText( "Incorrect." + " " * 5 + "Attempt " + str(self.problem.attempt + 1) + "/" + str(MAX_ATTEMPTS) + "." + " " * 5 + "Previous answers: " + ", ".join(self.problem.previous_answers))
def __init__(self, name="timedependent"): """ Constructor. """ Problem.__init__(self, name) self._loggingPrefix = "PrTD " return
def __init__(self, name="greensfns"): """ Constructor. """ Problem.__init__(self, name) self._loggingPrefix = "PrGF " return
def search(iterations, population, low_bound, high_bound, max_vel, C1, C2, topology, pso_type): problem = Problem() fitness = [] pop = create_population(population) collection = list(enumerate(pop, start=0)) gbest = update_global_best(pop) lbest = gbest fbest = gbest for ite in xrange(iterations): for i, particle in collection: if topology == "local": lbest = update_local_best(pop, i, lbest) update_velocity(particle, lbest, max_vel, C1, C2, ite, pso_type) elif topology == "focal": fbest = update_local_best(pop, i, fbest) update_velocity(particle, fbest, max_vel, C1, C2, ite, pso_type) else: update_velocity(particle, gbest, max_vel, C1, C2, ite, pso_type) update_position(particle, low_bound, high_bound) particle.cost = problem.sphere(particle.position) update_personal_best(particle) gbest = update_global_best(pop, gbest) print "Iteration: ", ite, "Fitness: ", gbest.cost fitness.append(gbest.cost) return gbest, fitness
def start(self): filename = "in.txt" probability = 0.01 populationSize = 50 noOfIterations = 1000 problem = Problem(filename) A = problem.getA() subsets = problem.getSubsets() # print(A, subsets) individSize = len(A) individ = Individ(individSize, A, A, subsets) population = Population(populationSize) population.computePopulation(A, individSize, subsets) algorithm = Algorithm(problem, population) graded, fitnessOptim, individualOptim, avgfitness = algorithm.run( noOfIterations, probability, individ) print('Result:\n After %d iterations \n Fitness Optim: %d' % (noOfIterations, fitnessOptim)) print(" Individual Optim:" + str(individualOptim)) meanValue, standardDeviation = algorithm.statistics() print("Mean Value: " + str(meanValue)) print("Standard Deviation: " + str(standardDeviation)) algorithm.getPlot(avgfitness)
def main(): filename = "in.txt" p = Problem(filename) graph, vertices = p.readFromFile() # PARAMETERS: noIteratii = 10 # number of particles noParticles = 10 # individual size dimParticle = len(graph) # specific parameters for PSO w = 1.0 c1 = 1.0 c2 = 2.5 sizeOfNeighborhood = 3 P = population(noParticles, dimParticle) # we establish the particles' neighbors neighborhoods = selectNeighbors(P, sizeOfNeighborhood) for i in range(noIteratii): P = iteration(P, neighborhoods, c1, c2, w / (i + 1)) best = 0 for i in range(1, len(P)): if P[i].getFitness() < P[best].getFitness(): best = i fitnessOptim = P[best].getFitness() individualOptim = P[best].getPosition() print("fitnessOptim " + str(fitnessOptim)) print("individualOptim " + str(individualOptim))
def preIn(): prein = PreIn() p = Problem() tree = p.buildTree(prein.preorder.raw_data[0].split(','), prein.inorder.raw_data[0].split(',')) prein.showResult = True prein.traversal = tree.getTreeRepresentation(order='post') return render_template('prein.html', form=prein)
def main(): problem = Problem() controller = Controller() ui = UI(controller) problem.loadProblem() controller.loadParameters(problem) ui.run()
class Controller(): def __init__(self): self.problem = Problem() def printState(self): self.problem.printState() def getProblem(self): return self.problem
def _configure(self): """ Set members based using inventory. """ Problem._configure(self) self.elasticPrestep = self.inventory.elasticPrestep self.formulation = self.inventory.formulation self.checkpointTimer = self.inventory.checkpointTimer return
def __init__(self, problemFile, paramFile, toBe=False): self._problem = Problem(problemFile) self._dimParticle = len(self._problem.getVertices()) self._noPopulation, self._sizeOfNeighborhood, self._w, self._c1, self._c2 = 0, 0, 0, 0, 0 self.loadParameters(paramFile) self._population = Swarm(self._noPopulation, self._dimParticle, self._problem) self._neighborhoods = self.selectNeighbors() self._toBeDrawn = toBe
def postIn(): postin = PostIn() p = Problem() tree = p.buildTreeFromPostOrderAndInorder( postin.postorder.raw_data[0].split(','), postin.inorder.raw_data[0].split(',')) postin.showResult = True postin.traversal = tree.getTreeRepresentation(order='pre') return render_template('postin.html', form=postin)
def __init__(self, state, parent=None, action=None, path_cost=0): self.state = state self.parent = parent self.action = action self.path_cost = path_cost self.heuristic_cost = Problem.manhattan_distance(self) if Problem.heuristic == "Manhattan-Distance" \ else Problem.euclidean_distance(self) self.a_star_score = self.path_cost + self.heuristic_cost self.priority = (self.a_star_score, Problem.priority[action])
def _configure(self): """ Set members based using inventory. """ Problem._configure(self) self.faultId = self.inventory.faultId self.formulation = self.inventory.formulation self.checkpointTimer = self.inventory.checkpointTimer return
def _configure(self): """ Set members based using inventory. """ Problem._configure(self) self.elasticPrestep = self.inventory.elasticPrestep self.formulation = self.inventory.formulation self.progressMonitor = self.inventory.progressMonitor self.checkpointTimer = self.inventory.checkpointTimer return
def __init__(self): self.__problem = Problem() self.__dimPopulation = 100 self.__dimIndividual = 2 self.__min = self.__problem.getMinVal() self.__max = self.__problem.getMaxVal() self.__population = Population(self.__dimPopulation, self.__dimIndividual, self.__problem.getInitialSet()) self.__x = 0
def initialize(self): problem = Problem() parameters = Parameters() problem_type = parameters.problem_type low_bound, high_bound = parameters.set_bounds(problem_type) self.position = np.random.uniform(low_bound, high_bound, parameters.dimension) self.velocity = np.random.uniform(parameters.min_vel, parameters.max_vel, parameters.dimension) self.cost = problem.cost_function(self.position) self.best_position = self.position[:] self.best_cost = self.cost
def init(v0, T, dt, N, parameters): problem = Problem(parameters) problem.set_initial_condition(v0); c = Solver(problem) c.set_timestep(dt) v = c.solve(T) time = linspace(0,dt*N,N); return time, v
def __init__(self): try: n = int(input("Input the size of the board (implicit n=4)")) except: print("Invalid number. Size set to implict: 4.") n = 4 matrix = np.zeros((n, n), dtype=int).tolist() self.__initialState = Matrix(n, matrix) self.__problem = Problem(self.__initialState) self.__controller = Controller(self.__problem)
def merge(self, lengths, demands): problem = Problem(stockLength=self.descriptors.stockLength) for i, length in enumerate(lengths): if i == len(lengths) - 1 or length != lengths[i + 1]: order = Order(length, demands[i]) problem.addOrder(order) else: demands[i + 1] += demands[i] return problem
def main(): """ Main method, where the magic is done. This method creates and initializes the original state. Then, applying the selected search algorithm, it calculates and it writes the correct solution. :return: """ parser = argparse.ArgumentParser() parser.add_argument('-a', '--algorithm', required=True, type=str, default='DFS', help='Set the search algorithm desired.') parser.add_argument('-d', '--depth', default=9, type=int, help='Set the maximum depth.') parser.add_argument('-i', '--increase', default=1, type=int, help='Set the increase in each iteration.') parser.add_argument( '-r', '--random', default=False, type=bool, help='Initial state configuration is randomly generated.') parser.add_argument('-f', '--file', default='../terrain.txt', type=str, help='Route to load your initial state configuration.') parser.add_argument('-o', '--output', default='successors.txt', type=str, help='File to write the solution.') args = parser.parse_args() terrain = State(0, 0, 0, 0, 0, 0, 0) # Initial state. Initialized at 0. operations = Problem(0, 0, args.file, terrain) if args.random: # Generate the terrain randomly operations.generate_terrain(terrain) else: if operations.file_format_correct(): operations.read_file(terrain) else: print("File {} has not a valid format.".format(args.file)) exit(1) # Search algorithm to calculate the solution sol = Search_Algorithm().search(operations, args.algorithm, args.depth, args.increase) if sol is None: print('No se ha encontrado una soluciĆ³n') else: operations.write_file(sol, args.output)
def __init__(self, sizeOfParticle): self._initialGraph = Problem("in.txt").getGraph() # self._initialVertices = Problem("in.txt").getVertices() self._initialDictionary = Problem("in.txt").getDictionary() self._sizeOfParticle = sizeOfParticle self._position = self.getRandom() self._fitness = None self.evaluate() self.velocity = [0 for x in range(sizeOfParticle)] self._bestPosition = self._position.copy() self._bestFitness = self._fitness
class UI: def __init__(self): self.__initC = Configuration([-1] * 4) self.__p = Problem(self.__initC) self.__ctrl = Controller(self.__p) self.__n = 4 def printMenu(self): str = '' str += "0 - exit \n" str += "1 - read the number of queens \n" str += "2 - find a solution with DFS \n" str += "3 - find a soultion with Greedy \n" print(str) def readCommand(self): n = 4 try: print("Input the number of queens") n = int(input("n = ")) except: print("Invalid number, the implicit value is 4.") n = 4 self.__initC = Configuration([-1] * n) self.__p = Problem(self.__initC) self.__ctrl = Controller(self.__p) self.__n = n def findSolDFS(self): startClock = time() print(str(self.__ctrl.DFS(self.__p.getRoot(), self.__n))) print('execution time = ', time() - startClock, " seconds") def findSolGreedy(self): startClock = time() print(str(self.__ctrl.greedy(self.__p.getRoot(), self.__n))) print('execution time = ', time() - startClock, " seconds") def run(self): run = True self.printMenu() while run: try: command = int(input(">> ")) if command == 0: run = False elif command == 1: self.readCommand() elif command == 2: self.findSolDFS() elif command == 3: self.findSolGreedy() except: print("Invalid command!")
def checkpoint(self): """ Save problem state for restart. """ Problem.checkpoint() # Save state of this object raise NotImplementedError, "TimeDependent::checkpoint() not implemented." # Save state of children self.formulation.checkpoint() return
def readCommand(self): n = 4 try: print("Input the number of queens") n = int(input("n = ")) except: print("Invalid number, the implicit value is 4.") n = 4 self.__initC = Configuration([-1] * n) self.__p = Problem(self.__initC) self.__ctrl = Controller(self.__p) self.__n = n
def main(): p = Problem() controller = Controller(15, p.getSize(), 100) permSolution = controller.runAlgorithm() finalSolution = p.giveFinalSolution(permSolution[0]) validator = Validator(1000, 30, 40) validator.plotACO for i in range(len(finalSolution)): print(finalSolution[i])
def verifyConfiguration(self): """ Verify compatibility of configuration. """ Problem.verifyConfiguration(self) self.formulation.verifyConfiguration() if not "numImpulses" in dir(self.source) or not "numComponents" in dir(self.source): raise ValueError("Incompatible source for green's function impulses " "with id '%d' and label '%s'." % \ (self.source.id(), self.source.label())) return
def reconfigure(self): size = 5 try: print( "Input the size of the board and number of queens (implicit 5)" ) size = int(input("size = ")) except: print("Invalid input, implicit value is still in place") self._initialConfig = Configuration(size) self._problem = Problem(self._initialConfig) self._controller = Controller(self._problem)
def verifyConfiguration(self): """ Verify compatibility of configuration. """ Problem.verifyConfiguration(self) self.formulation.verifyConfiguration() if not "numImpulses" in dir(self.source) or not "numComponents" in dir( self.source): raise ValueError("Incompatible source for green's function impulses " "with id '%d' and label '%s'." % \ (self.source.id(), self.source.label())) return
def fitness(self): """ Determine the fitness of an individual. Lower is better.(min problem) For this problem we have the Rastrigin function individual: the individual to evaluate """ S = 0 for a in range(self.__size): for b in range(self.__size): S += Problem.w(a, b) * Problem.d(self.__chromosome[a], self.__chromosome[b]) return S
def next_problem(self): assert(self._v_message) # FIXME l = len(self._collection) r = randint(0, l - 1) f = open(join(self._directory, self._collection[r])) self._problem = Problem(f.read()) transform = Transform() self._to_board = transform.to_board self._from_board = transform.from_board self._fix_color = transform.fix_color self._model = BoardModel() if self.to_move() == Color.B: self._v_message.set('Black to move') else: self._v_message.set('White to move') self._model.setup_position(self._problem.get_setup()) self._board_widget.update_board()
def main(): """ Main method, where the magic is done. This method creates and initializes the original state. Then, applying the selected search algorithm, it calculates and it writes the correct solution. :return: """ parser = argparse.ArgumentParser() parser.add_argument('-a', '--algorithm', required=True, type=str, default='DFS', help='Set the search algorithm desired.') parser.add_argument('-d', '--depth', default=9, type=int, help='Set the maximum depth.') parser.add_argument('-i', '--increase', default=1, type=int, help='Set the increase in each iteration.') parser.add_argument('-r', '--random', default=False, type=bool, help='Initial state configuration is randomly generated.') parser.add_argument('-f', '--file', default='../terrain.txt', type=str, help='Route to load your initial state configuration.') parser.add_argument('-o', '--output', default='successors.txt', type=str, help='File to write the solution.') args = parser.parse_args() terrain = State(0, 0, 0, 0, 0, 0, 0) # Initial state. Initialized at 0. operations = Problem(0, 0, args.file, terrain) if args.random: # Generate the terrain randomly operations.generate_terrain(terrain) else: if operations.file_format_correct(): operations.read_file(terrain) else: print("File {} has not a valid format.".format(args.file)) exit(1) # Search algorithm to calculate the solution sol = Search_Algorithm().search(operations, args.algorithm, args.depth, args.increase) if sol is None: print('No se ha encontrado una soluciĆ³n') else: operations.write_file(sol, args.output)
class BoardController(object): def __init__(self): self._v_message = None self._model = None self._to_board = lambda x, y: (x, y) self._from_board = lambda x, y: (x, y) self._fix_color = lambda c: c self._board_widget = None self._directory = None self._collection = None self._problem = None def register_message_var(self, v): self._v_message = v def register_board_widget(self, widget): self._board_widget = widget def get_stones(self): stones = self._model.get_stones() def stone_to_board((nx, ny, s)): nxb, nyb = self._to_board(nx, ny) c = self._fix_color(s) return (nxb, nyb, c) return map(stone_to_board, stones) def get_ko(self): ko = self._model.get_ko() if ko: return self._to_board(*ko) else: return None def allowed(self, nxb, nyb): nx, ny = self._from_board(nxb, nyb) return self._model.allowed(nx, ny) def add(self, nxb, nyb): assert(self._v_message) nx, ny = self._from_board(nxb, nyb) self._model.do_move(nx, ny) self._board_widget.update_board() if not self._problem.is_over(): reply = self._problem.get_reply(nx, ny) # TODO if self._problem.is_over(): if self._problem.is_wrong(): self._v_message.set("Wrong") else: self._v_message.set("Right") else: self._v_message.set('') if reply is None: return self._model.do_move(*reply) self._board_widget.update_board() def to_move(self): return self._fix_color(self._model.to_move()) def last_move(self): lm = self._model.last_move() if lm: lmx, lmy = lm return self._to_board(lmx, lmy) else: return None def open_collection(self, directory): # FIXME self._directory = directory self._collection = [f for f in listdir(directory) if isfile(join(directory, f))] def next_problem(self): assert(self._v_message) # FIXME l = len(self._collection) r = randint(0, l - 1) f = open(join(self._directory, self._collection[r])) self._problem = Problem(f.read()) transform = Transform() self._to_board = transform.to_board self._from_board = transform.from_board self._fix_color = transform.fix_color self._model = BoardModel() if self.to_move() == Color.B: self._v_message.set('Black to move') else: self._v_message.set('White to move') self._model.setup_position(self._problem.get_setup()) self._board_widget.update_board()
def test(i, solver, choice, problem): xtol = 1E-12 N = 2**i mesh = UnitSquareMesh(N, N, 'crossed') n_cells = mesh.num_cells() n_obtuse_cells = len(obtuse_cells(mesh)) if problem == "point": A = array([1.0, 0.0]) point_distance = Problem(MyPoint(A)) elif problem == "line": A = array([0., 0.]) B = array([1., 0.]) point_distance = Problem(Segment(A, B)) if solver == "Q1": # set up the linear problem V = FunctionSpace(mesh, "CG", 1) u = Function(V) u_exact = Function(V) fixed_dofs = [] point_distance.init(u, fixed_dofs) point_distance.exact_solution(u_exact) solver1 = Geometric(V) start = clock() n_sweeps = solver1.solve(u, fixed_dofs, xtol=xtol) stop = clock() - start l1 = assemble(abs(u - u_exact)*dx) l2 = assemble((u - u_exact)**2*dx) # set up the quadratic problem W = FunctionSpace(mesh, "CG", 2) v = interpolate(u, W) v_exact = Function(W) fixed_dofs = [] point_distance.init(v, fixed_dofs) point_distance.exact_solution(v_exact) solver2 = Quadratic(W, choice) start = clock() n_sweeps = solver2.solve(v, fixed_dofs, xtol=xtol, order_vector=v.vector()) stop = clock() - start if solver == "Q2": # set up the linear problem V = FunctionSpace(mesh, "CG", 1) u = Function(V) u_exact = Function(V) fixed_dofs = [] point_distance.init(u, fixed_dofs) point_distance.exact_solution(u_exact) solver1 = Geometric(V) n_sweeps = solver1.solve(u, fixed_dofs, xtol=xtol) # set up the quadratic problem W = FunctionSpace(mesh, "CG", 2) v = interpolate(u, W) xxx = Function(W) xxx.vector()[:] = v.vector().array() v_exact = Function(W) Fixed_dofs = [] point_distance.init(v, Fixed_dofs) point_distance.exact_solution(v_exact) #print fixed_dofs #for i in range(W.dim()): # print i, xxx.vector()[i], v.vector()[i], # if i in fixed_dofs: # print "<--" # else: # print solver2 = Quad(W, choice) start = clock() n_sweeps = solver2.solve(v, Fixed_dofs, xtol=xtol) stop = clock() - start if solver == "Q3": # set up the quadratic problem W = FunctionSpace(mesh, "CG", 2) v = Function(W) v_exact = Function(W) fixed_dofs = [] point_distance.init(v, fixed_dofs) point_distance.exact_solution(v_exact) solver2 = QuadraticRatic(W, choice) start = clock() n_sweeps = solver2.solve(v, fixed_dofs, xtol=xtol) stop = clock() - start if solver == "Q4": # set up the linear problem V = FunctionSpace(mesh, "CG", 1) u = Function(V) u_exact = Function(V) fixed_dofs = [] point_distance.init(u, fixed_dofs) point_distance.exact_solution(u_exact) solver1 = Geometric(V) start = clock() n_sweeps = solver1.solve(u, fixed_dofs, xtol=xtol) stop = clock() - start l1 = assemble(abs(u - u_exact)*dx) l2 = assemble((u - u_exact)**2*dx) # set up the quadratic problem W = FunctionSpace(mesh, "CG", 2) v = Function(W) v_exact = Function(W) fixed_dofs = [] point_distance.init(v, fixed_dofs) point_distance.exact_solution(v_exact) order = interpolate(u, W) solver2 = Q4(W, choice) start = clock() n_sweeps = solver2.solve(v, fixed_dofs, xtol=xtol, order_u=order) stop = clock() - start l1 = assemble(abs(v - v_exact)*dx) l2 = assemble((v - v_exact)**2*dx) diff = v.vector() - v_exact.vector() diff.abs() ci = diff.max() plot(v, interactive=True, title='numeric') plot(v_exact, interactive=True, title='exact') v_exact.vector()[:] -= v.vector().array() v_exact.vector().abs() plot(v_exact, interactive=True, title='error') if choice == 0: local = "sample" else: local = "quad" print "%g %.8E %.8E %.8E %d/%d %d %g" %\ (mesh.hmin(), l1, l2, ci, n_obtuse_cells, n_cells, n_sweeps, stop) out_name = "./test_results/"+solver+"_"+local+"_"+problem+".dat" with open(out_name, "a") as out: out.write("%g %.8E %.8E %.8E %d %d %d %g\n" %\ (mesh.hmin(), l1, l2, ci, n_obtuse_cells, n_cells, n_sweeps, stop) )
from Problem import Problem from solver_vertical_motion import Solver from read_file import read_file from scitools.std import plot from numpy import linspace, array, zeros import sys v0 = 0 T = 100 dt = 0.01 N = int(T/float(dt)) parameters = read_file(sys.argv[1:]) problem = Problem(parameters) problem.set_initial_condition(v0); c = Solver(problem) c.set_timestep(dt) v = c.solve(T) v = array(v) F_d = zeros(N) for i in range(N): F_d[i] = problem.get_drag_force(v[i]) F_g = zeros(N) + problem.get_gravity_force() F_b = zeros(N) + problem.get_buoyancy_force() time = linspace(0,dt*N,N); plot(time,F_d,time,F_g,time,F_b, legend=['drag','gravity','buoyancy'])
import csv from Problem import Problem reader = csv.reader(open("A1Ratings.csv","rU")) problem=Problem() for row in reader: problem.loadline(row) average_ratings=dict(zip(problem.movienames,[('%.2f')%f for f in problem.meanRatings()])) average_ratings=sorted(average_ratings.iteritems(),key=lambda d:d[1], reverse=True) print average_ratings most_ratings=dict(zip(problem.movienames,[f for f in problem.mostRatings()])) most_ratings=sorted(most_ratings.iteritems(),key=lambda d:d[1],reverse=True) print most_ratings higher_ratings=dict(zip(problem.movienames,[('%.2f')%f for f in problem.rating4()])) higher_ratings=sorted(higher_ratings.iteritems(),key=lambda d:d[1],reverse=True) print higher_ratings rel=dict(zip(problem.movienames[1:],[('%.2f')%f for f in problem.getRelevance()])) rel=sorted(rel.iteritems(),key=lambda d:d[1],reverse=True) print rel
def __init__(self, args): """ Default constructor. """ Problem.__init__(self, self.PN, self.PT, self.PD, self.PDT, args)
#!/usr/bin/env python "Usage: python {0} <node>" from State import State from Node_Tree import Node_Tree from Node_Map import Node_Map from State_Space import State_Space from Problem import Problem import sys if len(sys.argv) != 2: print(__doc__.format(__file__)) sys.exit(1) if __name__ == "__main__": initial_state = State(Node_Map(sys.argv[1])) initial_state.objetive_nodes.append((-1)) #The frontier will never find this node, thus will never stop expanding p = Problem(State_Space(), initial_state) p.build_hash_table() p.expand_frontier()
import sys if len(sys.argv) < 7: print(__doc__.format(__file__)) sys.exit(0) if __name__ == "__main__": print "Looking for nodes " + str(sys.argv[6:]) initial_state = State(Node_Map(sys.argv[1]), sys.argv[6:]) boundary_coordinates = (sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) p = Problem(State_Space(boundary_coordinates), initial_state) p.build_hash_table() path = p.search(Searching_Strategies.BFS) if len(path)==0: print "Path not found" sys.exit(0) print "Path found! Path saved in data/solution.out" sys.stdout = open('data/solution.out','w') print "Final path to " + str(sys.argv[6:]) while (len(path)>0): print path.pop()
__author__ = 'YanChenDeng' from Problem import Problem import csv read=csv.reader(file('A1Ratings.csv','rb')) problem=Problem() for line in read: problem.loadLine(line) print 'mean rating:' print dict(zip(problem.moviesName,[('%.2f')%f for f in problem.meanRating()])) print 'rating count:' print dict(zip(problem.moviesName,[('%.2f')%f for f in problem.ratingCount()])) print 'high rating:' print dict(zip(problem.moviesName,[('%.2f')%f for f in problem.highRating()])) print 'relevance of Star Wars: Episode IV - A New Hope (1977):' print dict(zip(problem.moviesName,[('%.2f')%f for f in problem.calcRelevance('260: Star Wars: Episode IV - A New Hope (1977)')]))
__author__ = "YanChenDeng" import csv from Problem import Problem import copy reader = csv.reader(file("Assignment 2.csv", "rb")) problem = Problem() for line in reader: problem.loadTopic(line) problem.loadUserRating(line) print "Profile of User1 is:" print dict(zip(problem.topicNames, problem.generateUserProfiles(0))) print "Profile of User2 is:" print dict(zip(problem.topicNames, problem.generateUserProfiles(1))) print "Document which User1 like most is:" matchResult = problem.cloestMatches(problem.generateUserProfiles(0)) print "doc " + str(matchResult[0] + 1) + " score is:" + str(matchResult[1]) print "Document which User2 like most is:" matchResult = problem.cloestMatches(problem.generateUserProfiles(1)) print "doc " + str(matchResult[0] + 1) + " score is:" + str(matchResult[1]) print "------------------------" print "After refine topic matrix" problem.refineTopicMatrix() print "Profile of User1 is:" print dict(zip(problem.topicNames, [("%.3f") % i for i in problem.generateUserProfiles(0)])) print "Profile of User2 is:" print dict(zip(problem.topicNames, [("%.3f") % i for i in problem.generateUserProfiles(1)])) print problem.evaluateDocument(0, problem.generateUserProfiles(0)) print problem.evaluateDocumentByIDF(0, problem.generateUserProfiles(0))
print "\n******** STATISTICS *********" print "Final cost: "+ str(final_cost) if __name__ == "__main__": search_strategy = int(raw_input("Search algorithm? (BFS = 0, DFS = 1, DLS = 2, IDS = 3, UC = 4, AStar = 5)\n")) if not search_strategy in range(6): print("Invalid search algorithm. Exiting...") sys.exit(0) prune = raw_input("Execute prune? (Y/N)\n") print "Looking for nodes " + str(sys.argv[6:]) initial_state = State(Node_Map(sys.argv[1]), sys.argv[6:]) boundary_coordinates = (sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) problem = Problem(State_Space(boundary_coordinates), initial_state) problem.build_hash_table() timestamp1 = datetime.datetime.now() path = search(problem, search_strategy) print "Time taken to accomplish the search: " + str(datetime.datetime.now() - timestamp1) global number_of_generated_nodes print "Number of generated nodes: " + str(number_of_generated_nodes) sys.exit(0)
import csv from Problem import Problem reader=csv.reader(file("Assignment 3.csv","rb")) problem=Problem() index=0 for row in reader: problem.loadline(row,index) index+=1 # print problem.users # print problem.movies # print problem.matrix #Without Normalization problem.computecorelation() problem.calcuNearneibor() #test 3712(7th) #problem.predict(6) #predict movies for 3867(5th) and 89(14th) problem.predict(4) problem.predict(13) #Normalization problem.predictnormalized(4) problem.predictnormalized(13)