Skip to main content

Crested Porcupine Optimizer (CPO) for optimization problems

Project description

Porcupy: Crested Porcupine Optimizer

CPO

PyPI version License: MIT Python 3.7+ Code Coverage

Overview

Porcupy is a Python library that implements the Crested Porcupine Optimizer (CPO) algorithm, a nature-inspired metaheuristic optimization technique. The algorithm mimics the defensive behaviors of crested porcupines (sight, sound, odor, and physical attack) to balance exploration and exploitation, with cyclic population reduction for convergence.

This library provides both object-oriented and procedural interfaces for the CPO algorithm, along with visualization tools, benchmark functions, and population management utilities. The implementation is thoroughly tested with extensive test coverage across all components.

Features

Core Components

  • Object-oriented implementation with base Optimizer class and CrestPorcupineOptimizer class
  • Procedural API (cpo function) for backward compatibility and simplicity
  • Backend components in porcupines.py with PorcupinePopulation, DefenseMechanisms, and PopulationManager classes

Advanced Capabilities

  • Parallel processing support for faster optimization on multi-core systems
  • Constraint handling for constrained optimization problems
  • Convergence criteria with customizable tolerance and iteration thresholds
  • History tracking for detailed analysis of the optimization process

Population Management

  • Cyclic population reduction strategies (linear, cosine, exponential)
  • Selection strategies for maintaining population diversity
  • Population initialization with various distribution options

Visualization and Analysis

  • 2D and 3D visualization of search spaces and optimization trajectories
  • Convergence plots for monitoring optimization progress
  • Interactive dashboards for real-time monitoring and parameter tuning
  • Animation capabilities for visualizing the optimization process

Testing and Benchmarking

  • Extensive benchmark functions including both unimodal and multimodal test functions
  • Comprehensive test suite with high code coverage (80%+)
  • Parameter sensitivity analysis tools for algorithm tuning

Installation

pip install porcupy

For visualization support, install with the plotting extras:

pip install porcupy[plotting]

For development, install with the dev extras:

pip install porcupy[dev]

Quick Start

Object-Oriented Interface

import numpy as np
from porcupy import CPO
from porcupy.functions import sphere, get_function_bounds
from porcupy.utils.visualization import plot_convergence, plot_2d_search_space

# Define the problem
dimensions = 10
bounds = get_function_bounds('sphere', dimensions)

# Create the optimizer with custom options
optimizer = CPO(
    dimensions=dimensions,
    bounds=bounds,
    pop_size=30,
    max_iter=100,
    options={
        'reduction_strategy': 'cosine',  # Population reduction strategy
        'min_pop_size': 10,              # Minimum population size
        'parallel': True,                # Enable parallel processing
        'defense_weights': [0.3, 0.3, 0.2, 0.2]  # Custom defense mechanism weights
    },
    ftol=1e-6,  # Convergence tolerance
    ftol_iter=5  # Number of iterations for convergence check
)

# Run the optimization with progress tracking
best_pos, best_cost, cost_history = optimizer.optimize(
    objective_func=sphere,
    verbose=True
)

print(f"Best position: {best_pos}")
print(f"Best cost: {best_cost}")

# Visualize the results
plot_convergence(cost_history)

# For 2D problems, visualize the search space
if dimensions == 2:
    plot_2d_search_space(sphere, bounds, positions=optimizer.positions, best_pos=best_pos)

Procedural Interface

import numpy as np
from porcupy.cpo import cpo
from porcupy.functions import rastrigin

# Define the problem
lb = [-5.12] * 2  # Lower bounds
ub = [5.12] * 2   # Upper bounds

# Run the optimization with default parameters
best_pos, best_cost, cost_history = cpo(
    objective_func=rastrigin,
    lb=lb,
    ub=ub,
    pop_size=30,
    max_iter=100,
    verbose=True
)

print(f"Best position: {best_pos}")
print(f"Best cost: {best_cost}")

Documentation

Porcupy comes with comprehensive documentation to help you get started and make the most of the library:

  • User Guide: A step-by-step guide to using Porcupy, including installation, basic usage, advanced features, and examples.
  • API Reference: Detailed documentation of all classes, methods, and functions in the library.
  • Examples: A collection of example scripts demonstrating various features of the library.

The documentation covers:

  • Core optimization algorithms and their parameters
  • Population management strategies
  • Visualization tools and techniques
  • Benchmark functions and their characteristics
  • Advanced usage patterns and customization options

Algorithm

