Ejemplo n.º 1
0
    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()
Ejemplo n.º 2
0
 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
Ejemplo n.º 3
0
def random_restart_hill_climbing(n=100):
    current_state = hill_climbing(Problem().randomize_graph())
    best_val = current_state.value()
    visited = current_state.visited
    explored = current_state.explored
    for i in range(0, n - 1):
        tmp = hill_climbing(Problem().randomize_graph())
        visited += tmp.visited
        explored += tmp.explored
        if tmp.value() < best_val:
            current_state = tmp
            best_val = current_state.value()
    current_state.set_explored(explored)
    current_state.set_visited(visited)
    return current_state
Ejemplo n.º 4
0
def main():
    problem = Problem("temperature.in", "humidity.in", "rules.in")
    c = Controller(problem)
    c.solveFuzzy()
    c.solveFuzzy()
    c.solveFuzzy()
    c.solveFuzzy()
Ejemplo n.º 5
0
    def Solve(self, problem):
        self.problem = Problem(problem)
        # self.print_problem_info()

        if self.problem.problemType == "2x2":
            return [1., 1., 1., 1., 1., 1.]
        if self.problem.problemType == "3x3" and self.problem.hasVerbal:
            solverE = SolverE(self.problem)
            anAnswer = solverE.solve()
            if solverE.total_count == 0:
                solverD = SolverD(self.problem)
                myAnswer = solverD.solve()
            else:
                myAnswer = anAnswer
        if self.problem.problemType == "3x3" and not self.problem.hasVerbal:
            if "D-" in self.problem.name:
                solverD = SolverD(self.problem)
                myAnswer = solverD.solve()
            elif "E-" in self.problem.name:
                solverE = SolverE(self.problem)
                myAnswer = solverE.solve()
            else:
                solverE = SolverE(self.problem)
                anAnswer = solverE.solve()
                if solverE.total_count == 0:
                    solverD = SolverD(self.problem)
                    myAnswer = solverD.solve()
                else:
                    myAnswer = anAnswer

        # self.test_correct_answer(myAnswer)

        return myAnswer
Ejemplo n.º 6
0
def find_idastar_route(source, target):
    def g(node):
        return node.path_cost

    def h(node):
        junction = roads[node.state]
        target = roads[goal.state]
        x = compute_distance(junction.lat, junction.lon, target.lat,
                             target.lon) / 110
        return x

    roads = load()
    #roads = load('israel.csv',0,50)
    start = Node(roads[source])
    goal = Node(roads[target])
    p = Problem(start, goal, roads)
    limit_cost = h(start)
    path = [start.state]
    while (True):
        import time
        t = time.time
        next = ida_star(path, p, start, limit_cost, f=lambda n: g(n) + h(n))
        if next == -1:
            print(t - time.time)
            return path[::-1]
        if next == math.inf:
            return None
        limit_cost = next
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 parseFile(self):
    matrices = []
    for i, line in enumerate(self):
        line = line.rstrip()
        if i == 0:
            problemTitle = line
        elif i == 1:
            problemSize = line
        elif i == 2:
            correctAnswer = line
        else:
            if not line.startswith("\t"):
                #this is a matrix
                newMatrix = Matrix(line)
                matrices.append(newMatrix)
            elif not line.startswith("\t\t"):
                #this is an object
                line = line.strip()
                newObject = Object(line)
                newMatrix.objects[line] = newObject
            else:
                #this is an attribute (key-value pair)
                line = line.strip()
                keyValue = line.split(":")
                newObject.attributes.update({keyValue[0]: keyValue[1]})

    problem = Problem(problemTitle, problemSize, correctAnswer, matrices)
    return problem
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
def main():
    D = 20
    problem = Problem('problem.txt')
    clusters = Clustering(problem, D)
    clusters.clustering()
    # print(clusters.cluster)
    aif = ArcIndexedFormulation({
        "N": [0, 1, 2, 3, 4],
        "V": [1, 2, 3, 4],
        'k': [5, 5, 5, 5],
        'c': [10, 10, 10, 10, 10],
        's0': [5, 5, 5, 5, 5],
        't': [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5],
              [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]],
        'alpha':
        0.3,
        'T':
        100,
        'U':
        1,
        'L':
        1,
        'f':
        problem.f
    })
    aif.solve()
