simple artificial intelligence utilities

Overview

Simple AI

Project home: http://github.com/simpleai-team/simpleai

This lib implements many of the artificial intelligence algorithms described on the book "Artificial Intelligence, a Modern Approach", from Stuart Russel and Peter Norvig. We strongly recommend you to read the book, or at least the introductory chapters and the ones related to the components you want to use, because we won't explain the algorithms here.

This implementation takes some of the ideas from the Norvig's implementation (the aima-python lib), but it's made with a more "pythonic" approach, and more emphasis on creating a stable, modern, and maintainable version. We are testing the majority of the lib, it's available via pip install, has a standard repo and lib architecture, well documented, respects the python pep8 guidelines, provides only working code (no placeholders for future things), etc. Even the internal code is written with readability in mind, not only the external API.

At this moment, the implementation includes:

  • Search
    • Traditional search algorithms (not informed and informed)
    • Local Search algorithms
    • Constraint Satisfaction Problems algorithms
    • Interactive execution viewers for search algorithms (web-based and terminal-based)
  • Machine Learning
    • Statistical Classification

Installation

Just get it:

pip install simpleai

And if you want to use the interactive search viewers, also install:

pip install pydot flask

You will need to have pip installed on your system. On linux install the python-pip package, on windows follow this. Also, if you are on linux and not working with a virtualenv, remember to use sudo for both commands (sudo pip install ...).

Examples

Simple AI allows you to define problems and look for the solution with different strategies. Another samples are in the samples directory, but here is an easy one.

This problem tries to create the string "HELLO WORLD" using the A* algorithm:

from simpleai.search import SearchProblem, astar

GOAL = 'HELLO WORLD'


class HelloProblem(SearchProblem):
    def actions(self, state):
        if len(state) < len(GOAL):
            return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ')
        else:
            return []

    def result(self, state, action):
        return state + action

    def is_goal(self, state):
        return state == GOAL

    def heuristic(self, state):
        # how far are we from the goal?
        wrong = sum([1 if state[i] != GOAL[i] else 0
                    for i in range(len(state))])
        missing = len(GOAL) - len(state)
        return wrong + missing

problem = HelloProblem(initial_state='')
result = astar(problem)

print(result.state)
print(result.path())

More detailed documentation

You can read the docs online here. Or for offline access, you can clone the project code repository and read them from the docs folder.

Help and discussion

Join us at the Simple AI google group.

Authors

  • Many people you can find on the contributors section.
  • Special acknowledgements to Machinalis for the time provided to work on this project. Machinalis also works on some other very interesting projects, like Quepy and more.
