# MHA Flow - Comprehensive Lab Manual
**Version 2.0.7** | Updated February 2026

---

## Table of Contents

1. [Introduction](#introduction)
2. [System Requirements](#system-requirements)
3. [Installation](#installation)
4. [Project Structure](#project-structure)
5. [Configuration](#configuration)
6. [Running the Application](#running-the-application)
7. [Command-Line Interface (CLI)](#command-line-interface-cli)
8. [Python API Usage](#python-api-usage)
9. [Flask Web Interface](#flask-web-interface)
10. [Algorithm Catalog](#algorithm-catalog)
11. [Examples and Tutorials](#examples-and-tutorials)
12. [Troubleshooting](#troubleshooting)
13. [Advanced Features](#advanced-features)

---

## Introduction

### What is MHA Flow?

MHA Flow is a professional, production-ready Python framework for **Meta-Heuristic Optimization** with:
- **142+ Algorithms** including swarm, evolutionary, physics-based, and hybrid variants
- **Flask Web Interface** with user authentication and personal history tracking
- **AI-Powered Recommendations** for algorithm selection
- **Universal Levy Flight Integration** across all algorithms
- **Custom Algorithm Upload** system with GitHub PR workflow
- **Complete CLI** for headless operation

### Key Features

✅ **142+ Metaheuristic Algorithms**  
🧬 **Universal Levy Flight** - Enhanced convergence  
🔄 **GitHub-Based Custom Algorithms**  
🤖 **AI-Powered Recommendations**  
📊 **Real-Time Visualization**  
💾 **Session Management** - Save, load, compare runs  
🌐 **Flask Web Interface** - Professional UI with REST API  
📤 **Multiple Export Formats** - CSV, Excel, JSON, PNG, PDF  
🔐 **Multi-User Support** - Authentication and history  
🖥️ **Full CLI Support** - Command-line automation

---

## System Requirements

### Minimum Requirements

- **Python**: 3.8 or higher
- **RAM**: 4GB minimum
- **Disk Space**: 1GB minimum
- **OS**: Windows, macOS, Linux

### Recommended Setup

- **Python**: 3.10 or higher
- **RAM**: 8GB or more
- **GPU**: Optional, for large-scale optimization
- **Browser**: Modern web browser (Chrome, Firefox, Edge)

### Core Dependencies

```text
numpy >= 1.24.0, < 2.0.0
pandas >= 2.0.0, < 3.0.0
scipy >= 1.11.0, < 2.0.0
scikit-learn >= 1.3.0, < 2.0.0
matplotlib >= 3.7.0, < 4.0.0
seaborn >= 0.12.0, < 1.0.0
plotly >= 5.17.0, < 6.0.0
```

### Flask Web Framework

```text
Flask >= 2.3.0, < 3.0.0
Flask-CORS >= 4.0.0, < 5.0.0
Flask-Session >= 0.5.0, < 1.0.0
Flask-Login >= 0.6.0, < 1.0.0
Werkzeug >= 2.3.0, < 3.0.0
```

### Database Support

```text
# MongoDB (Primary - Recommended for Cloud)
flask-mongoengine >= 1.0.0
mongoengine >= 0.27.0
pymongo >= 4.6.0
dnspython >= 2.4.0

# SQL Databases (Optional Fallback)
Flask-SQLAlchemy >= 3.0.0, < 4.0.0
SQLAlchemy >= 2.0.0, < 3.0.0
psycopg2-binary >= 2.9.0  # PostgreSQL
pymysql >= 1.1.0  # MySQL
```

---

## Installation

### Method 1: From Source (Recommended for Development)

```bash
# Step 1: Clone the repository
git clone https://github.com/Achyut103040/MHA-Algorithm.git
cd MHA-Algorithm

# Step 2: Install the package
pip install -e .

# Step 3: Install with web interface support
pip install -e .[ui]

# Step 4: Install complete (all features)
pip install -e .[complete]
```

### Method 2: Using Windows Setup Script

```batch
# Run the setup script
setup.bat

# Follow the prompts:
# [1/5] Python found - Checks Python installation
# [2/5] Creating .env file - Configuration setup
# [3/5] Installing dependencies - Installs requirements.txt
# [4/5] Initializing database - Sets up SQLite database
# [5/5] Setup complete
```

### Method 3: Manual Installation

```bash
# Step 1: Create virtual environment (recommended)
python -m venv .venv

# Step 2: Activate virtual environment
# Windows:
.venv\Scripts\activate
# Linux/macOS:
source .venv/bin/activate

# Step 3: Install dependencies
pip install -r requirements.txt

# Step 4: Initialize database
python init_db.py full
```

### Verify Installation

```bash
# Check version
python -c "import mha_toolbox; print(mha_toolbox.__version__)"

# List available algorithms
python -m mha_toolbox list

# Check CLI commands
mha-flow --help
```

---

## Project Structure

```
MHA-Algorithm/
├── mha_toolbox/                    # Core library
│   ├── algorithms/                 # 142+ algorithm implementations
│   │   ├── levy_flight_universal.py   # Universal Levy flight
│   │   ├── base_algorithm.py          # Base classes
│   │   ├── hybrid/                    # Hybrid algorithms
│   │   └── custom/                    # User-uploaded algorithms
│   ├── levy_flight_engine.py       # Advanced Levy flight engine
│   ├── custom_algorithm_manager.py # Algorithm upload system
│   ├── algorithm_recommender.py    # AI recommendation system
│   ├── dataset_intelligence.py     # Dataset analysis
│   ├── complete_algorithm_registry_v2.py  # Algorithm metadata
│   ├── toolbox.py                  # Main API interface
│   ├── cli.py                      # Command-line interface
│   └── __init__.py                 # Package initialization
│
├── app_production.py               # Flask web application
├── templates/                      # HTML templates
├── static/                         # CSS, JS, assets
├── models.py                       # Database models
├── db_helpers.py                   # Database helper functions
├── config.py                       # Configuration management
├── init_db.py                      # Database initialization
│
├── tests/                          # Test suite
├── docs/                           # Documentation
├── examples/                       # Example scripts
├── objective_functions/            # Standard test functions
│
├── requirements.txt                # Python dependencies
├── pyproject.toml                  # Package configuration
├── setup.py                        # Setup script
├── setup.bat                       # Windows setup
├── .env.example                    # Environment variables template
└── README.md                       # Main documentation
```

---

## Configuration

### Environment Variables

Create a `.env` file in the project root:

```env
# Database Configuration
DB_TYPE=sqlite                      # Use 'mongodb' for cloud database
DATABASE_URL=sqlite:///instance/mha_flow.db

# MongoDB (Optional - for cloud deployment)
MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/mha_flow?retryWrites=true&w=majority
MONGO_DB_NAME=mha_flow

# Flask Configuration
FLASK_ENV=development               # or 'production'
FLASK_HOST=127.0.0.1
FLASK_PORT=5000
SECRET_KEY=your-secret-key-here     # CHANGE THIS IN PRODUCTION

# GitHub Integration (Optional - for custom algorithm submissions)
GITHUB_TOKEN=your_github_token
GITHUB_REPO=username/repository

# Upload Configuration
UPLOAD_FOLDER=uploads
MAX_CONTENT_LENGTH=16777216         # 16MB max upload size

# Session Configuration
SESSION_TYPE=filesystem
SESSION_PERMANENT=False
PERMANENT_SESSION_LIFETIME=3600     # 1 hour
```

### Database Initialization

```bash
# Full initialization (creates tables and demo data)
python init_db.py full

# Create tables only
python init_db.py

# Reset database (WARNING: Deletes all data)
python init_db.py reset
```

---

## Running the Application

### Method 1: Flask Web Interface (Recommended)

```bash
# Start the Flask server
python -m mha_toolbox ui

# Or using the start script
python start_server.py

# Or using the installed command
mha-flow ui

# Access at: http://127.0.0.1:5000
```

**Custom Port and Host:**

```bash
# Run on custom port
python -m mha_toolbox ui --port 8080

# Allow external connections
python -m mha_toolbox ui --host 0.0.0.0

# Debug mode
python -m mha_toolbox ui --debug
```

### Method 2: Production Deployment

```bash
# Using Gunicorn (Linux/macOS)
gunicorn -w 4 -b 0.0.0.0:5000 app_production:app

# Using Windows batch script
launch_production.bat
```

### Default Login Credentials

After running `init_db.py full`, use:
- **Username**: `admin`
- **Password**: `admin123`

> **⚠️ IMPORTANT**: Change these credentials immediately in production!

---

## Command-Line Interface (CLI)

### Available Commands

| Command | Description |
|---------|-------------|
| `mha-flow ui` | Launch Flask web interface |
| `mha-flow list` | List all 142+ algorithms |
| `mha-flow recommend` | AI-powered algorithm recommendations |
| `mha-flow run <algo>` | Run algorithm on dataset |
| `mha-flow info <algo>` | Show algorithm details |
| `mha-flow demo` | Run interactive demo |
| `mha-flow version` | Show version info |

### 1. List Algorithms

```bash
# List all algorithms
python -m mha_toolbox list

# Filter by category
python -m mha_toolbox list --category swarm
python -m mha_toolbox list --category evolution
python -m mha_toolbox list --category hybrid
```

**Output:**
```
📋 Available Algorithms (142 total):
==================================================
A:
  • ABC   (Artificial Bee Colony)
  • ALO   (Ant Lion Optimizer)
  • AVOA  (African Vultures Optimization Algorithm)
G:
  • GA    (Genetic Algorithm)
  • GBO   (Gradient-Based Optimizer)  
  • GWO   (Grey Wolf Optimizer)
P:
  • PSO   (Particle Swarm Optimization)
  • PSO_GWO_Hybrid
...
```

### 2. Get Algorithm Information

```bash
# Get PSO information
python -m mha_toolbox info pso

# Get Grey Wolf Optimizer info
python -m mha_toolbox info gwo
```

**Output:**
```json
📖 Algorithm Information: PSO
======================================================================
{
  "name": "PSO",
  "full_name": "Particle Swarm Optimization",
  "category": "Swarm Intelligence",
  "year": 1995,
  "authors": ["Kennedy", "Eberhart"],
  "parameters": {
    "population_size": 30,
    "max_iterations": 100,
    "c1": 2.0,
    "c2": 2.0,
    "w": 0.9
  }
}
```

### 3. Get Algorithm Recommendations

```bash
# Interactive recommendation
python -m mha_toolbox recommend --interactive
```

**Interactive Prompts:**
1. Dataset size (small/medium/large)
2. Problem type (classification/regression/function)
3. Number of features
4. Number of samples

**Output:**
```
🎯 Algorithm Recommendation System
======================================================================
✨ Top 5 Recommended Algorithms:
======================================================================
1. PSO
   📊 Confidence Score: 95.00%
   💡 Reason: Excellent for medium-sized datasets
2. GWO  
   📊 Confidence Score: 92.50%
   💡 Reason: Good exploration-exploitation balance
...
```

### 4. Run Optimization

```bash
# Basic run
python -m mha_toolbox run pso --dataset breast_cancer

# Custom parameters
python -m mha_toolbox run gwo --dataset iris \
  --population_size 50 \
  --max_iterations 200

# Save model
python -m mha_toolbox run sca --dataset breast_cancer --save_model

# Custom output directory
python -m mha_toolbox run woa --dataset iris --output my_results
```

**Output:**
```
🚀 Running PSO
======================================================================
Dataset: breast_cancer
Parameters: {'population_size': 30, 'max_iterations': 100}
======================================================================
Progress: 100%|██████████| 100/100 [00:15<00:00,  6.67it/s]

✅ Results saved to: results/pso_breast_cancer.json
📊 Best fitness: 0.9649
🎯 Selected features: 15
```

---

## Python API Usage

### Basic Optimization

```python
from mha_toolbox import optimize
from sklearn.datasets import load_iris

# Load dataset
X, y = load_iris(return_X_y=True)

# Run optimization with Levy flight support
result = optimize(
    algorithm='pso',
    X=X, 
    y=y,
    population_size=30,
    max_iterations=100,
    levy_enabled=True  # Enable Levy flight
)

# Access results
print(f"Best fitness: {result.best_fitness_:.6f}")
print(f"Runtime: {result.execution_time_:.2f}s")
print(f"Selected features: {result.n_selected_features_}")
```

### Using MHAToolbox Class

```python
from mha_toolbox import MHAToolbox

# Initialize toolbox
toolbox = MHAToolbox()

# List all algorithms
algorithms = toolbox.get_all_algorithm_names()
print(f"Available algorithms: {len(algorithms)}")

# Get algorithm info
info = toolbox.get_algorithm_info('pso')
print(info)

# Run with custom parameters
result = toolbox.optimize(
    'gwo',  # Grey Wolf Optimizer
    X=X, y=y,
    population_size=50,
    max_iterations=200,
    hyperparameter_tuning=True
)
```

### AI-Powered Algorithm Recommendation

```python
from mha_toolbox import AlgorithmRecommender
from mha_toolbox.dataset_intelligence import DatasetIntelligence

# Initialize recommender
recommender = AlgorithmRecommender()

# Analyze dataset
intelligence = DatasetIntelligence()
profile = intelligence.analyze_dataset(X, y)

# Get recommendations
recommendations = recommender.recommend(
    dataset_profile=profile,
    user_preferences={
        'priority': 'accuracy',  # or 'speed', 'balance'
        'expected_features': ['multimodal', 'complex'],
        'time_limit': 60  # seconds
    },
    top_k=5
)

# Display recommendations
for i, rec in enumerate(recommendations, 1):
    print(f"{i}. {rec['algorithm']} (confidence: {rec['confidence']:.2%})")
    print(f"   Reason: {rec['reasoning']}")
```

### Parallel Optimization

```python
from mha_toolbox.parallel_optimizer import parallel_compare

# Run multiple algorithms in parallel
results = parallel_compare(
    algorithms=['pso', 'gwo', 'sca', 'woa'],
    X=X, y=y,
    n_jobs=4  # Number of parallel processes
)

# Compare results
for name, result in results.items():
    print(f"{name}: {result.best_fitness:.4f}")
```

### Custom Algorithm Upload

```python
from mha_toolbox.custom_algorithm_manager import CustomAlgorithmManager

# Initialize manager
manager = CustomAlgorithmManager()

# Process uploaded algorithm file
result = manager.process_upload(
    file_path='my_custom_algorithm.py',
    metadata={
        'author': 'Your Name',
        'description': 'My innovative MHA algorithm',
        'year': 2025
    }
)

# Check validation status
if result['success']:
    print(f"✓ Algorithm validated: {result['validation']['main_class_name']}")
    print(f"Parameters detected: {result['parameter_mapping']}")
    
    # Integrate into system
    integration = manager.integrate_algorithm(
        file_path='my_custom_algorithm.py',
        parameter_mapping=result['parameter_mapping'],
        category='custom'
    )
    print(f"✓ Algorithm integrated: {integration['algorithm_id']}")
```

### Using Levy Flight Directly

```python
from mha_toolbox.algorithms.levy_flight_universal import add_levy_flight_to_position
import numpy as np

# Your algorithm's iteration
current_position = np.random.rand(10)
best_position = np.zeros(10)
bounds = (-100, 100)

# Apply Levy flight
new_position = add_levy_flight_to_position(
    position=current_position,
    best_position=best_position,
    bounds=bounds,
    iteration=10,
    max_iterations=100,
    beta=1.5  # Levy exponent
)

print(f"Position after Levy flight: {new_position}")
```

---

## Flask Web Interface

### Accessing the Web UI

1. **Start the server**:
   ```bash
   python -m mha_toolbox ui
   ```

2. **Open browser**:
   Navigate to http://127.0.0.1:5000

3. **Login**:
   - Username: `admin`
   - Password: `admin123`

### Web Interface Features

#### 1. Dashboard
- **Statistics Overview**: Total algorithms, experiments, success rate
- **Recent Results**: Latest optimization runs
- **Custom Algorithms**: User-submitted algorithms
- **Quick Actions**: Run optimization, compare algorithms

#### 2. Optimization Page
- **Algorithm Selection**: Choose from 142+ algorithms
- **Dataset Upload**: Upload CSV datasets
- **Parameter Configuration**: Set population size, iterations, etc.
- **Real-Time Progress**: Live convergence plot
- **Results Download**: Export as JSON, CSV, Excel, PDF

#### 3. Algorithm Comparison
- **Multi-Algorithm**: Compare up to 10 algorithms simultaneously
- **Benchmark Functions**: Test on standard optimization problems
- **Statistical Analysis**: Mean, std, best, worst fitness
- **Visualization**: Side-by-side convergence plots

#### 4. Custom Algorithm Upload
- **File Upload**: Submit custom MHA algorithms
- **Validation**: Automatic syntax and structure checking
- **GitHub Integration**: Automatic PR creation for review
- **Integration**: Approved algorithms added to library

#### 5. History & Results
- **Personal History**: All optimization runs
- **Filter & Search**: By algorithm, date, fitness
- **Rerun**: Repeat experiments with same parameters
- **Export**: Download results in multiple formats

### REST API Endpoints

#### Authentication

```bash
# Register new user
POST /api/auth/register
{
  "username": "newuser",
  "email": "user@example.com",
  "password": "password123"
}

# Login
POST /api/auth/login
{
  "username": "admin",
  "password": "admin123"
}
```

#### Algorithms

```bash
# Get all algorithms
GET /api/algorithms

# Get algorithms by category
GET /api/algorithms?category=swarm

# Get algorithm details
GET /api/algorithm/pso
```

#### Optimization

```bash
# Run optimization
POST /api/optimize
{
  "algorithms": ["pso", "gwo"],
  "objective_function": "sphere",
  "population_size": 30,
  "max_iterations": 100,
  "dimensions": 10,
  "lower_bound": -100,
  "upper_bound": 100
}

# Get optimization history
GET /api/history

# Delete result
DELETE /api/history/1

# Rerun optimization
POST /api/history/1/rerun
```

#### Recommendations

```bash
# Get algorithm recommendations
POST /api/recommend
{
  "problem_type": "continuous",
  "dimensions": 10,
  "multimodal": true,
  "has_constraints": false
}
```

---

## Algorithm Catalog

### Swarm Intelligence (50+ algorithms)

| Code | Full Name | Year | Authors |
|------|-----------|------|---------|
| **PSO** | Particle Swarm Optimization | 1995 | Kennedy, Eberhart |
| **GWO** | Grey Wolf Optimizer | 2014 | Mirjalili et al. |
| **WOA** | Whale Optimization Algorithm | 2016 | Mirjalili, Lewis |
| **SSA** | Salp Swarm Algorithm | 2017 | Mirjalili et al. |
| **ALO** | Ant Lion Optimizer | 2015 | Mirjalili |
| **GOA** | Grasshopper Optimization Algorithm | 2017 | Saremi et al. |
| **HHO** | Harris Hawks Optimization | 2019 | Heidari et al. |
| **JS** | Jellyfish Search | 2020 | Chou, Truong |
| **HBA** | Honey Badger Algorithm | 2021 | Hashim et al. |
| **MPA** | Marine Predators Algorithm | 2020 | Faramarzi et al. |
| **SMA** | Slime Mould Algorithm | 2020 | Li et al. |
| **ChOA** | Chimp Optimization Algorithm | 2020 | Khishe, Mosavi |
| **AO** | Aquila Optimizer | 2021 | Abualigah et al. |
| **RSA** | Reptile Search Algorithm | 2022 | Abualigah et al. |
| **GTO** | Gorilla Troops Optimizer | 2021 | Abdollahzadeh et al. |

### Evolutionary Algorithms (20+ algorithms)

| Code | Full Name | Year | Authors |
|------|-----------|------|---------|
| **GA** | Genetic Algorithm | 1975 | Holland |
| **DE** | Differential Evolution | 1997 | Storn, Price |
| **ABC** | Artificial Bee Colony | 2005 | Karaboga |
| **EP** | Evolutionary Programming | 1966 | Fogel et al. |
| **ES** | Evolution Strategy | 1973 | Rechenberg |

### Physics-Based (15+ algorithms)

| Code | Full Name | Year | Authors |
|------|-----------|------|---------|
| **SA** | Simulated Annealing | 1983 | Kirkpatrick et al. |
| **GSA** | Gravitational Search Algorithm | 2009 | Rashedi et al. |
| **MVO** | Multi-Verse Optimizer | 2016 | Mirjalili et al. |
| **EO** | Equilibrium Optimizer | 2020 | Faramarzi et al. |
| **AOA** | Arithmetic Optimization Algorithm | 2021 | Abualigah et al. |

### Hybrid Algorithms (30+ algorithms)

| Code | Full Name | Description |
|------|-----------|-------------|
| **PSO-GA** | PSO + Genetic Algorithm | Combines swarm and evolutionary |
| **GWO-PSO** | GWO + PSO | Enhanced exploration-exploitation |
| **DE-PSO** | DE + PSO | Differential evolution with PSO |
| **JS-PSO** | JS + PSO | Jellyfish search hybrid |
| **HBA-GWO** | HBA + GWO | Honey badger with grey wolf |
| **MPA-DE** | MPA + DE | Marine predators with DE |
| **SMA-GA** | SMA + GA | Slime mould with genetic |
| **AO-WOA** | AO + WOA | Aquila with whale optimization |

### Custom Algorithms

User-submitted algorithms approved through GitHub PR workflow.

---

## Examples and Tutorials

### Example 1: Feature Selection on Iris Dataset

```python
from mha_toolbox import optimize
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# Load dataset
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# Run PSO for feature selection
result = optimize('pso', X_train, y_train, 
                 population_size=30, 
                 max_iterations=50)

# Get selected features
selected_features = result.selected_features_

# Train model with selected features
X_train_selected = X_train[:, selected_features]
X_test_selected = X_test[:, selected_features]

clf = RandomForestClassifier()
clf.fit(X_train_selected, y_train)
y_pred = clf.predict(X_test_selected)

print(f"Accuracy: {accuracy_score(y_test, y_pred):.2%}")
print(f"Selected {len(selected_features)}/{X.shape[1]} features")
```

### Example 2: Function Optimization (Sphere Function)

```python
from mha_toolbox import optimize
import numpy as np

# Define objective function
def sphere(x):
    """Sphere function: f(x) = sum(x_i^2)"""
    return np.sum(x**2)

# Run optimization
result = optimize(
    'gwo',  # Grey Wolf Optimizer
    objective_function=sphere,
    dimensions=10,
    population_size=30,
    max_iterations=100,
    bounds=(-100, 100)
)

print(f"Best fitness: {result.best_fitness_:.6f}")
print(f"Best solution: {result.best_position_}")
print(f"Execution time: {result.execution_time_:.2f}s")
```

### Example 3: Compare Multiple Algorithms

```python
from mha_toolbox import compare_algorithms

# Compare algorithms
results = compare_algorithms(
    algorithms=['pso', 'gwo', 'sca', 'woa', 'ssa'],
    X=X, y=y,
    runs=10  # Run each algorithm 10 times
)

# Display statistical comparison
for algo, stats in results.items():
    print(f"{algo}:")
    print(f"  Mean: {stats['mean']:.4f}")
    print(f"  Std:  {stats['std']:.4f}")
    print(f"  Best: {stats['best']:.4f}")
    print(f"  Worst: {stats['worst']:.4f}")
```

### Example 4: Using Flask REST API

```python
import requests

# Start the Flask server first: python -m mha_toolbox ui

# Login
login_response = requests.post('http://localhost:5000/api/auth/login', json={
    'username': 'admin',
    'password': 'admin123'
})
print(login_response.json())

# Get algorithm recommendations
recommend_response = requests.post('http://localhost:5000/api/recommend', json={
    'problem_type': 'continuous',
    'dimensions': 10,
    'multimodal': True
})
print(recommend_response.json()['recommendations'])

# Run optimization
optimize_response = requests.post('http://localhost:5000/api/optimize', json={
    'algorithms': ['pso'],
    'objective_function': 'sphere',
    'population_size': 30,
    'max_iterations': 100,
    'dimensions': 10,
    'lower_bound': -100,
    'upper_bound': 100
})
print(optimize_response.json())
```

### Example 5: Parallel Algorithm Comparison

```python
from mha_toolbox.parallel_optimizer import parallel_compare
from sklearn.datasets import load_breast_cancer

# Load dataset
X, y = load_breast_cancer(return_X_y=True)

# Run 8 algorithms in parallel on 4 cores
results = parallel_compare(
    algorithms=['pso', 'gwo', 'sca', 'woa', 'ssa', 'alo', 'hho', 'js'],
    X=X, y=y,
    n_jobs=4,
    population_size=30,
    max_iterations=50
)

# Sort by fitness
sorted_results = sorted(results.items(), 
                       key=lambda x: x[1].best_fitness, 
                       reverse=True)

print("Algorithm Ranking:")
for rank, (name, result) in enumerate(sorted_results, 1):
    print(f"{rank}. {name}: {result.best_fitness:.4f}")
```

---

## Troubleshooting

### Common Issues

#### 1. Module Not Found Error

**Error**: `ModuleNotFoundError: No module named 'mha_toolbox'`

**Solution**:
```bash
# Ensure package is installed
pip install -e .

# Or install from PyPI
pip install mha-flow
```

#### 2. Flask Dependencies Missing

**Error**: `ImportError: cannot import name 'Flask'`

**Solution**:
```bash
# Install Flask dependencies
pip install -r requirements.txt

# Or install with UI support
pip install -e .[ui]
```

#### 3. Port Already in Use

**Error**: `OSError: [Errno 98] Address already in use`

**Solution**:
```bash
# Use a different port
python -m mha_toolbox ui --port 8080

# Or kill process using port 5000
# Windows:
netstat -ano | findstr :5000
taskkill /PID <PID> /F

# Linux/macOS:
lsof -i :5000
kill <PID>
```

#### 4. Database Errors

**Error**: `sqlalchemy.exc.OperationalError: no such table`

**Solution**:
```bash
# Reset and reinitialize database
python init_db.py full
```

#### 5. Import Errors for Specific Algorithms

**Error**: `ImportError: cannot import name 'PSO'`

**Solution**:
```python
# Use string name instead of direct import
from mha_toolbox import optimize
result = optimize('pso', X, y)  # Use 'pso' string, not PSO class
```

#### 6. Memory Errors with Large Datasets

**Error**: `MemoryError`

**Solution**:
```python
# Use robust optimization for large datasets
from mha_toolbox.robust_optimization import optimize_for_large_dataset

result = optimize_for_large_dataset(
    'pso', X, y,
    batch_size=1000,  # Process in batches
    n_jobs=2  # Reduce parallel processes
)
```

#### 7. Slow Convergence

**Issue**: Algorithm takes too long or doesn't converge

**Solution**:
```python
# Enable Levy flight for better exploration
result = optimize('pso', X, y, levy_enabled=True)

# Or try hybrid algorithms
result = optimize('pso_gwo', X, y)  # PSO-GWO hybrid

# Reduce problem size
result = optimize('gwo', X, y, 
                 max_iterations=50,  # Reduce iterations
                 population_size=20)  # Reduce population
```

---

## Advanced Features

### 1. Hyperparameter Tuning

```python
from mha_toolbox.hyperparameter_tuning import HyperparameterTuner

# Initialize tuner
tuner = HyperparameterTuner()

# Define parameter grid
param_grid = {
    'population_size': [20, 30, 50],
    'w': [0.5, 0.7, 0.9],  # PSO inertia weight
    'c1': [1.5, 2.0, 2.5],  # PSO cognitive parameter
    'c2': [1.5, 2.0, 2.5]   # PSO social parameter
}

# Tune hyperparameters
best_params = tuner.grid_search(
    algorithm='pso',
    X=X, y=y,
    param_grid=param_grid,
    cv=5  # 5-fold cross-validation
)

print(f"Best parameters: {best_params}")
```

### 2. Custom Objective Functions

```python
# Define custom benchmark function
def rosenbrock(x):
    """Rosenbrock function"""
    return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)

# Optimize custom function
result = optimize(
    'gwo',
    objective_function=rosenbrock,
    dimensions=10,
    bounds=(-5, 10),
    population_size=50,
    max_iterations=200
)
```

### 3. Save and Load Results

```python
from mha_toolbox.results_manager import ResultsManager

# Initialize manager
manager = ResultsManager()

# Run optimization
result = optimize('pso', X, y)

# Save result
manager.save_result(result, filename='pso_experiment_1.pkl')

# Load result later
loaded_result = manager.load_result('pso_experiment_1.pkl')

# Export to multiple formats
manager.export_to_csv(result, 'results.csv')
manager.export_to_excel(result, 'results.xlsx')
manager.export_to_json(result, 'results.json')
```

### 4. Advanced Visualization

```python
from mha_toolbox.advanced_visualization import AdvancedVisualizer

# Initialize visualizer
viz = AdvancedVisualizer()

# Plot convergence curve
viz.plot_convergence(result, save_path='convergence.png')

# Plot 3D search space
viz.plot_3d_search_space(result, save_path='search_space.png')

# Plot feature importance
viz.plot_feature_importance(result, save_path='features.png')

# Generate comprehensive report
viz.generate_report(result, output_path='report.pdf')
```

### 5. Multi-Objective Optimization

```python
from mha_toolbox.advanced_hybrid import AdvancedHybridOptimizer

# Initialize multi-objective optimizer
optimizer = AdvancedHybridOptimizer()

# Define multiple objectives
def objective1(x):
    return np.sum(x**2)  # Minimize sum of squares

def objective2(x):
    return np.sum(np.abs(x))  # Minimize sum of absolute values

# Run multi-objective optimization
pareto_front = optimizer.multi_objective_optimize(
    objectives=[objective1, objective2],
    dimensions=10,
    bounds=(-100, 100),
    population_size=100,
    max_iterations=200
)

print(f"Pareto solutions found: {len(pareto_front)}")
```

### 6. Real-Time Monitoring

```python
# Define callback for real-time monitoring
def callback(iteration, best_fitness, population):
    print(f"Iteration {iteration}: Best Fitness = {best_fitness:.6f}")
    # Add custom logic (e.g., early stopping, logging)

# Run with callback
result = optimize('pso', X, y, 
                 callback=callback,
                 callback_interval=10)  # Call every 10 iterations
```

---

## Conclusion

This comprehensive lab manual provides everything needed to:
- ✅ Install and configure MHA Flow
- ✅ Use the command-line interface
- ✅ Leverage the Python API
- ✅ Access the Flask web interface
- ✅ Understand all 142+ algorithms
- ✅ Run optimization experiments
- ✅ Troubleshoot common issues
- ✅ Utilize advanced features

### Additional Resources

- **GitHub Repository**: https://github.com/Achyut103040/MHA-Algorithm
- **Documentation Wiki**: https://github.com/Achyut103040/MHA-Algorithm/wiki
- **Issue Tracker**: https://github.com/Achyut103040/MHA-Algorithm/issues
- **Discussions**: https://github.com/Achyut103040/MHA-Algorithm/discussions

### Support

For questions or issues:
1. Check this manual first
2. Search existing GitHub issues
3. Create a new issue with:
   - Error message
   - Code snippet
   - Python version
   - Operating system

---

**Version**: 2.0.7  
**Last Updated**: February 2026  
**License**: MIT  
**Made with ❤️ by the MHA Flow Team**