Ejemplo n.º 11
0
 def __init__(self):
     self.__problem = Problem()
     self.__dimPopulation = 0
     self.__noOfIterations = 0
     self.readFromFile()
     self.__population = Population(self.__dimPopulation)
     self.__best = []
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
def main():

    parser = argparse.ArgumentParser(
        description='''The driver Script for Compilation''',
        epilog=
        "Usage >> ./Compiler.py -m current_domain.pddl -p current_problem.pddl -f plan_fragment"
        +
        " -t domain_templ.pdd -r prob_templ.pddl -s new_domain.pddl -q new_problem.pddl"
    )

    # Flags for the search
    parser.add_argument('-m',
                        '--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('-t',
                        '--domain_templ',
                        type=str,
                        help="Template for domain file for robot.",
                        required=True)
    parser.add_argument('-r',
                        '--prob_templ',
                        type=str,
                        help="Template for problem file for robot.",
                        required=True)
    parser.add_argument('-s',
                        '--domain_dest',
                        type=str,
                        help="Destination for the new domain file for robot.",
                        required=True)
    parser.add_argument('-q',
                        '--prob_dest',
                        type=str,
                        help="Destination for new problem file for robot.",
                        required=True)
    parser.add_argument('-f',
                        '--plan_file',
                        type=str,
                        help="Plan file.",
                        required=True)

    if not sys.argv[1:] or '-h' in sys.argv[1:]:
        print parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    # define problem object and run the required search
    try:
        pr_obj = Problem(args.model, args.problem, args.plan_file,
                         args.domain_templ, args.prob_templ, args.domain_dest,
                         args.prob_dest)
    except Exception as e:
        print("Exception: " + str(e))
Ejemplo n.º 14
0
def main():
    c = CommandLine(sys.argv)
    c.run()

    problem = Problem(c.instance())
    problem.processInstanceFiles()
    problem.print()
Ejemplo n.º 15
0
 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())
Ejemplo n.º 16
0
    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)
Ejemplo n.º 17
0
    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))
Ejemplo n.º 18
0
    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()
Ejemplo n.º 19
0
    def play(self):
        mapp = self.map.getMapState()

        # generate problem to solve
        problem = Problem(State(mapp))

        # set problem
        self.searchAlgorithm.setProblem(problem)

        # calculate running time
        start = time.time()

        # solve problem
        self.map.loadInfo("solving")
        moves = self.searchAlgorithm.solve()
        if moves != []: self.map.loadInfo("found")
        else: self.map.loadInfo("notfound")

        # stop time
        stop = time.time()

        # print some statistics
        print "Thoi gian giai quyet : %d giay" % (stop - start)
        print "So luong move la : %d" % len(moves)
        self.map.loadTime(start)

        for move in moves:
            self.map.moveBlock(move.mapp)
            self.map.loadMove()
        self.map.move = 1

        # notify that player have solve the problem
        print "AI player done playing!"
Ejemplo n.º 20
0
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)
Ejemplo n.º 21
0
def problems_list(URL):
    '''
    This functions takes a spoj problems page url, and returns a list of Problem instances.
    '''
    debug("Fetching html....")
    html_data = urllib.urlopen(URL).read()
    debug("Html fetched, prettifying results....")
    soup = BeautifulSoup(html_data, 'html.parser')
    table = soup.find('table', attrs={'class': 'problems'})
    problems_list = table.find('tbody').findAll('tr')
    debug("In the middle of parsing....")
    problems = []
    for problem in problems_list:
        col_list = problem.findAll('td')
        pid = col_list[0].string.strip()
        plink = 'http://www.spoj.com' + col_list[1].find('a').get('href')
        pname = col_list[1].find('a').string.strip()
        try:
            quality = col_list[2].find('span').find('strong').string.strip()
        except AttributeError:
            quality = 'undefined'
        users = col_list[3].find('a').string.strip()
        accuracy = col_list[4].find('a').string.strip()
        instance = Problem(pid, pname, plink, quality, users, accuracy)
        problems.append(instance)
    debug("Done!")
    return problems
