fix contract
This commit is contained in:
@@ -0,0 +1,276 @@
|
||||
# AI Genetic Algorithm for Room Reservations
|
||||
|
||||
This module implements a genetic algorithm-based optimization system for intelligent room reservation assignments in educational institutions.
|
||||
|
||||
## Overview
|
||||
|
||||
The system uses genetic algorithms to optimize room assignments taking into account:
|
||||
- Capacity efficiency
|
||||
- Time preferences
|
||||
- Conflict resolution
|
||||
- Resource matching
|
||||
- Student enrollment numbers
|
||||
|
||||
## Key Components
|
||||
|
||||
### 1. Genetic Algorithm Core (`app/models/genetic_algorithm.py`)
|
||||
|
||||
#### Main Classes:
|
||||
- **`ReservationRequest`**: Represents a reservation request from the teaching committee
|
||||
- **`Gene`**: Single reservation assignment (classroom + commission + time)
|
||||
- **`Individual`**: Complete reservation schedule (chromosome)
|
||||
- **`GeneticAlgorithm`**: Main algorithm implementation
|
||||
- **`ReservationOptimizer`**: High-level interface layer
|
||||
|
||||
#### Algorithm Configuration:
|
||||
- **Population Size**: 50 individuals
|
||||
- **Generations**: 100 evolution cycles
|
||||
- **Mutation Rate**: 10%
|
||||
- **Crossover Rate**: 80%
|
||||
|
||||
### 2. API Endpoints (`app/routes/genetic_algorithm.py`)
|
||||
|
||||
- **`POST /api/genetic/optimize`**: Run optimization
|
||||
- **`POST /api/genetic/preview-optimization`**: Preview results without applying
|
||||
- **`POST /api/genetic/apply-optimization`**: Apply optimized reservations
|
||||
- **`GET /api/genetic/commissions`**: Get available commissions
|
||||
- **`GET /api/genetic/algorithm-status`**: Get system status
|
||||
|
||||
### 3. Frontend Interface
|
||||
|
||||
#### Access Point:
|
||||
- **URL**: `/genetic-optimizer`
|
||||
- **Permissions**: Admin and Teacher roles only
|
||||
|
||||
#### Features:
|
||||
- Commission selection interface
|
||||
- Real-time preview of optimization results
|
||||
- Fitness score visualization
|
||||
- Conflict detection and reporting
|
||||
- One-click reservation application
|
||||
|
||||
## Fitness Function Components
|
||||
|
||||
The algorithm optimizes for multiple objectives:
|
||||
|
||||
### 1. Capacity Efficiency (40% weight)
|
||||
- Perfect match: 1.0
|
||||
- <10% waste: 1.0
|
||||
- <30% waste: 0.8
|
||||
- <50% waste: 0.6
|
||||
- >50% waste: 0.4
|
||||
- Overfilled: 0.0
|
||||
|
||||
### 2. Time Preference Satisfaction (30% weight)
|
||||
- Within 30 minutes: 1.0
|
||||
- Within flexibility window: 0.8 - 0.5
|
||||
- Beyond flexibility: max(0.0, 0.5 - penalty)
|
||||
|
||||
### 3. Conflict Penalty (20% weight)
|
||||
- No conflicts: 1.0
|
||||
- Each conflict: -0.5 penalty
|
||||
|
||||
### 4. Resource Matching (10% weight)
|
||||
- Based on classroom resources and subject requirements
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Optimization
|
||||
|
||||
```python
|
||||
from app.models.genetic_algorithm import ReservationOptimizer
|
||||
|
||||
optimizer = ReservationOptimizer()
|
||||
|
||||
# Optimize for specific commissions
|
||||
result = optimizer.optimize_schedule(
|
||||
commission_ids=[1, 2, 3],
|
||||
admin_user_id=1,
|
||||
start_date=datetime(2024, 1, 15),
|
||||
end_date=datetime(2024, 1, 20)
|
||||
)
|
||||
|
||||
print(f"Fitness Score: {result['fitness_score']}")
|
||||
print(f"Reservations Created: {result['assigned_reservations']}")
|
||||
```
|
||||
|
||||
### Applying Optimized Reservations
|
||||
|
||||
```python
|
||||
# Apply to database
|
||||
reservations = optimizer.apply_optimized_reservations(result['reservations'])
|
||||
print(f"Applied {len(reservations)} reservations")
|
||||
```
|
||||
|
||||
### API Usage
|
||||
|
||||
```bash
|
||||
# Preview optimization
|
||||
curl -X POST http://localhost:5000/api/genetic/preview-optimization \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"commission_ids": [1, 2, 3]}'
|
||||
|
||||
# Run full optimization
|
||||
curl -X POST http://localhost:5000/api/genetic/optimize \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"commission_ids": [1, 2, 3]}'
|
||||
|
||||
# Apply reservations
|
||||
curl -X POST http://localhost:5000/api/genetic/apply-optimization \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"reservations": [...]}'
|
||||
```
|
||||
|
||||
## Frontend Integration
|
||||
|
||||
### HTML Template: `app/templates/genetic_optimizer.html`
|
||||
|
||||
The interface provides:
|
||||
- Commission selection with filtering
|
||||
- Real-time algorithm status
|
||||
- Preview vs. full optimization modes
|
||||
- Results visualization
|
||||
- Download functionality for results
|
||||
|
||||
### JavaScript: `app/static/js/genetic-algorithm.js`
|
||||
|
||||
Key features:
|
||||
- AJAX communication with backend
|
||||
- Local storage for intermediate results
|
||||
- Progress indicators
|
||||
- Error handling
|
||||
- CSV export functionality
|
||||
|
||||
## Testing
|
||||
|
||||
### Unit Tests: `tests/test_genetic_algorithm.py`
|
||||
|
||||
Run tests:
|
||||
```bash
|
||||
python -m pytest tests/test_genetic_algorithm.py -v
|
||||
```
|
||||
|
||||
Test coverage includes:
|
||||
- Fitness calculation validation
|
||||
- Conflict detection
|
||||
- Crossover and mutation operations
|
||||
- Tournament selection
|
||||
- Complete optimization process
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Optimization Complexity:
|
||||
- Time Complexity: O(P × G × N) where P=population, G=generations, N=requests
|
||||
- Space Complexity: O(P × N)
|
||||
|
||||
### Scalability:
|
||||
- Handles 50+ reservation requests efficiently
|
||||
- Configurable population size for larger datasets
|
||||
- Parallel evolution possible for very large datasets
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Algorithm Parameters (can be modified in routes):
|
||||
```python
|
||||
genetic_algorithm = GeneticAlgorithm(
|
||||
population_size=100, # Increase for better results
|
||||
generations=200, # Increase for convergence
|
||||
mutation_rate=0.15, # Adjust diversity
|
||||
crossover_rate=0.85 # Adjust inheritance
|
||||
)
|
||||
```
|
||||
|
||||
### Fitness Weights (can be tuned):
|
||||
```python
|
||||
# In Individual.calculate_fitness()
|
||||
score += capacity_score * 0.4 # 40% weight
|
||||
score += time_score * 0.3 # 30% weight
|
||||
score += conflict_score * 0.2 # 20% weight
|
||||
score += resource_score * 0.1 # 10% weight
|
||||
```
|
||||
|
||||
## Monitoring and Debugging
|
||||
|
||||
### Debug Information:
|
||||
- Individual fitness scores
|
||||
- Conflict detection reports
|
||||
- Generation progress
|
||||
- Resource utilization metrics
|
||||
|
||||
### Logging:
|
||||
All major operations are logged with appropriate levels:
|
||||
- INFO: Optimization progress
|
||||
- WARNING: Conflicts detected
|
||||
- ERROR: Algorithm failures
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Planned Features:
|
||||
1. **Multi-objective optimization**: Pareto-optimal solutions
|
||||
2. **Real-time optimization**: Live scheduling updates
|
||||
3. **Machine learning integration**: Historical pattern recognition
|
||||
4. **Advanced resource matching**: Equipment and facility requirements
|
||||
5. **Mobile optimization**: Mobile-friendly interface
|
||||
|
||||
### Algorithm Improvements:
|
||||
1. **Adaptive parameters**: Dynamic mutation/crossover rates
|
||||
2. **Island model**: Multi-population evolution
|
||||
3. **Local search**: Hill climbing integration
|
||||
4. **Constraint handling**: Advanced constraint satisfaction
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Access Control:
|
||||
- Role-based permissions (admin/teacher only)
|
||||
- CSRF token validation
|
||||
- Input sanitization
|
||||
|
||||
### Data Protection:
|
||||
- No sensitive data in genetic representation
|
||||
- Secure API endpoints
|
||||
- Audit logging for all operations
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues:
|
||||
|
||||
1. **Poor optimization results**:
|
||||
- Increase population size
|
||||
- Adjust fitness weights
|
||||
- Check data quality
|
||||
|
||||
2. **Slow performance**:
|
||||
- Reduce population size temporarily
|
||||
- Limit commission selection
|
||||
- Check database performance
|
||||
|
||||
3. **High conflicts**:
|
||||
- Increase flexibility hours
|
||||
- Add more classrooms
|
||||
- Check existing reservations
|
||||
|
||||
### Debug Mode:
|
||||
Add to `app.py` for detailed logging:
|
||||
```python
|
||||
import logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
### Code Style:
|
||||
- Follow PEP 8 conventions
|
||||
- Add comprehensive docstrings
|
||||
- Include type hints
|
||||
- Write unit tests
|
||||
|
||||
### Pull Request Checklist:
|
||||
- [ ] Tests pass
|
||||
- [ ] Documentation updated
|
||||
- [ ] Code follows style guide
|
||||
- [ ] No security vulnerabilities
|
||||
- [ ] Performance acceptable
|
||||
|
||||
## License
|
||||
|
||||
This module is part of the admin-edu-space project and follows the same licensing terms.
|
||||
Reference in New Issue
Block a user