awraf-toolkit 0.1.0
Adaptive Weight-Based Resource Allocation Framework for 6G IoT with THz Links and Intelligent Surfaces
Requires Python: >=3.7
Keywords: iot, 6g, resource-allocation, edge-computing, thz, irs, machine-learning, reinforcement-learning, optimization, simulation, wireless-networks, federated-learning

# AWRAF Toolkit: Adaptive Weight-Based Resource Allocation Framework for 6G IoT

[![Python 3.7+](https://img.shields.io/badge/python-3.7+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![PyPI version](https://badge.fury.io/py/awraf-toolkit.svg)](https://badge.fury.io/py/awraf-toolkit)

A comprehensive Python toolkit for the **Adaptive Weight-Based Resource Allocation Framework (AWRAF)**, designed for dynamic resource management in 6G IoT environments with Terahertz (THz) links and Intelligent Reflecting Surfaces (IRS).

## 🚀 Features

- **Realistic 6G Scenarios**: Smart Healthcare (IRS-THz), Smart Transportation (V2X-THz), and Baseline IoT environments
- **Adaptive Resource Allocation**: Dynamic adjustment of allocation weights based on real-time system conditions
- **Multiple Algorithms**: AWRAF (Dynamic/Static), Greedy, and Reinforcement Learning baselines
- **Statistical Validation**: Comprehensive performance analysis with confidence intervals and t-tests
- **Scalability Analysis**: Performance evaluation under varying device and server loads
- **Command-Line Interface**: Easy-to-use CLI for quick simulations without coding
- **Modern Python**: Type hints, dataclasses, and clean architecture

## 📦 Installation

### From PyPI (Recommended)
```bash
pip install awraf-toolkit
```

### From Source
```bash
git clone https://github.com/afrilab/awraf.git
cd awraf
pip install -e .
```

## 🎯 Quick Start

### **Option 1: Command Line (Easiest)**

Run simulations directly from the command line:

```bash
# Install the package
pip install awraf-toolkit

# Quick demo
awraf-sim --demo

# Custom simulation
awraf-sim --scenarios "SMART_HEALTHCARE:50:10" --algorithms "AWRAF_DYNAMIC,GREEDY" --trials 30
```

### **Option 2: Python API**

Use the Python interface for more control:

```python
import numpy as np
from awraf import AWRAFSimulator, ScenarioType, AlgorithmType
from awraf import run_statistical_analysis, analyze_and_plot, print_summary_table

# Set random seeds for reproducibility
np.random.seed(42)

# Define your simulation parameters
scenarios = [
    (ScenarioType.SMART_HEALTHCARE, 50, 10),
    (ScenarioType.SMART_TRANSPORTATION, 60, 12),
    (ScenarioType.BASELINE_IOT, 40, 10)
]

algorithms = [
    AlgorithmType.AWRAF_DYNAMIC,
    AlgorithmType.AWRAF_STATIC,
    AlgorithmType.GREEDY,
    AlgorithmType.RL_BASED
]

# Run comprehensive analysis
results = run_statistical_analysis(scenarios, algorithms, num_trials=30)
aggregated = analyze_and_plot(results, scenarios)
print_summary_table(aggregated, results)
```

## 📚 API Reference

### Core Classes

| Class | Description | Key Methods |
|-------|-------------|-------------|
| `AWRAFSimulator` | Main simulation engine for resource allocation | `run_simulation(max_iterations=100)` |
| `IoTDevice` | Represents IoT devices with 6G characteristics | Data class with device properties |
| `EdgeServer` | Represents edge servers with 6G capabilities | Data class with server properties |
| `ScenarioGenerator` | Generates realistic IoT scenarios | `generate_scenario()` |
| `RLAgent` | Q-learning agent for reinforcement learning | `choose_action(state)`, `update_q_table(...)` |

### Enums

| Enum | Values | Description |
|------|--------|-------------|
| `ScenarioType` | `SMART_HEALTHCARE`, `SMART_TRANSPORTATION`, `BASELINE_IOT` | Available IoT scenarios |
| `AlgorithmType` | `AWRAF_DYNAMIC`, `AWRAF_STATIC`, `GREEDY`, `RL_BASED` | Resource allocation algorithms |

### Main Functions

| Function | Parameters | Returns | Description |
|----------|------------|---------|-------------|
| `run_statistical_analysis(scenarios, algorithms, num_trials=30)` | `scenarios`: List of (ScenarioType, devices, servers)<br>`algorithms`: List of AlgorithmType<br>`num_trials`: Number of simulation runs | `pandas.DataFrame` | Runs multiple simulation trials for statistical validation |
| `analyze_and_plot(df_stats, scenarios_config)` | `df_stats`: Statistical results DataFrame<br>`scenarios_config`: Scenarios configuration | `pandas.DataFrame` | Creates comprehensive plots and returns aggregated results |
| `print_summary_table(df_agg, df_stats)` | `df_agg`: Aggregated results<br>`df_stats`: Statistical results | `None` | Prints formatted performance comparison table |

### Data Models

#### IoTDevice Attributes
- `device_id`: Unique identifier
- `task_size`: Computational task size
- `latency_tolerance`: Maximum acceptable latency
- `energy_constraint`: Energy consumption limit
- `device_type`: Type of IoT device
- `scenario`: Associated scenario type
- `mobility_speed`: Device movement speed
- `federated_learning_capable`: FL support flag
- `thz_frequency`: THz frequency band
- `data_to_upload`: Data size for uplink
- `model_size_downlink`: Model size for downlink

#### EdgeServer Attributes
- `server_id`: Unique identifier
- `computational_capacity`: Processing power
- `bandwidth`: Network bandwidth
- `energy_capacity`: Energy storage
- `server_type`: Type of edge server
- `irs_elements`: Number of IRS elements
- `thz_bandwidth`: THz bandwidth capacity
- `supports_federated_learning`: FL support flag
- `current_load`: Current computational load
- `allocated_devices`: List of assigned devices

## 🔬 Usage Examples

### Basic Simulation
```python
from awraf import AWRAFSimulator, ScenarioType, AlgorithmType

# Create simulator for healthcare scenario
sim = AWRAFSimulator(
    scenario_type=ScenarioType.SMART_HEALTHCARE,
    algorithm=AlgorithmType.AWRAF_DYNAMIC,
    num_devices=50,
    num_servers=10
)

# Run simulation
history = sim.run_simulation(max_iterations=100)

# Access results
print(f"Average device utility: {np.mean(history['device_utility']):.3f}")
print(f"Success rate: {history['allocation_success_rate'][-1]*100:.1f}%")
```

### Custom Scenario Analysis
```python
from awraf import run_statistical_analysis, ScenarioType, AlgorithmType

# Define custom scenarios
custom_scenarios = [
    (ScenarioType.SMART_HEALTHCARE, 100, 20),    # 100 devices, 20 servers
    (ScenarioType.SMART_TRANSPORTATION, 200, 40), # 200 devices, 40 servers
]

# Compare algorithms
algorithms = [AlgorithmType.AWRAF_DYNAMIC, AlgorithmType.GREEDY]

# Run analysis with 50 trials
results = run_statistical_analysis(custom_scenarios, algorithms, num_trials=50)
```

### Performance Comparison
```python
from awraf import analyze_and_plot, print_summary_table

# Analyze and visualize results
aggregated = analyze_and_plot(results, custom_scenarios)

# Print comprehensive summary
print_summary_table(aggregated, results)
```

## 📊 Output Analysis

The toolkit provides comprehensive analysis including:

- **Device Utility**: Normalized utility scores with confidence intervals
- **Server Load**: Load balancing efficiency across edge servers
- **Allocation Success Rate**: Percentage of successful resource allocations
- **Communication Delay**: Network latency analysis
- **Scalability**: Performance under varying device/server ratios
- **Statistical Significance**: T-test results comparing algorithms

## 🏗️ Project Structure

```
awraf-toolkit/
├── awraf/                    # Main package
│   ├── __init__.py          # Package initialization
│   ├── simulator.py         # Core simulation engine
│   ├── models.py            # Data models (IoTDevice, EdgeServer)
│   ├── enums.py             # Enums for scenarios and algorithms
│   ├── scenario.py          # Scenario generation
│   ├── algorithm.py         # RL agent implementation
│   └── utils.py             # Analysis and plotting utilities
├── examples/                 # Usage examples
│   └── run_simulation.py    # Complete simulation example
├── tests/                    # Unit tests
├── README.md                 # This file
├── setup.py                  # Package configuration
└── requirements.txt          # Dependencies
```

## 🖥️ Command-Line Interface (CLI)

The AWRAF Toolkit includes a powerful command-line interface that makes it easy to run simulations without writing Python code.

### **Installation & Usage**

After installing the package, you'll have access to the `awraf-sim` command:

```bash
# Install the package
pip install awraf-toolkit

# Check if CLI is available
awraf-sim --help
```

### **Quick Demo**

Run a quick demonstration with default scenarios:

```bash
awraf-sim --demo
```

This runs a 10-trial simulation with:
- Smart Healthcare: 30 devices, 6 servers
- Smart Transportation: 40 devices, 8 servers  
- Baseline IoT: 25 devices, 5 servers
- Algorithms: AWRAF Dynamic vs Greedy

### **Custom Simulations**

#### **Basic Single Scenario**
```bash
awraf-sim --scenarios "SMART_HEALTHCARE:50:10" --algorithms "AWRAF_DYNAMIC"
```

#### **Multiple Scenarios & Algorithms**
```bash
awraf-sim --scenarios "SMART_HEALTHCARE:50:10,SMART_TRANSPORTATION:60:12" --algorithms "AWRAF_DYNAMIC,GREEDY" --trials 50
```

#### **With Custom Random Seed**
```bash
awraf-sim --scenarios "BASELINE_IOT:100:20" --algorithms "AWRAF_DYNAMIC,RL_BASED" --trials 100 --seed 42
```

### **CLI Parameters**

| Parameter | Description | Example | Default |
|-----------|-------------|---------|---------|
| `--scenarios` | Comma-separated scenarios in format "scenario:devices:servers" | `"SMART_HEALTHCARE:50:10"` | Required |
| `--algorithms` | Comma-separated algorithms to compare | `"AWRAF_DYNAMIC,GREEDY"` | Required |
| `--trials` | Number of simulation trials | `50` | `30` |
| `--demo` | Run demo with default settings | `--demo` | False |
| `--seed` | Random seed for reproducibility | `42` | Random |

### **Available Scenarios**
- `SMART_HEALTHCARE`: Healthcare IoT with IRS-THz capabilities
- `SMART_TRANSPORTATION`: V2X transportation with THz links
- `BASELINE_IOT`: Standard IoT environment

### **Available Algorithms**
- `AWRAF_DYNAMIC`: AWRAF with adaptive weights
- `AWRAF_STATIC`: AWRAF with fixed weights
- `GREEDY`: Greedy resource allocation
- `RL_BASED`: Reinforcement learning approach

### **CLI Output**

The CLI provides:
- 📊 **Configuration Summary**: Shows selected scenarios, algorithms, and trials
- ⏳ **Progress Updates**: Real-time trial progress
- 📈 **Statistical Analysis**: T-test results and performance metrics
- 🎨 **Visualization**: Comprehensive plots and charts
- 📋 **Summary Table**: Formatted performance comparison

### **Example CLI Session**

```bash
$ awraf-sim --scenarios "SMART_HEALTHCARE:40:8" --algorithms "AWRAF_DYNAMIC,GREEDY" --trials 20

🚀 Running AWRAF Toolkit Demo...
📊 Scenarios: ['SMART_HEALTHCARE(40 devices, 8 servers)']
🔧 Algorithms: ['AWRAF_DYNAMIC', 'GREEDY']
🔄 Trials: 20

⏳ Running statistical analysis...
Running Statistical Validation (20 trials)...
  Trial 1/20...
  Trial 2/20...
  [...]
  Trial 20/20...

📈 Generating plots and analysis...
--- T-Test Results (p-value for Device Utility) ---
Scenario: Smart Healthcare (IRS-THz)
  vs Greedy Allocation: p-value = 0.0234 (Significant Improvement)

📋 Printing summary table...
[Comprehensive performance summary table]

✅ Analysis complete!
```

## 🧪 Testing

Run the test suite to ensure everything works correctly:

```bash
# Install in development mode
pip install -e .

# Run tests
python -m pytest tests/ -v

# Run example
python examples/run_simulation.py

# Test CLI
awraf-sim --demo
```

## 📋 Requirements

- Python 3.7+
- numpy
- matplotlib
- pandas
- seaborn
- scipy
- tabulate

## 🤝 Contributing

We welcome contributions! Please feel free to:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Submit a pull request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 📖 Citation

If you use this toolkit in your research, please cite:

```bibtex
@article{awraf2024,
  title={AWRAF: An Energy-Aware Adaptive Weight-Based Resource Allocation Framework for IoT with THz Links and Intelligent Surfaces},
  author={Agrawal, Kushagra and Ayaz, Ferheen and Goktas, Polat},
  journal={arXiv preprint},
  year={2024}
}
```