The Crested Porcupine Optimizer (CPO) algorithm is inspired by the defensive behaviors of crested porcupines, which use four distinct mechanisms to protect themselves from predators:

  1. Sight Defense: An exploration mechanism that simulates how porcupines use visual cues to detect threats from a distance. This mechanism helps the algorithm explore new regions of the search space by moving search agents toward random positions.

  2. Sound Defense: Another exploration mechanism that mimics how porcupines use auditory signals to warn others of danger. This mechanism enhances exploration by moving search agents toward positions that combine information from multiple sources.

  3. Odor Defense: An exploitation mechanism inspired by how porcupines use olfactory signals to communicate. This mechanism focuses on refining solutions by moving search agents toward the current best position with controlled randomness.

  4. Physical Attack: The most aggressive exploitation mechanism, representing the porcupine's quill defense. This mechanism intensifies local search around promising solutions by moving search agents directly toward the best position with minimal randomness.

What makes CPO unique is its cyclic population reduction strategy, which periodically reduces the population size to focus computational resources on the most promising solutions. This strategy helps balance exploration and exploitation throughout the optimization process, leading to faster convergence and better solutions for complex problems.

The algorithm dynamically adjusts the influence of each defense mechanism based on the current iteration, gradually shifting from exploration-focused strategies (sight and sound) to exploitation-focused strategies (odor and physical attack) as the optimization progresses.

Citing

If you use Porcupy in your research, please cite the original paper:

@article{article,
author = {Abdel-Basset, Mohamed and Mohamed, Reda and Abouhawwash, Mohamed},
year = {2023},
month = {12},
pages = {111257},
title = {Crested Porcupine Optimizer: A new nature-inspired metaheuristic},
volume = {284},
journal = {Knowledge-Based Systems},
doi = {10.1016/j.knosys.2023.111257}
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Development and Testing

Setting Up the Development Environment

To set up the development environment for contributing to Porcupy:

# Clone the repository
git clone https://github.com/SammanSarkar/Porcupy.git
cd Porcupy

# Install in development mode with all extras
pip install -e .[all]

Code Structure

The Porcupy codebase is organized as follows:

porcupy/
├── __init__.py           # Package initialization
├── cpo.py                # Procedural interface
├── functions.py          # Benchmark functions
├── porcupines.py         # Core algorithm components
├── optimizer.py          # Base optimizer class and CPO implementation
└── utils/                # Utility modules
    ├── helpers.py        # Helper functions
    ├── plotting.py       # Basic plotting utilities
    ├── population.py     # Population management utilities
    ├── visualization.py  # Advanced visualization tools
    └── interactive_visualization.py  # Interactive dashboards
tests/                    # Test suite
docs/                     # Documentation
examples/                 # Example scripts

Running Tests

Porcupy has a comprehensive test suite with over 80% code coverage. To run the tests:

# Run all tests
python -m pytest tests/

# Run tests for a specific module
python -m pytest tests/test_porcupines.py

# Run tests with verbose output
python -m pytest tests/ -v

# Generate test coverage report
python -m pytest tests/ --cov=porcupy

# Generate detailed HTML coverage report
python -m pytest tests/ --cov=porcupy --cov-report=html

Note: Using python -m pytest is recommended over just pytest as it ensures the current directory is in the Python path, which helps with imports.

Continuous Integration

The codebase is continuously tested to ensure high quality and reliability. All pull requests must pass the test suite before being merged.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

porcupy-0.1.0.tar.gz (84.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

porcupy-0.1.0-py3-none-any.whl (56.2 kB view details)

Uploaded Python 3

File details

Details for the file porcupy-0.1.0.tar.gz.

File metadata

  • Download URL: porcupy-0.1.0.tar.gz
  • Upload date:
  • Size: 84.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.5

File hashes

Hashes for porcupy-0.1.0.tar.gz
Algorithm Hash digest
SHA256 b97520fe4f2f561cb3c186ecab78aa3e23bad314071090b49db73c6c38cedf74
MD5 816ad7a3f341d154ca8ed3e1e3fb45d7
BLAKE2b-256 c5c4ae0c41bafc458e38c20fbcb8c1112cfa54c54f3c9a658d13d1baae3fae11

See more details on using hashes here.

File details

Details for the file porcupy-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: porcupy-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 56.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.5

File hashes

Hashes for porcupy-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b36f2f9fc5615ee29b9410f8bbfa34d8bad38039b715d35b027c411fe26d9583
MD5 5340594d280e30cc10d5d6e0e2fa8333
BLAKE2b-256 7cf8554b5c7c684d60919bed719c60ec53510b499e929139a8d84e2ae451af1e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page