Metadata-Version: 2.4
Name: arp-ai
Version: 1.0.1
Summary: Artificial Intelligence Practicals for Jupyter Notebooks & Python — 11 Core AI Algorithms with Interactive Visualizations
Author-email: ARP Development Team <dev@arp-ai.org>
License-Expression: MIT
Project-URL: Homepage, https://github.com/arp-ai/arp
Project-URL: Documentation, https://github.com/arp-ai/arp#readme
Project-URL: Issues, https://github.com/arp-ai/arp/issues
Project-URL: Changelog, https://github.com/arp-ai/arp/blob/main/CHANGELOG.md
Keywords: artificial-intelligence,ai,algorithms,jupyter,notebook,search,heuristic,a-star,alpha-beta,minimax,n-queens,nlp,education
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Education
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: nlp
Requires-Dist: nltk>=3.8.0; extra == "nlp"
Provides-Extra: jupyter
Requires-Dist: ipython>=8.0.0; extra == "jupyter"
Requires-Dist: ipykernel>=6.0.0; extra == "jupyter"
Requires-Dist: nbformat>=5.0.0; extra == "jupyter"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Requires-Dist: nbclient>=0.7.0; extra == "dev"
Provides-Extra: all
Requires-Dist: arp-ai[dev,jupyter,nlp]; extra == "all"
Dynamic: license-file

# ARP — Artificial Intelligence Practicals

