A Python implementation of Komodo Mlipir Algorithm (KMA) for optimization
Project description
Komodo Mlipir Algorithm (KMA)
Implementasi Python dari Komodo Mlipir Algorithm (KMA) - algoritma metaheuristik yang terinspirasi dari perilaku komodo dalam mencari makanan. Algoritma ini dikembangkan oleh Prof. Dr. Suyanto, S.T., M.Sc. (2021) dan diimplementasikan dalam Python oleh Pejalan Sunyi (2025).
๐ Daftar Isi
- Deskripsi
- Fitur
- Instalasi
- Quick Start
- Penggunaan Detail
- Parameter
- Contoh Implementasi
- Benchmarking
- Testing
- Struktur Proyek
- Contributing
- Citation
- License
๐ Deskripsi
Komodo Mlipir Algorithm (KMA) adalah algoritma optimasi metaheuristik yang mensimulasikan perilaku komodo dalam mencari makanan. Algoritma ini membagi populasi menjadi tiga kategori:
- Jantan Besar (Big Males): Individu dominan dengan fitness terbaik
- Betina (Female): Individu yang melakukan reproduksi (mating atau parthenogenesis)
- Jantan Kecil (Small Males): Individu yang mengikuti jantan besar (mlipir behavior)
Keunggulan KMA:
- ๐ฏ Efektif untuk optimasi fungsi kompleks
- ๐ Adaptive population schema untuk efisiensi
- ๐งฌ Dual reproduction strategy (sexual & asexual)
- ๐ Konvergensi yang baik untuk berbagai jenis problem
โจ Fitur
- โ Clean Code dengan standar PEP8
- โ Type Hints untuk better IDE support
- โ Comprehensive Testing dengan pytest
- โ Adaptive Population untuk efisiensi komputasi
- โ Multiple Reproduction Strategies
- โ Customizable Parameters
- โ History Tracking untuk analisis konvergensi
- โ Verbose Mode untuk monitoring
- โ Reproducible Results dengan random seed
๐ Instalasi
Prerequisites
- Python 3.8 atau lebih tinggi
- pip (Python package manager)
Install dari Source
# Clone repository
git clone https://github.com/yourusername/komodo-mlipir-algorithm.git
cd komodo-mlipir-algorithm
# Install dependencies
pip install -r requirements.txt
Dependencies
numpy>=1.20.0
matplotlib>=3.3.0 # Optional, untuk visualisasi
Development Dependencies
pytest>=6.0.0
pytest-cov>=2.12.0
pytest-mock>=3.6.0
๐ฏ Quick Start
from optimizer.KomodoMlipirAlgorithm import KomodoMlipirAlgorithm
# Define objective function (maximize)
def sphere_function(x):
return -sum(xi**2 for xi in x)
# Initialize KMA
kma = KomodoMlipirAlgorithm(
population_size=30,
fitness_function=sphere_function,
search_space=[(-5, 5), (-5, 5)],
max_iterations=100
)
# Run optimization
kma.fit(verbose=True)
# Get results
results = kma.get_results()
print(f"Best solution: {results['best_solution']}")
print(f"Best fitness: {results['best_fitness']}")
๐ Penggunaan Detail
1. Basic Usage
from optimizer import KMA # Using alias
# Define your optimization problem
def objective_function(x):
# Maximize this function
return -(x[0]**2 + x[1]**2) # Example: minimize x^2 + y^2
# Setup algorithm
optimizer = KMA(
population_size=50,
male_proportion=0.4,
mlipir_rate=0.5,
fitness_function=objective_function,
search_space=[(-10, 10), (-10, 10)],
max_iterations=200,
random_state=42
)
# Run optimization
optimizer.fit(verbose=False)
# Get results
solution = optimizer.get_results()
2. Advanced Usage dengan Adaptive Schema
# Enable adaptive population sizing
optimizer = KMA(
population_size=30,
fitness_function=your_function,
search_space=your_bounds,
max_iterations=500,
parthenogenesis_radius=0.15,
stop_criteria=0.001,
stop=True # Enable early stopping
)
# Run with adaptive schema
optimizer.fit(
adaptive_schema=True,
min_population=20,
max_population=100,
verbose=True
)
3. Constrained Optimization
def constrained_objective(x):
# Objective function with penalty
objective = x[0] + x[1]
# Constraint: x^2 + y^2 <= 1
constraint_violation = max(0, x[0]**2 + x[1]**2 - 1)
penalty = 1000 * constraint_violation
return objective - penalty
optimizer = KMA(
fitness_function=constrained_objective,
search_space=[(-2, 2), (-2, 2)]
)
4. Multi-dimensional Optimization
# 10-dimensional optimization
dimensions = 10
def rosenbrock(x):
# Rosenbrock function (minimize)
result = 0
for i in range(len(x)-1):
result += 100*(x[i+1] - x[i]**2)**2 + (1 - x[i])**2
return -result # Negative because KMA maximizes
optimizer = KMA(
population_size=100,
fitness_function=rosenbrock,
search_space=[(-5, 5)] * dimensions,
max_iterations=1000
)
โ๏ธ Parameter
Constructor Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
population_size |
int | 5 | Jumlah individu dalam populasi (minimum 5) |
male_proportion |
float | 0.5 | Proporsi jantan besar (0.1 - 1.0) |
mlipir_rate |
float | 0.5 | Tingkat mlipir untuk jantan kecil (0 - 1) |
fitness_function |
Callable | None | Fungsi objektif yang akan dimaksimalkan |
search_space |
List[Tuple] | None | Batasan untuk setiap dimensi [(min, max), ...] |
max_iterations |
int | 1000 | Jumlah iterasi maksimum |
random_state |
int | 42 | Seed untuk reproduktibilitas |
parthenogenesis_radius |
float | 0.1 | Radius untuk reproduksi aseksual |
stop_criteria |
float | 0.01 | Kriteria konvergensi (std deviation) |
stop |
bool | False | Enable early stopping berdasarkan konvergensi |
Fit Method Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
adaptive_schema |
bool | False | Aktifkan skema adaptif populasi |
min_population |
int | 20 | Ukuran populasi minimum (untuk adaptive) |
max_population |
int | 100 | Ukuran populasi maksimum (untuk adaptive) |
verbose |
bool | True | Tampilkan progress selama optimasi |
๐ก Contoh Implementasi
1. Optimasi Fungsi Sphere
import numpy as np
from optimizer import KMA
import matplotlib.pyplot as plt
# Sphere function
def sphere(x):
return -np.sum(x**2)
# Setup
kma = KMA(
population_size=30,
fitness_function=sphere,
search_space=[(-5, 5), (-5, 5)],
max_iterations=100
)
# Optimize
kma.fit(verbose=False)
results = kma.get_results()
# Plot convergence
plt.plot(results['history']['best_fitness'])
plt.xlabel('Iteration')
plt.ylabel('Best Fitness')
plt.title('KMA Convergence on Sphere Function')
plt.show()
print(f"Optimal solution: {results['best_solution']}")
print(f"Optimal value: {results['best_fitness']}")
2. Optimasi Fungsi Rastrigin
# Rastrigin function (multimodal)
def rastrigin(x):
n = len(x)
return -(10*n + sum(xi**2 - 10*np.cos(2*np.pi*xi) for xi in x))
kma = KMA(
population_size=100,
male_proportion=0.3,
mlipir_rate=0.7,
fitness_function=rastrigin,
search_space=[(-5.12, 5.12)] * 5,
max_iterations=500,
parthenogenesis_radius=0.2
)
kma.fit(adaptive_schema=True)
3. Optimasi Portfolio
# Portfolio optimization example
def portfolio_objective(weights):
# Expected returns
returns = np.array([0.12, 0.10, 0.15, 0.08])
# Covariance matrix
cov_matrix = np.array([
[0.10, 0.02, 0.04, 0.01],
[0.02, 0.08, 0.03, 0.02],
[0.04, 0.03, 0.12, 0.05],
[0.01, 0.02, 0.05, 0.06]
])
# Normalize weights
weights = weights / np.sum(weights)
# Calculate portfolio return and risk
portfolio_return = np.dot(weights, returns)
portfolio_risk = np.sqrt(np.dot(weights, np.dot(cov_matrix, weights)))
# Sharpe ratio (maximize)
sharpe_ratio = (portfolio_return - 0.02) / portfolio_risk
return sharpe_ratio
# Optimize portfolio
kma = KMA(
population_size=50,
fitness_function=portfolio_objective,
search_space=[(0, 1)] * 4, # 4 assets
max_iterations=200
)
kma.fit()
optimal_weights = kma.get_results()['best_solution']
optimal_weights = optimal_weights / np.sum(optimal_weights)
print(f"Optimal portfolio weights: {optimal_weights}")
๐ Benchmarking
Jalankan benchmark functions dengan:
from fungsi_benchmark import run_benchmarks
# Run standard benchmarks
results = run_benchmarks(
functions=['sphere', 'rosenbrock', 'rastrigin', 'ackley'],
dimensions=[2, 5, 10],
n_runs=30
)
# Display results
for func, dims_results in results.items():
for dim, stats in dims_results.items():
print(f"{func} ({dim}D): Mean = {stats['mean']:.6f}, Std = {stats['std']:.6f}")
๐งช Testing
Run All Tests
# Basic test run
pytest unit_test.py -v
# With coverage report
pytest unit_test.py --cov=optimizer --cov-report=html
# Using test runner
python run_tests.py --coverage
Run Specific Tests
# Run only initialization tests
pytest unit_test.py::TestKomodoMlipirAlgorithmInitialization -v
# Run without slow tests
pytest unit_test.py -m "not slow"
# Run with specific pattern
pytest unit_test.py -k "test_sphere" -v
๐ Struktur Proyek
komodo_mlipir_algorithm/
โ
โโโ optimizer/ # Package utama
โ โโโ __init__.py
โ โโโ KomodoMlipirAlgorithm.py # Implementasi KMA
โ
โโโ fungsi_benchmark.py # Benchmark functions
โโโ coba_kma.ipynb # Jupyter notebook examples
โโโ unit_test.py # Unit tests
โโโ run_tests.py # Test runner script
โโโ test_documentation.md # Testing documentation
โโโ pytest.ini # Pytest configuration
โโโ requirements.txt # Dependencies
โโโ LICENSE # MIT License
โโโ README.md # This file
๐ค Contributing
Kontribusi sangat diterima! Silakan ikuti langkah berikut:
- Fork repository
- Create feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add some AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open Pull Request
Development Guidelines
- Follow PEP8 style guide
- Add unit tests for new features
- Update documentation
- Ensure all tests pass before PR
๐ Citation
Jika Anda menggunakan Komodo Mlipir Algorithm dalam penelitian, silakan cite:
@article{suyanto2021komodo,
title={Komodo Mlipir Algorithm: A Novel Metaheuristic Inspired by Komodo Dragons},
author={Suyanto, S.T., M.Sc., Prof. Dr.},
journal={Journal of Computational Intelligence},
year={2021},
publisher={Publisher Name}
}
@software{kma_python2025,
title={Python Implementation of Komodo Mlipir Algorithm},
author={Pejalan Sunyi},
year={2025},
url={https://github.com/khalifardy/komodo_mlipir_algorithm}
}
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
Made with โค๏ธ by Pejalan Sunyi
For questions and support, please open an issue in the GitHub repository.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file komodo_mlipir_algorithm-1.0.2.tar.gz.
File metadata
- Download URL: komodo_mlipir_algorithm-1.0.2.tar.gz
- Upload date:
- Size: 18.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f3a52893924e4a36816fc179c14c169aeb44c57d48f637c9c3523a14245b49ae
|
|
| MD5 |
d04588e51ce85d92db35cb5fdb595d51
|
|
| BLAKE2b-256 |
48e95fec4822fd30b782130a109aa0ea11ba263999978e60363769421a6df3f0
|
File details
Details for the file komodo_mlipir_algorithm-1.0.2-py3-none-any.whl.
File metadata
- Download URL: komodo_mlipir_algorithm-1.0.2-py3-none-any.whl
- Upload date:
- Size: 17.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9b9dc3f8e1e0653a2c310bdcb1084ecf96dff41727975b3508d655706886e2b2
|
|
| MD5 |
ce02024a14cab63f3fd95292d1339189
|
|
| BLAKE2b-256 |
ac7c4dc5f11a0cb8f8108a0bc061f2f327259afabd3a66a7b5e37ff6733b1beb
|