d weritten # Contributing to MHA Flow

Thank you for your interest in contributing to MHA Flow! This document provides guidelines and instructions for contributing.

## 📋 Table of Contents

- [Code of Conduct](#code-of-conduct)
- [How Can I Contribute?](#how-can-i-contribute)
- [Development Setup](#development-setup)
- [Adding New Algorithms](#adding-new-algorithms)
- [Coding Standards](#coding-standards)
- [Testing Guidelines](#testing-guidelines)
- [Pull Request Process](#pull-request-process)
- [Community](#community)

---

## 📜 Code of Conduct

This project adheres to the Contributor Covenant [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code.

---

## 🤝 How Can I Contribute?

### Reporting Bugs

Before creating bug reports, please check existing issues. When creating a bug report, include:

- **Clear title and description**
- **Steps to reproduce**
- **Expected vs actual behavior**
- **Environment details** (OS, Python version, etc.)
- **Code samples** (if applicable)
- **Error messages and stack traces**

**Template:**
```markdown
**Bug Description:**
A clear description of the bug.

**To Reproduce:**
1. Step one
2. Step two
3. Error occurs

**Expected Behavior:**
What should happen.

**Environment:**
- OS: [e.g., Windows 11]
- Python: [e.g., 3.10.5]
- MHA Flow Version: [e.g., 3.0.0]

**Additional Context:**
Any other relevant information.
```

### Suggesting Enhancements

Enhancement suggestions are tracked as GitHub issues. Include:

- **Clear title and description**
- **Use case and rationale**
- **Proposed solution**
- **Alternative solutions considered**
- **Impact on existing functionality**

### Contributing Code

1. **Fork the repository**
2. **Create a feature branch**
3. **Make your changes**
4. **Add/update tests**
5. **Update documentation**
6. **Submit a pull request**

---

## 🛠️ Development Setup

### Prerequisites

- Python 3.8+
- Git
- Virtual environment tool (venv, conda, etc.)

### Setup Steps

```bash
# 1. Fork and clone the repository
git clone https://github.com/yourusername/MHA-Algorithm.git
cd MHA-Algorithm

# 2. Create a virtual environment
python -m venv venv

# 3. Activate virtual environment
# Windows:
venv\Scripts\activate
# Linux/Mac:
source venv/bin/activate

# 4. Install dependencies
pip install -e .[dev]

# 5. Install pre-commit hooks
pre-commit install

# 6. Run tests to verify setup
pytest tests/
```

### Development Tools

We use the following tools:

- **pytest** - Testing framework
- **black** - Code formatting
- **flake8** - Linting
- **mypy** - Type checking
- **pre-commit** - Git hooks

---

## 🔬 Adding New Algorithms

### Algorithm Structure

All algorithms should follow this structure:

```python
"""
Algorithm Name (Acronym)
========================

Brief description of the algorithm.

Reference:
Author(s). (Year). Paper title. Journal/Conference.

Author: Your Name
License: MIT
"""

import numpy as np
from ..base import BaseOptimizer


class YourAlgorithm(BaseOptimizer):
    """
    Your Algorithm Name (Acronym)
    
    Detailed description of the algorithm including:
    - Inspiration
    - Key mechanisms
    - Parameters
    
    Parameters
    ----------
    population_size : int, default=30
        Number of individuals in population
    max_iterations : int, default=100
        Maximum number of iterations
    param1 : float, default=0.5
        Description of parameter 1
    
    Attributes
    ----------
    algorithm_name : str
        Full name of the algorithm
    aliases : list
        List of alternative names/abbreviations
    
    Examples
    --------
    >>> from mha_toolbox.algorithms.your_algorithm import YourAlgorithm
    >>> algo = YourAlgorithm(population_size=50, max_iterations=200)
    >>> result = algo.optimize(objective_func, bounds=(-100, 100), dimensions=10)
    >>> print(f"Best fitness: {result['best_fitness']}")
    """
    
    def __init__(self, population_size=30, max_iterations=100, param1=0.5, **kwargs):
        super().__init__(population_size, max_iterations, **kwargs)
        self.algorithm_name = "Your Algorithm Name"
        self.aliases = ["acronym", "alternative_name"]
        self.param1 = param1
    
    def _optimize(self, objective_function, bounds, dimension):
        """
        Execute the optimization algorithm.
        
        Parameters
        ----------
        objective_function : callable
            Function to optimize
        bounds : tuple
            (lower_bound, upper_bound)
        dimension : int
            Problem dimensionality
        
        Returns
        -------
        tuple
            (best_solution, best_fitness, convergence_curve)
        """
        lb, ub = bounds
        
        # Initialize population
        population = np.random.uniform(lb, ub, (self.population_size, dimension))
        fitness = np.array([objective_function(ind) for ind in population])
        
        # Track best solution
        best_idx = np.argmin(fitness)
        best_solution = population[best_idx].copy()
        best_fitness = fitness[best_idx]
        convergence_curve = []
        
        # Main optimization loop
        for iteration in range(self.max_iterations):
            # Your algorithm logic here
            for i in range(self.population_size):
                # Update individual
                new_individual = self._update_individual(
                    population[i], best_solution, iteration
                )
                
                # Boundary control
                new_individual = np.clip(new_individual, lb, ub)
                
                # Evaluate
                new_fitness = objective_function(new_individual)
                
                # Update if better
                if new_fitness < fitness[i]:
                    population[i] = new_individual
                    fitness[i] = new_fitness
                    
                    if new_fitness < best_fitness:
                        best_solution = new_individual.copy()
                        best_fitness = new_fitness
            
            convergence_curve.append(best_fitness)
            
            # Optional: Progress logging
            if self.verbose and iteration % 10 == 0:
                print(f"Iteration {iteration}: Best Fitness = {best_fitness:.6e}")
        
        return best_solution, best_fitness, convergence_curve
    
    def _update_individual(self, individual, best_solution, iteration):
        """Helper method for individual update logic"""
        # Your update logic here
        return individual
```

### Adding Levy Flight Support

To add Levy flight support to your algorithm:

```python
from ..levy_flight_universal import add_levy_flight_to_position

# In your optimization loop:
if iteration % 5 == 0:  # Apply every 5 iterations
    new_individual = add_levy_flight_to_position(
        position=new_individual,
        best_position=best_solution,
        bounds=bounds,
        iteration=iteration,
        max_iterations=self.max_iterations
    )
```

### Algorithm Checklist

Before submitting your algorithm, ensure:

- [ ] Follows the structure above
- [ ] Includes comprehensive docstring
- [ ] Has proper parameter descriptions
- [ ] Implements `_optimize` method
- [ ] Returns (best_solution, best_fitness, convergence_curve)
- [ ] Handles boundary constraints
- [ ] Includes reference to original paper
- [ ] Has example usage in docstring
- [ ] Passes all tests
- [ ] Documented in algorithm registry

### Testing Your Algorithm

Create a test file in `tests/test_algorithms/`:

```python
import pytest
import numpy as np
from mha_toolbox.algorithms.your_algorithm import YourAlgorithm


def sphere_function(x):
    """Simple test function"""
    return np.sum(x ** 2)


class TestYourAlgorithm:
    def test_initialization(self):
        algo = YourAlgorithm(population_size=30, max_iterations=100)
        assert algo.population_size == 30
        assert algo.max_iterations == 100
    
    def test_optimize(self):
        algo = YourAlgorithm(population_size=20, max_iterations=50)
        result = algo.optimize(
            sphere_function,
            bounds=(-100, 100),
            dimensions=10
        )
        best_solution, best_fitness, convergence = result
        
        assert len(best_solution) == 10
        assert best_fitness < 100  # Should find better than random
        assert len(convergence) == 50
        assert convergence[-1] <= convergence[0]  # Converging
    
    def test_bounds_respected(self):
        algo = YourAlgorithm(population_size=10, max_iterations=10)
        result = algo.optimize(
            sphere_function,
            bounds=(-50, 50),
            dimensions=5
        )
        best_solution = result[0]
        
        assert np.all(best_solution >= -50)
        assert np.all(best_solution <= 50)
```

---

## 💻 Coding Standards

### Python Style Guide

We follow [PEP 8](https://pep8.org/) with some modifications:

- **Line length**: 100 characters (not 79)
- **Indentation**: 4 spaces
- **Quotes**: Double quotes for strings
- **Naming**:
  - Classes: `PascalCase`
  - Functions/methods: `snake_case`
  - Constants: `UPPER_CASE`
  - Private members: `_leading_underscore`

### Code Formatting

Use `black` for automatic formatting:

```bash
black mha_toolbox/
```

### Type Hints

Use type hints for function signatures:

```python
def optimize(self, 
            objective_function: Callable,
            bounds: Tuple[float, float],
            dimensions: int) -> Tuple[np.ndarray, float, List[float]]:
    pass
```

### Documentation

- All public APIs must have docstrings
- Use NumPy documentation style
- Include examples in docstrings
- Keep documentation up-to-date

Example:

```python
def my_function(param1: int, param2: str = "default") -> bool:
    """
    Brief one-line description.
    
    More detailed description if needed. Can span
    multiple lines.
    
    Parameters
    ----------
    param1 : int
        Description of param1
    param2 : str, default="default"
        Description of param2
    
    Returns
    -------
    bool
        Description of return value
    
    Examples
    --------
    >>> result = my_function(42, "test")
    >>> print(result)
    True
    
    Notes
    -----
    Additional notes if needed.
    
    References
    ----------
    .. [1] Author, "Title", Journal, Year
    """
    return True
```

---

## 🧪 Testing Guidelines

### Running Tests

```bash
# Run all tests
pytest

# Run specific test file
pytest tests/test_algorithms/test_pso.py

# Run with coverage
pytest --cov=mha_toolbox --cov-report=html

# Run with verbose output
pytest -v
```

### Writing Tests

- Place tests in `tests/` directory
- One test file per module
- Use descriptive test names
- Test both success and failure cases
- Aim for >80% code coverage

### Test Categories

1. **Unit Tests**: Test individual functions/methods
2. **Integration Tests**: Test module interactions
3. **Algorithm Tests**: Test algorithm correctness
4. **Performance Tests**: Benchmark algorithm performance

---

## 📥 Pull Request Process

### Before Submitting

1. **Update documentation**
2. **Add/update tests**
3. **Run test suite**: `pytest`
4. **Format code**: `black mha_toolbox/`
5. **Check linting**: `flake8 mha_toolbox/`
6. **Update CHANGELOG.md**

### PR Title Format

```
[Type] Brief description

Types:
- feat: New feature
- fix: Bug fix
- docs: Documentation changes
- style: Code style changes
- refactor: Code refactoring
- test: Test additions/changes
- chore: Maintenance tasks
```

Examples:
- `[feat] Add Jellyfish Search Algorithm`
- `[fix] Correct PSO velocity update formula`
- `[docs] Update installation instructions`

### PR Description Template

```markdown
## Description
Brief description of changes.

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

## Related Issue
Fixes #(issue number)

## Changes Made
- Change 1
- Change 2
- Change 3

## Testing
- [ ] All existing tests pass
- [ ] New tests added
- [ ] Manual testing completed

## Checklist
- [ ] Code follows style guidelines
- [ ] Self-review completed
- [ ] Documentation updated
- [ ] No new warnings generated
- [ ] Tests added/updated
```

### Review Process

1. Automated checks must pass
2. At least one maintainer approval required
3. All comments must be resolved
4. Branch must be up-to-date with main

---

## 🌟 Recognition

Contributors will be:

- Listed in `CONTRIBUTORS.md`
- Credited in release notes
- Acknowledged in documentation
- Featured on project website (if applicable)

---

## 📞 Getting Help

- **Questions**: Use [GitHub Discussions](https://github.com/yourusername/MHA-Algorithm/discussions)
- **Chat**: Join our Discord server
- **Email**: dev@mhaflow.com

---

## 📚 Resources

- [Python Documentation](https://docs.python.org/)
- [NumPy Documentation](https://numpy.org/doc/)
- [SciPy Documentation](https://docs.scipy.org/)
- [Flask Documentation](https://flask.palletsprojects.com/)
- [Testing with pytest](https://docs.pytest.org/)

---

**Thank you for contributing to MHA Flow! 🚀**

Every contribution, no matter how small, helps make this project better for everyone.