[![Python Version](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![Tests](https://img.shields.io/badge/tests-111%20passed-brightgreen.svg)]()
[![Coverage](https://img.shields.io/badge/coverage-91%25-success.svg)]()
[![Jupyter Ready](https://img.shields.io/badge/Jupyter-Notebook%20Ready-orange.svg)](https://jupyter.org/)

**ARP (Artificial Intelligence Practicals)** is a modern, modular, educational Python library designed for computer science students, educators, and AI practitioners. It packages canonical Artificial Intelligence algorithms into clean, reusable Python functions with interactive Jupyter Notebook displays, automated execution engines, and a unified command-line interface.

---

## Table of Contents

1. [Features](#features)
2. [Installation](#installation)
3. [Quick Start](#quick-start)
4. [Complete Practical Inventory](#complete-practical-inventory)
5. [Algorithm Explanations](#algorithm-explanations)
6. [Core API Documentation](#core-api-documentation)
7. [Jupyter Notebook Integration](#jupyter-notebook-integration)
8. [Command-Line Interface (CLI)](#command-line-interface-cli)
9. [Dependencies](#dependencies)
10. [Troubleshooting](#troubleshooting)
11. [Contributing](#contributing)
12. [License](#license)

---

## 1. Features

- **11 Core AI Practicals:** All original curriculum programs preserved, audited, and refactored into high-quality modular Python functions.
- **Jupyter Notebook First-Class Support:** Rich HTML visualization tables, interactive chessboards, and step-by-step state representations rendered natively in notebooks (`_repr_html_`).
- **Interactive & Headless Execution:** Run educational demonstrations without blocking `input()` prompts, or pass custom graphs, heuristics, and parameters programmatically.
- **Unified Registry & Search:** Search algorithms by problem category, technique name, or keywords.
- **Jupyter Next-Cell Insertion (`arp.get`):** Automatically retrieve complete source code and insert it into a new editable cell directly below the active cell without auto-execution (matching the proven `MLP.get()` workflow).
- **Zero Import Side-Effects:** Modules never execute or trigger downloads during import.
- **High Test Coverage:** 111 automated tests covering algorithms, edge cases, registry, runner, CLI, and end-to-end headless Jupyter notebook execution with 91% code coverage.

---

## 2. Installation

### From PyPI (Standard Installation)

```bash
pip install arp-ai
```

### With Optional Dependencies

To enable optional NLP (`nltk`) and Jupyter Notebook dependencies:

```bash
# For Natural Language Processing enhancements
pip install "arp-ai[nlp]"

# For Jupyter Notebook environment
pip install "arp-ai[jupyter]"

# Install all optional extras
pip install "arp-ai[all]"
```

### From Local Source (Editable Mode)

```bash
git clone https://github.com/arp-ai/arp.git
cd ARP
pip install -e .
```

---

## 3. Quick Start

Inside a Python shell or Jupyter Notebook:

```python
import arp

# 1. Browse all available AI practicals
arp.list()

# 2. Search for algorithms
arp.search("search")

# 3. View algorithm specifications and complexity
arp.info("AS")

# 4. Run an algorithm demo
result = arp.run("AS")

# 5. Access the user guide
arp.help()
```

---

## 4. Complete Practical Inventory

All 11 original practical programs are indexed in the central registry:

| ID | Practical Name | Original File | AI Domain | Time Complexity | Space Complexity |
|---|---|---|---|---|---|
| **AB** | Alpha-Beta Pruning | `AB.py` | Adversarial Game Theory | $O(b^{d/2})$ | $O(b \cdot d)$ |
| **AOS** | AO* Search | `AOS.py` | Problem Reduction (AND-OR) | $O(b^d)$ | $O(b \cdot d)$ |
| **AS** | A* Search | `AS.py` | Informed Heuristic Search | $O(b^d)$ | $O(b^d)$ |
| **BFS** | Best-First Search | `BFS.py` | Greedy Heuristic Search | $O(b^m)$ | $O(b^m)$ |
| **CA** | Cryptarithmetic Problem | `CA.py` | Constraint Satisfaction (CSP) | $O(10! / (10-k)!)$ | $O(k)$ |
| **CH** | Chatbot | `CH.py` | Natural Language Processing | $O(N \cdot M)$ | $O(1)$ |
| **HC** | Hill Climbing | `HC.py` | Local Search Optimization | $O(d \cdot k)$ | $O(1)$ |
| **MIMA** | Minimax Algorithm | `MIMA.py` | Adversarial Game Theory | $O(b^d)$ | $O(b \cdot d)$ |
| **NL** | Natural Language Processing | `NL.py` | NLP Text Preprocessing | $O(W \cdot L)$ | $O(W)$ |
| **NQ** | N-Queens Problem | `NQ.py` | Constraint Satisfaction (CSP) | $O(N!)$ | $O(N)$ |
| **WJ** | Water Jug Problem | `WJ.py` | State Space Search | $O(X \cdot Y)$ | $O(X \cdot Y)$ |

---

## 5. Algorithm Explanations

### 5.1 Alpha-Beta Pruning (`AB`)
- **What it is:** An enhancement of the Minimax adversarial game search.
- **How it works:** It maintains two thresholds: $\alpha$ (the minimum score the maximizing player is assured of) and $\beta$ (the maximum score the minimizing player is assured of). If at any point $\beta \le \alpha$, remaining sibling branches cannot affect the final outcome and are pruned.
- **Real-world use:** Game engines for Chess, Checkers, and Connect Four.

### 5.2 AO* Search (`AOS`)
- **What it is:** A heuristic algorithm for traversing AND-OR graphs.
- **How it works:** When a problem can be decomposed into independent sub-problems (AND branch) or alternate choices (OR branch), AO* computes bottom-up costs and marks the optimal sub-graph.
- **Real-world use:** Goal planning, automated theorem proving, and medical diagnosis workflows.

### 5.3 A* Search (`AS`)
- **What it is:** The premier informed pathfinding algorithm.
- **How it works:** Evaluates nodes using $f(n) = g(n) + h(n)$, where $g(n)$ is the exact cost from start to $n$, and $h(n)$ is the heuristic estimated cost from $n$ to the goal. It is optimal and complete when $h(n)$ is admissible.
- **Real-world use:** GPS navigation systems (Google Maps) and video game pathfinding.

### 5.4 Best-First Search (`BFS`)
- **What it is:** A greedy informed search strategy.
- **How it works:** Uses a priority queue ordered strictly by the heuristic estimate $h(n)$ to expand the node that appears closest to the goal. The package also includes Breadth-First Search (`breadth_first_search`) to illustrate the distinction.
- **Real-world use:** Rapid exploration in large search graphs where an approximate solution is needed quickly.

### 5.5 Cryptarithmetic (`CA`)
- **What it is:** An alphametic math puzzle modeled as a Constraint Satisfaction Problem (CSP).
- **How it works:** Distinct letters map uniquely to digits $0$ through $9$ without leading zeroes (e.g., $\text{SEND} + \text{MORE} = \text{MONEY}$). The solver validates all constraints and generates matching digit assignments.
- **Real-world use:** Cryptanalysis, scheduling, and logic puzzle solvers.

### 5.6 Chatbot (`CH`)
- **What it is:** A rule-based conversational agent.
- **How it works:** Matches incoming user utterances against regularized keyword dictionaries (Clothes Store domain) and dispatches intent-based replies with safe exit conditions.
- **Real-world use:** E-commerce FAQs, customer support triage, and automated routing.

### 5.7 Hill Climbing (`HC`)
- **What it is:** A local search optimization technique.
- **How it works:** Begins with an initial state and iteratively transitions to neighbor states that yield an improvement in objective score (steepest ascent). Terminates when a local peak or plateau is reached.
- **Real-world use:** Traveling Salesperson Problem (TSP), circuit board layout, and numerical optimization.

### 5.8 Minimax Algorithm (`MIMA`)
- **What it is:** A decision-theoretic algorithm for two-player zero-sum games.
- **How it works:** Assumes the opponent plays rationally to minimize your gain. MAX chooses the branch maximizing the score, while MIN chooses the branch minimizing it.
- **Real-world use:** Tic-tac-toe, Othello, and classical board games.

### 5.9 Natural Language Processing Pipeline (`NL`)
- **What it is:** Essential preprocessing for textual data.
- **How it works:**
  1. *Tokenization*: Splitting text into words and punctuation.
  2. *Stopword Removal*: Removing non-informative grammatical terms ("the", "is", "at").
  3. *Stemming*: Stripping suffixes to extract base stems ("running" $\to$ "run").
  4. *Lemmatization*: Morphological reduction using lexical dictionaries.
  Includes a pure-Python offline engine so students can run experiments without installing or downloading external NLTK data.
- **Real-world use:** Search engines, spam detection, sentiment analysis.

### 5.10 N-Queens Problem (`NQ`)
- **What it is:** A classic backtracking constraint puzzle.
- **How it works:** Places $N$ chess queens on an $N \times N$ chessboard such that no two queens share the same row, column, or diagonal.
- **Real-world use:** Parallel task scheduling, register allocation in compilers.

### 5.11 Water Jug Problem (`WJ`)
- **What it is:** A state-space search problem.
- **How it works:** Models uncalibrated jugs $(X, Y)$ and uses Breadth-First Search (BFS) to find the shortest sequence of actions (Fill, Empty, Pour) that measures an exact target volume $Z$. Includes Bézout's identity validation ($\gcd$).
- **Real-world use:** Robot task planning and finite state machine transitions.

---

## 6. Core API Documentation

### `arp.list()`
Displays a formatted catalog of all 11 practical programs with IDs, categories, and complexities.

```python
arp.list()
```

### `arp.search(query: str)`
Searches programs by ID, title, problem category, or keywords.

```python
arp.search("search")
arp.search("minimax")
```

### `arp.info(identifier: str)`
Returns a `ProgramMetadata` object containing detailed specifications, complexity characteristics, inputs, and outputs.

```python
arp.info("AS")
```

### `arp.get(identifier: str, source: bool = True, original: bool = True, refactored: bool = False, insert: Optional[bool] = None)`
Retrieves the complete, unaltered Python source code of the practical program and automatically inserts it into a **new Jupyter Notebook cell immediately below the current cell** (matching the proven `MLP.get("DT-A")` user experience):

```python
import arp

# Automatically inserts original A* Search code into the next cell below ready to edit and execute
arp.get("AS")
```

- **Exact Original Source by Default:** Returns the exact curriculum student practical source code by default (`original=True`), preserving 100% of the original variables, data structures, comments, print statements, and execution flow.
- **Interactive Cell Insertion:** In Jupyter Notebook, JupyterLab, and VS Code, `arp.get()` calls `set_next_input(replace=False)` to insert the code into a new cell directly beneath the active cell.
- **Safe & Non-Destructive:** The inserted code is **never executed automatically**. Students can inspect, modify variables, and run it independently.
- **Formatting Preserved:** Python indentation, docstrings, comments, and structure are 100% preserved.
- **Refactored Modular Implementation:** To view or insert the refactored modular implementation instead of the original script, pass `refactored=True`:
  ```python
  arp.get("AS", refactored=True)
  ```
- **All 11 Practicals Supported:** Works with any registered ID (`AB`, `AOS`, `AS`, `BFS`, `CA`, `CH`, `HC`, `MIMA`, `NL`, `NQ`, `WJ`) or filename (`AS.py`).
- **Sensible Non-Jupyter Fallback:** When called outside Jupyter (in scripts or standard terminals), it prints an informative notice and returns the source code string (`SourceCode`).
- **Inspect Without Inserting:** If you want to retrieve the source code object inside Jupyter without inserting a new cell, pass `insert=False`:
  ```python
  code = arp.get("AS", insert=False)
  ```
- **Graceful Error Handling:** Invalid program IDs print a friendly error message listing all valid practical IDs and return `None` without crashing.

### `arp.insert(identifier: str, raise_error: bool = False, original: bool = True, refactored: bool = False)`
Convenience wrapper for cell insertion:

```python
arp.insert("AS")
```

### `arp.run(identifier: str, *args, **kwargs)`
Executes the specified algorithm. Accepts custom inputs and returns structured result objects.

```python
# Default educational demo
res_as = arp.run("AS")

# Custom inputs
res_nq = arp.run("NQ", n=6)
res_wj = arp.run("WJ", jug1=5, jug2=3, target=4)
```

### `arp.help()`
Displays the interactive package usage guide.

```python
arp.help()
```

---

## 7. Jupyter Notebook Integration

The package is optimized for interactive learning in Jupyter.

### Interactive Demo Notebook

Open the bundled demonstration notebook:

```bash
jupyter notebook examples/ARP_Demo.ipynb
```

The notebook demonstrates:
1. Catalog exploration and multi-query searches (`arp.list()`, `arp.search()`).
2. Viewing specifications and complexity metrics (`arp.info()`).
3. Automatically inserting practical source code into a new notebook cell below ready to edit and execute (`arp.get()`).
4. Running A* Search with custom graphs and heuristics.
5. Evaluating Minimax and Alpha-Beta trees.
6. Solving 4-Queens and 8-Queens with interactive chessboard rendering.
7. Planning Water Jug solutions with capacity gauges.
8. Processing custom sentences with the NLP pipeline.
9. Interactive clothes store chatbot sessions.

---

## 8. Command-Line Interface (CLI)

The package provides an `arp` terminal command:

```bash
# List all practicals
arp list

# Search for practicals
arp search "heuristic"

# Show program information
arp show AS

# View Python source code
arp get AS

# Display code or guidance for cell insertion
arp insert AS

# Run program demonstration
arp run WJ

# Run N-Queens with 4 queens
arp run NQ

# Show usage help
arp help
```

---

## 9. Dependencies

- **Core Requirements:** Python 3.9+ (Zero required third-party dependencies; uses the Python standard library exclusively).
- **Optional Dependencies:**
  - `nltk`: Advanced lemmatization and corpus support (pure-Python fallback included).
  - `jupyter`, `ipython`, `nbformat`: Interactive notebook execution and rich displays.
  - `pytest`, `pytest-cov`, `nbclient`: Development, coverage, and testing tools.

---

## 10. Troubleshooting

### Issue: "ModuleNotFoundError: No module named 'nltk'"
**Solution:** The NLP module includes a built-in pure-Python fallback that operates without NLTK. If you wish to use NLTK, install it via:
```bash
pip install "arp-ai[nlp]"
```

### Issue: "NLTK data download error or offline environment"
**Solution:** `arp` never forces automatic network downloads on import. If NLTK corpora are missing, it seamlessly uses the pure-Python tokenizer, stopword dictionary, and stemmer.

### Issue: "Jupyter HTML rendering not displaying in terminal"
**Solution:** When run outside Jupyter (e.g., standard Python shell or terminal), `arp` automatically falls back to clean Unicode/ASCII table formatting.

---

## 11. Contributing

Contributions and algorithm extensions are welcome!

1. Fork the repository.
2. Create your feature branch (`git checkout -b feature/new-algorithm`).
3. Add tests in `tests/test_algorithms.py`.
4. Ensure all tests pass: `pytest --cov=arp`.
5. Commit your changes and open a Pull Request.

---

## 12. License

This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.