Comments
  • Add Python 3 support

    Add Python 3 support

    Fixes #66 and other small syntax issues that prevented this from running on Python 3.x. Of course, Python 2.x should still work.

    Tests seem to still pass, but I have only used a subset of this package myself, so I can't guarantee that everything that the tests don't cover work as expected on 3.x.

    opened by anassinator 13
  • AStar algorithm is implemented incorrectly.

    AStar algorithm is implemented incorrectly.

    fringe may not contain a node with a state that is in the memory. If a new candidate node has that state, it can not be added to the fringe.

    See python-astar project for a correct implementation: https://github.com/jrialland/python-astar.

    opened by calee88 5
  • Genetic Algorithm

    Genetic Algorithm

    I have a proposal of the implementation of a Genetic Algorithm - AG. Actually I already started to implement one, but I didn't finish it yet.

    For mre information about what is that see this link: https://en.wikipedia.org/wiki/Genetic_algorithm

    An AG has a lot of functionalities and I'm planning develop that using TDD in order to make a safe development

    This algorithm willbe so helpfull for this library.

    opened by jrandson 5
  • How to limit actions to be used once in the tree

    How to limit actions to be used once in the tree

    Dear,

    I am learning AI and I am at the beginning.

    I would like to limit the use of actions to one time for each. Indeed, I have to find a subset of actions to achieve the goal, but each action can be done only once.

    How should I add that constraint to the actions ?

    from simpleai.search import SearchProblem, breadth_first, depth_first, greedy, astar
    
    class MyPuzzle(SearchProblem):
        def __init__(self, initial_state = 0):
            self.goal = 51
            super(MyPuzzle, self).__init__(initial_state)
    
        def actions(self, state):
            if(state > self.goal):
                return []
            else :
                return (1,20,30,25,21,32,65,96,30,16,25,18,75,21,1)
    
        def result(self, state, action):
            return state + action
    
        def cost(self, state, action, state2):
            return 1
    
        def is_goal(self, state):
            return state == self.goal
    
        def heuristic(self, state):
            return self.goal - state
    
    opened by AlexisTM 4
  • simpleai.search.astar not working for 8 puzzle solver (please help)

    simpleai.search.astar not working for 8 puzzle solver (please help)

    # Eight Puzzle Solver using A*
    # This code is working for few cases and for the rest it is getting into infinite loop
    # Please see main() 
    
    from simpleai.search import astar, SearchProblem
    
    class PuzzleSolver(SearchProblem):
        def __init__(self, initial):
            self.goal = '1-2-3\n4-5-6\n7-8-_'
    
            #lets create a cache for goal positions of all the values
            matrix = self.string_to_list(self.goal)
            self.goal_position = {}
            for x in '12345678_':
                self.goal_position[x] = self.get_coordinates(matrix, x)
    
            SearchProblem.__init__(self, initial_state= initial)
    
    
        #A method that gets current state of the puzzle solver
        #and returns a list of the numbers that can be moved into the empty space
        def actions(self, curr_state):
            matrix = self.string_to_list(curr_state)
            row_empty, col_empty = self.get_coordinates(matrix, '_')
            moves = []
            if row_empty > 0:
                moves.append(matrix[row_empty-1][col_empty])
            if row_empty < 2:
                moves.append(matrix[row_empty+1][col_empty])
            if col_empty > 0:
                moves.append(matrix[row_empty][col_empty-1])
            if col_empty < 2:
                moves.append(matrix[row_empty][col_empty+1])
            return moves
    
        #A method that accepts current state and action. It returns the new state
        #that results by application of the action.
        def result(self, curr_state, action):
            matrix = self.string_to_list(curr_state)
            row_empty, col_empty = self.get_coordinates(matrix, '_')
            row_action, col_action = self.get_coordinates(matrix, action)
            #swap
            matrix[row_empty][col_empty], matrix[row_action][col_action] = matrix[row_action][col_action], matrix[row_empty][col_empty]
    
            new_state = self.list_to_string(matrix)
            return new_state
    
        #Termination criteria for A*
        def is_goal(self, curr_state):
            return curr_state == self.goal
    
        #Heuristic Search: A method that returns an estimate of distance from the current state to the goal
        #using the Manhattan Distance
        def heuristic(self, curr_state):
            matrix = self.string_to_list(curr_state)
            distance = 0
            for number in '12345678_':
                row_number, col_number = self.get_coordinates(matrix, number)
                goal_row_number, goal_col_number = self.goal_position[number]
    
                distance += abs(row_number - goal_row_number) + abs(col_number - goal_col_number)
            return distance
    
        #helper methods
        def string_to_list(self, input_string):
            data = [item.split('-') for item in input_string.split('\n')]
            return data
    
        def list_to_string(self, matrix):
            w = '\n'.join(['-'.join(x) for x in matrix])
            return w
    
        def get_coordinates(self, matrix, element):
            for i, row in enumerate(matrix):
                for j, col in enumerate(row):
                    if col == element:
                        return i,j
    
            return None
    
        def solve(self):
            #invoking A*
            result = astar(self)
            path = result.path()
            action, state = path.pop(0)
            print('Initial State')
            print(state)
    
            for action, state in path:
                print('After moving ', action, 'into empty space')
                print(state)
    
            print('Goal Achieved')
    
        def cost(self, state, action, state2):
            return 1
    
    def main():
        #test cases
        initial = '1-_-2\n6-3-4\n7-5-8' #working
        #initial = '1-2-3\n6-_-4\n7-5-8'  #not working
        initial = '1-2-_\n6-3-4\n7-5-8'  # working
        initial = '_-1-2\n6-3-4\n7-5-8'  # working
        #initial = '1-6-2\n_-3-4\n7-5-8'  #not working
        initial = '1-4-5\n6-3-8\n7-2-_'  # working
        #initial = '1-4-2\n6-3-_\n7-5-8'  # not working
        initial = '1-4-5\n6-8-3\n_-2-7'  # working
        #initial = '1-4-_\n6-8-3\n5-2-7'  # not working
        initial = '1-4-5\n6-8-3\n2-7-_'  # working
        #initial = '1-4-6\n5-8-3\n2-7-_'  # not working
        initial = '7-3-4\n2-_-8\n5-1-6' #not working
    
        ps = PuzzleSolver(initial)
        ps.solve()
    
    main()
    
    
    opened by rahulcomp2000 3
  • Installing from PIP fails

    Installing from PIP fails

    Installing from PIP fails giving the following (using Python 2.7.3)

    $ sudo pip install simpleai
    Downloading/unpacking simpleai
      Running setup.py egg_info for package simpleai
        Traceback (most recent call last):
          File "<string>", line 16, in <module>
          File "/tmp/pip-build-root/simpleai/setup.py", line 9
            description=u'An implementation of AI algorithms based on aima-python',
                                                                                 ^
        SyntaxError: invalid syntax
        Complete output from command python setup.py egg_info:
        Traceback (most recent call last):
    
      File "<string>", line 16, in <module>
    
      File "/tmp/pip-build-root/simpleai/setup.py", line 9
    
        description=u'An implementation of AI algorithms based on aima-python',
    
                                                                             ^
    
    SyntaxError: invalid syntax
    
    opened by kristiank 2
  • Added missing method on BoundedPriorityQueue

    Added missing method on BoundedPriorityQueue

    When _search is called with graph_replace_when_better=True, and the node expanded () is better that the one in the fringe it tries to remove it but fails.

    opened by ganiserb 2
  • Update docs/search_problems.rst

    Update docs/search_problems.rst

    Just a pep8 fix. If the code is an initial example that a lot of people will copy & paste for reviewing, could be nice to training them on the benefits of pep8 (better to catch'em early :P ).

    opened by pmourelle 2
  • Possible security issues on line 271

    Possible security issues on line 271

    on line 271 (add_branch), I propose a encrypted return branch, by adding a randomized value before and after the "branch" or, if the returned value is a number, I recommend using a lock and key. `

    opened by K-Dub1234 1
  • It is inconvenient that states have to be hashable

    It is inconvenient that states have to be hashable

    It is inconvenient that states have to be hashable. Why not remove the restriction? OR define apis converting state to its hashable version (e.g. self.state_representation(state)) automatically, the users could focus on the raw states.

    opened by Freakwill 1
  • Flask deprecated parameter

    Flask deprecated parameter

    When Flask 1.0 was released deprecated static_path parameter was removed, and, because dependencies in requirements.txt are not pinned, the web_viewer_server stop working.

    This PR solve this situation using static_url_path instead. This was the workaround used in Flask to support the deprecated parameter. See commit where parameter is removed.

    opened by arielrossanigo 1
  • Added a weighted hill climbing local search algorithm

    Added a weighted hill climbing local search algorithm

    I didn't notice that the stochastic HC algorithm chooses randomly from all the improving states. So for those who want the choice to be in respect to the value of each state I've added this pull request.

    opened by jonzarecki 2
  • Fix visited nodes stat on local search

    Fix visited nodes stat on local search

    When using local search the choosen_node event is never raised, so visited_nodes is allways 0. How should we count "visited nodes" on algorithms like beam or genetic?

    opened by fisadev 1
  • Add CSP constraint propagation visualizations

    Add CSP constraint propagation visualizations

    Once we have viewers for CSP algorithms, and constraint propagation, it would be really nice to have viewers for the constraints propagation.

    Depends on #12 and #42

    enhancement 
    opened by fisadev 0
  • Provide support to change accumulated cost

    Provide support to change accumulated cost

    The original Problem.cost() on aima-python receives the state, the actions, and the total cost, and expects to a new total cost to be returned. On simpleai we have changed that, to accept only the states and the action, and expect just the cost of that action to be returned. But this doesn't works for problem with actions that alter the costs of the previously taken actions.

    enhancement 
    opened by fisadev 1
Owner
null
AI Virtual Calculator: This is a simple virtual calculator based on Artificial intelligence.

AI Virtual Calculator: This is a simple virtual calculator that works with gestures using OpenCV. We will use our hand in the air to click on the calc

Md. Rakibul Islam 1 Jan 13, 2022
AI Face Mesh: This is a simple face mesh detection program based on Artificial intelligence.

AI Face Mesh: This is a simple face mesh detection program based on Artificial Intelligence which made with Python. It's able to detect 468 different

Md. Rakibul Islam 1 Jan 13, 2022
An Artificial Intelligence trying to drive a car by itself on a user created map

An Artificial Intelligence trying to drive a car by itself on a user created map

Akhil Sahukaru 17 Jan 13, 2022
Wordplay, an artificial Intelligence based crossword puzzle solver.

Wordplay, AI based crossword puzzle solver A crossword is a word puzzle that usually takes the form of a square or a rectangular grid of white- and bl

Vaibhaw 4 Nov 16, 2022
Artificial Intelligence playing minesweeper 🤖

AI playing Minesweeper ✨ Minesweeper is a single-player puzzle video game. The objective of the game is to clear a rectangular board containing hidden

Vaibhaw 8 Oct 17, 2022
Framework that uses artificial intelligence applied to mathematical models to make predictions

LiconIA Framework that uses artificial intelligence applied to mathematical models to make predictions Interface Overview Table of contents [TOC] 1 Ar

null 4 Jun 20, 2021
Artificial Intelligence search algorithm base on Pacman

Pacman Search Artificial Intelligence search algorithm base on Pacman Source The Pacman Projects by the University of California, Berkeley. Layouts Di

Day Fundora 6 Nov 17, 2022
AI Flow is an open source framework that bridges big data and artificial intelligence.

Flink AI Flow Introduction Flink AI Flow is an open source framework that bridges big data and artificial intelligence. It manages the entire machine

null 144 Dec 30, 2022
Python Rapid Artificial Intelligence Ab Initio Molecular Dynamics

Python Rapid Artificial Intelligence Ab Initio Molecular Dynamics

null 14 Nov 6, 2022
I created My own Virtual Artificial Intelligence named genesis, He can assist with my Tasks and also perform some analysis,,

Virtual-Artificial-Intelligence-genesis- I created My own Virtual Artificial Intelligence named genesis, He can assist with my Tasks and also perform

AKASH M 1 Nov 5, 2021
Randstad Artificial Intelligence Challenge (powered by VGEN). Soluzione proposta da Stefano Fiorucci (anakin87) - primo classificato

Randstad Artificial Intelligence Challenge (powered by VGEN) Soluzione proposta da Stefano Fiorucci (anakin87) - primo classificato Struttura director

Stefano Fiorucci 1 Nov 13, 2021
🔥 Cannlytics-powered artificial intelligence 🤖

Cannlytics AI ?? Cannlytics-powered artificial intelligence ?? ??️ Installation ??‍♀️ Quickstart ?? Development ?? Automation ?? Support ??️ License ?

Cannlytics 3 Nov 11, 2022
2021 Artificial Intelligence Diabetes Datathon

A.I.D.D. 2021 2021 Artificial Intelligence Diabetes Datathon A.I.D.D. 2021은 ‘2021 인공지능 학습용 데이터 구축사업’을 통해 만들어진 학습용 데이터를 활용하여 당뇨병을 효과적으로 예측할 수 있는가에 대한 A

null 2 Dec 27, 2021
CasualHealthcare's Pneumonia detection with Artificial Intelligence (Convolutional Neural Network)

CasualHealthcare's Pneumonia detection with Artificial Intelligence (Convolutional Neural Network) This is PneumoniaDiagnose, an artificially intellig

Azhaan 2 Jan 3, 2022
CS50's Introduction to Artificial Intelligence Test Scripts

CS50's Introduction to Artificial Intelligence Test Scripts ??‍♂️ What's this? ??‍♀️ This repository contains Python scripts to automate tests for mos

Jet Kan 2 Dec 28, 2022
Artificial intelligence technology inferring issues and logically supporting facts from raw text

개요 비정형 텍스트를 학습하여 쟁점별 사실과 논리적 근거 추론이 가능한 인공지능 원천기술 Artificial intelligence techno

null 6 Dec 29, 2021
Tom-the-AI - A compound artificial intelligence software for Linux systems.

Tom the AI (version 0.82) WARNING: This software is not yet ready to use, I'm still setting up the GitHub repository. Should be ready in a few days. T

null 2 Apr 28, 2022
An AI made using artificial intelligence (AI) and machine learning algorithms (ML) .

DTech.AIML An AI made using artificial intelligence (AI) and machine learning algorithms (ML) . This is created by help of some members in my team and

null 1 Jan 6, 2022
This Artificial Intelligence program can take a black and white/grayscale image and generate a realistic or plausible colorized version of the same picture.

Colorizer The point of this project is to write a program capable of taking a black and white / grayscale image, and generating a realistic or plausib

Maitri Shah 1 Jan 6, 2022