Ejemplo n.º 22
0
    def get_problem(prob):
        details = SPOJScrapper.get_prob_desc(prob)
        # print details
        if details is None:
            raise Exception("Problem code invalid")

        desc = details[0]
        category_link = details[1]
        problem = Problem(prob, desc, category_link)

        current_page = category_link
        while True:
            response = urlopen(current_page)
            html = response.read()
            soup = BeautifulSoup(html, 'html.parser')
            prob_link = soup.find('a', href='/ranks/' + prob)

            if prob_link is not None:
                SPOJScrapper.set_points_and_solvers(problem, prob_link)
                return problem
            else:
                next_element = SPOJScrapper.get_next_url(soup)
                if next_element is None:
                    raise Exception("Couldn't find problem link")
                current_page = URLutil.SPOJURL + SPOJScrapper.get_next_url(
                    soup)['href']
Ejemplo n.º 23
0
def main():

    parser = argparse.ArgumentParser(
        description='''Driver script for Projection-Aware Planning''',
        epilog="Usage >> ./main.py -u 1")

    parser.add_argument('-u',
                        '--usecase',
                        type=int,
                        help="ID of the Use Case.")
    parser.add_argument('-d',
                        '--domain',
                        type=str,
                        help="(path to) domain file.")
    parser.add_argument('-p',
                        '--problem',
                        type=str,
                        help="(path to) problem file.")
    parser.add_argument('-o',
                        '--hyps',
                        type=str,
                        help="(path to) hypothesis file.")
    parser.add_argument('-r',
                        '--real_hyp',
                        type=str,
                        help="(path to) real hypothesis file.")

    if not sys.argv[1:] or '-h' in sys.argv[1:]:
        print parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    if args.usecase == 1:

        problem_instance = Problem(args.domain, args.problem)
        print PAPP(problem_instance)

    elif args.usecase == 2:

        execution_instance = Exe(args.domain, args.problem, args.hyps,
                                 args.real_hyp)

        print execution_instance.getPlan()
        print execution_instance.getProjection()

    elif args.usecase == 3:

        execution_instance = ExeHILP(args.domain, args.problem, args.hyps,
                                     args.real_hyp)

        print execution_instance.getPlan()
        print execution_instance.getProjection()

    elif args.usecase == 4:
        raise NotImplementedError

    else:
        pass
Ejemplo n.º 24
0
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)
Ejemplo n.º 25
0
def main():
    problem = Problem()
    controller = Controller()
    ui = UI(controller)

    problem.loadProblem()
    controller.loadParameters(problem)
    ui.run()
Ejemplo n.º 26
0
def new_population_production(populationSize):
    population = []
    for i in range(0, populationSize):
        chromosome = Problem()
        for node in chromosome.graph:
            node.set_color(random.choice([0, 1, 2]))
        population.append(chromosome)
    return population
Ejemplo n.º 27
0
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)
Ejemplo n.º 28
0
 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
Ejemplo n.º 29
0
def main():
    problem = Problem("../json/x4cube.json")
    fringe = Frontier()

    print("Starting test... ")
    start = time.time()
    stress_test(problem, fringe)
    print("Total time: %.11f" % (time.time() - start))
    print("\nStress test has ended.")
 def __init__(self, coin_set=None, max_chances=100):
     if not Problem.singleton_problem:
         Problem(coin_set)
     self.__population_size = 10
     self.population = self.__createInitialPopulation()
     self.best_fit = None
     self.__current_generation = 1
     self.max_chances = max_chances
     self.__same_best_chances = self.max_chances