aima-python

repository·master·Indexed 27 days ago

https://github.com/aimacode/aima-python

Python implementations of the algorithms and pseudocode from the textbook 'Artificial Intelligence: A Modern Approach' (4th edition). The library includes modules for agents, search, games, constraint satisfaction (CSP), logic, planning, probability, MDPs, reinforcement learning, learning, knowledge, NLP, and game theory. It provides a core package for local installation and a JupyterLite proof-of-concept for running a subset of notebooks in the browser via Pyodide.

Tokens
35.8K
Snippets
55
Records
294
Agent score
93%

What's inside aima-python

  1. Project Structure Overview

    master

    The repository is organized into the following top-level directories:

    • aima/: The core importable Python package. Contains modules for major AI topics (e.g., search.py).
    • notebooks/: Jupyter notebooks for demonstrating and explaining the code. Notebooks use %run bootstrap.ipynb to ensure the repository root is in sys.path.
    • tests/: A test suite using assert statements, compatible with pytest.
    • lite/: A JupyterLite proof-of-concept that runs notebooks in the browser via Pyodide.
  2. Run aima-python in the browser via JupyterLite

    master

    You can run a subset of aima notebooks entirely in the browser using JupyterLite and Pyodide. This setup requires no server or local installation.

    Limitations: Modules requiring heavy native dependencies (e.g., TensorFlow/Keras, OpenCV, cvxopt, qpsolvers) are not available. This includes deep_learning, perception, and the SVM path in learning.

    Available Modules in Browser:

    • aima.agents (reflex vs. model-based agents)
    • aima.search (BFS / A*)
    • aima.games (minimax / alpha-beta)
    • aima.csp (AC-3 / backtracking / min-conflicts)
    • aima.logic (propositional model checking / DPLL / first-order forward chaining)
    • aima.planning (STRIPS / GraphPlan)
    • aima.probability (exact and approximate inference)
    • aima.mdp (value / policy iteration)
    • aima.reinforcement_learning (Q-learning)
    • aima.learning (decision tree / naive Bayes)
    • aima.knowledge (current-best-hypothesis learning)
    • aima.nlp (probabilistic CYK parsing)
    • aima.text (unigram / bigram language models)
    • aima.game_theory (Nash equilibria / zero-sum games / Shapley value)
  3. Build the JupyterLite site locally

    master

    To build the aima wheel and the JupyterLite site locally, navigate to the lite directory and run the build script. You can then serve the output using a local Python HTTP server.

    Steps:

    1. Build the wheel and the site.
    2. Serve the _output directory.
    3. Access the site at http://localhost:8000.
    cd lite
    ./build.sh          # builds the aima wheel + runs `jupyter lite build`
    python -m http.server -d _output 8000   # then open http://localhost:8000
  4. Install aima-python

    master

    To use aima-python locally, clone the repository, install the required Python dependencies, and initialize the data submodules.

    Prerequisites

    • Python: Version 3.9 or higher is required.
    • Graphviz: Some notebooks require the dot system binary for rendering. Install it via your OS package manager (e.g., apt install graphviz or brew install graphviz).

    Installation Steps

    1. Clone the repository:
      git clone https://github.com/aimacode/aima-python.git
      cd aima-python
    2. Install basic dependencies:
      pip install -r requirements.txt
    3. Fetch required datasets via submodules:
      git submodule init
      git submodule update
    4. (Optional) Install pytest to run the test suite:
      pip install pytest
    git clone https://github.com/aimacode/aima-python.git
    cd aima-python
    pip install -r requirements.txt
    git submodule init
    git submodule update
    pip install pytest
  5. Verify JupyterLite notebooks in a browser

    master

    To ensure that the notebooks actually execute correctly in Pyodide, use the verify_browser.py script. This script uses Playwright to run a headless Chromium instance, installs the built aima wheel, and executes the code cells in each notebook.

    Prerequisites:

    • playwright
    • nbformat
    pip install playwright nbformat
    python -m playwright install chromium
    cd lite && ./build.sh && python verify_browser.py
  6. Overview of Agent Types in AIMA

    master

    The aima-python library provides various agent program implementations to demonstrate different levels of AI complexity:

    • Random Agent: Chooses actions randomly.
    • Table-Driven Agent: Uses a lookup table of percept histories to actions.
    • Simple Reflex Agent: Uses condition-action rules based on the current percept.
    • Model-Based Reflex Agent: Maintains an internal state to track unobserved aspects of the world.
    • Goal-Based Agent: Uses goal information to find action sequences that achieve desirable states.
    • Utility-Based Agent: Uses a utility function to maximize a performance measure.
    • Learning Agent: Includes a learning element, critic, performance element, and problem generator to improve over time.
  7. Get started with aima-python

    master

    The aima-python repository provides Python implementations of algorithms from the textbook Artificial Intelligence: A Modern Approach.

    To use the project, you can interact with the provided IPython notebooks in three ways:

    1. View static HTML: Browse .ipynb files directly on GitHub.
    2. Local Execution: Download the repository, start a Jupyter notebook server using the jupyter notebook command from the repository directory, and run the notebooks locally.
    3. Binder: Use the Binder badge on the repository main page to run notebooks in an online, executable environment without local installation.

    For a quick setup in a local environment, it is recommended to use the Anaconda distribution of Python 3.5.

  8. Install the aima package in JupyterLite

    master

    When using aima-python in a browser-based environment like JupyterLite, you must install the aima package into the browser kernel at the start of your session. Use piplite.install with deps=False to skip heavy native dependencies (like TensorFlow, OpenCV, or cvxopt) that are not required for lightweight modules and to ensure a faster installation, as Pyodide already provides core scientific libraries like numpy, scipy, matplotlib, and networkx.

    import piplite
    await piplite.install("aima", deps=False)
    
    from aima.search import romania_map
    print("aima loaded — Romania map has", len(romania_map.locations), "cities")
  9. Use the GridMDP Editor GUI

    master

    The grid_mdp.py tool provides a graphical interface to build and solve Grid Markov Decision Processes (GridMDP).

    Steps to use the editor:

    1. Launch the editor from the project root: python gui/grid_mdp.py.
    2. Setup Grid: Enter the grid dimensions (e.g., 3 x 4) and click 'Build a GridMDP'.
    3. Initialize: Go to the Edit menu and click Initialize.
    4. Set Rewards: Set the reward value (e.g., -0.4) and click Apply.
    5. Configure Cells:
      • Select a cell and choose the Wall radio button to create an obstacle.
      • Select cells and choose the Terminal radio button to set end states with specific rewards.
      • Click Apply after changes.
    6. Run Solver: Go to the Build menu and click Build and Run.

    The tool will generate a heatmap where green shades indicate positive utilities and brown shades indicate negative utilities. Once converged, utility values and arrow diagrams will appear in separate dialogs.

    python gui/grid_mdp.py
  10. Implement a Dynamic MDP with State and Action Dependent Rewards

    master

    A Dynamic MDP (DMDP) is used when rewards depend on the transition (the action taken from a state) rather than just the state itself.

    1. Extend the DMDP class.
    2. Implement R(self, state, action) to return self.rewards[state][action].
    3. Implement T(self, state, action) to return self.transitions[state][action].
    4. Because the standard value_iteration assumes state-only rewards, you must use a modified version: value_iteration_dmdp(dmdp, epsilon).
    5. Use a custom best_policy_dmdp(dmdp, U) function to derive the policy from utilities U.
    # Custom DMDP implementation snippet
    class CustomDMDP(DMDP):
        def T(self, state, action):
            if action is None:
                return [(0.0, state)]
            else:
                return [(prob, new_state) for new_state, prob in self.t[state][action].items()]
    
        def R(self, state, action):
            if action is None:
                return 0
            else:
                return self.rewards[state][action]
    
    # Solving with custom value iteration
    def value_iteration_dmdp(dmdp, epsilon=0.001):
        U1 = {s: 0 for s in dmdp.states}
        R, T, gamma = dmdp.R, dmdp.T, dmdp.gamma
        while True:
            U = U1.copy()
            delta = 0
            for s in dmdp.states:
                U1[s] = max([(R(s, a) + gamma*sum([(p*U[s1]) for (p, s1) in T(s, a)])) for a in dmdp.actions(s)])
                delta = max(delta, abs(U1[s] - U[s]))
            if delta < epsilon * (1 - gamma) / gamma:
                return U
  11. Import NLP module and components

    master

    To use the Natural Language Processing features, import the nlp module and its specific classes for grammars, lexicons, and parsing from aima.nlp.

    from aima import nlp
    from aima.nlp import Page, HITS
    from aima.nlp import Lexicon, Rules, Grammar, ProbLexicon, ProbRules, ProbGrammar
    from aima.nlp import CYK_parse, Chart