{"id":30114349,"url":"https://github.com/sammansarkar/porcupy","last_synced_at":"2025-08-10T07:40:40.653Z","repository":{"id":296052827,"uuid":"990043470","full_name":"SammanSarkar/Porcupy","owner":"SammanSarkar","description":"A Python library for the Crested Porcupine Optimizer for research and optimization tasks","archived":false,"fork":false,"pushed_at":"2025-06-11T11:28:42.000Z","size":15056,"stargazers_count":4,"open_issues_count":2,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-09T13:58:24.986Z","etag":null,"topics":["algorithms","cpo","crested-porcupine-optimizer","machine-learning","metaheuristics","optimization-algorithms","optimization-tools"],"latest_commit_sha":null,"homepage":"https://porcupy-cpo.readthedocs.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SammanSarkar.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-05-25T11:39:59.000Z","updated_at":"2025-06-11T11:28:46.000Z","dependencies_parsed_at":"2025-05-28T20:09:13.137Z","dependency_job_id":null,"html_url":"https://github.com/SammanSarkar/Porcupy","commit_stats":null,"previous_names":["sammansarkar/porcupy"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/SammanSarkar/Porcupy","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SammanSarkar%2FPorcupy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SammanSarkar%2FPorcupy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SammanSarkar%2FPorcupy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SammanSarkar%2FPorcupy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SammanSarkar","download_url":"https://codeload.github.com/SammanSarkar/Porcupy/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SammanSarkar%2FPorcupy/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":269693405,"owners_count":24460234,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-10T02:00:08.965Z","response_time":71,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithms","cpo","crested-porcupine-optimizer","machine-learning","metaheuristics","optimization-algorithms","optimization-tools"],"created_at":"2025-08-10T07:40:22.317Z","updated_at":"2025-08-10T07:40:40.613Z","avatar_url":"https://github.com/SammanSarkar.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Porcupy: Crested Porcupine Optimizer\n\n![CPO](https://github.com/user-attachments/assets/af843836-1338-4609-bec9-09ea15852294)\n\n[![PyPI version](https://img.shields.io/pypi/v/porcupy.svg)](https://pypi.org/project/porcupy/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Python 3.7+](https://img.shields.io/badge/python-3.7+-blue.svg)](https://www.python.org/downloads/release/python-370/)\n[![codecov](https://codecov.io/gh/SammanSarkar/Porcupy/graph/badge.svg?token=W0VM41CPL2)](https://codecov.io/gh/SammanSarkar/Porcupy)\n[![PyPI Downloads](https://static.pepy.tech/badge/porcupy)](https://pepy.tech/projects/porcupy)\n\n## Overview\n\nPorcupy implements the Crested Porcupine Optimizer (CPO), a nature-inspired metaheuristic that mimics porcupine defense mechanisms for optimization. It offers both object-oriented and procedural interfaces with comprehensive testing and documentation.\n\n## Installation\n\n```bash\npip install porcupy\n```\n\n## Quick Start\n\n```python\nfrom porcupy import CPO\nfrom porcupy.functions import sphere\n\n# Define search space\ndim = 10\nbounds = [(-5.12, 5.12)] * dim\n\n# Initialize and run optimizer\noptimizer = CPO(dimensions=dim, bounds=bounds, max_iter=100)\nbest_solution, best_fitness, _ = optimizer.optimize(sphere)\n\nprint(f\"Best solution: {best_solution}\")\nprint(f\"Fitness: {best_fitness}\")\n```\n\n## Features\n\n- **Multiple Interfaces**: Object-oriented (`CPO` class) and procedural (`cpo` function)\n- **GPU Acceleration**: Optional CUDA support for large-scale problems\n- **Visualization**: Built-in plotting for 2D/3D optimization landscapes\n- **Benchmark Functions**: 20+ test functions included\n- **Population Management**: Adaptive population sizing and reduction strategies\n\n## GPU Support\n\nFor GPU acceleration, install with CUDA support:\n\n```bash\npip install \"porcupy[cuda]\"\n# Or for specific CUDA version\n# pip install \"porcupy[cuda]\" cupy-cuda11x\n```\n\nExample usage:\n\n```python\nfrom porcupy import GPUCPO\n\noptimizer = GPUCPO(dimensions=30, bounds=([-5.12]*30, [5.12]*30))\nbest_pos, best_cost, _ = optimizer.optimize(sphere)\n```\n\n## Documentation\n\nFull documentation is available at [https://porcupy-cpo.readthedocs.io](https://porcupy-cpo.readthedocs.io).\n\n## Contributing\n\nContributions are welcome! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n  - Contour and surface plots\n  - Real-time population tracking\n  - Defense mechanism visualization\n- **Convergence Analysis**\n  - Cost vs iteration plots\n  - Population diversity metrics\n- **Export Options**\n  - Save as GIF/MP4/PNG/PDF\n  - Customizable figure sizes\n\n### Benchmark Functions\n- **Unimodal functions**: Sphere, Rosenbrock, Schwefel 2.22, Schwefel 1.2, Schwefel 2.21, Step, Quartic\n- **Multimodal functions**: Rastrigin, Ackley, Griewank, Schwefel, Michalewicz\n- **Function utilities**: Easy access to function bounds and optima\n\n### Testing and Documentation\n- **Comprehensive test suite** with high code coverage\n- **API Reference** with detailed docstrings\n- **User Guide** with examples and tutorials\n- **Interactive examples** for quick start\n\n## Installation\n\n```bash\npip install porcupy\n```\n\nFor visualization support, install with the plotting extras:\n\n```bash\npip install porcupy[plotting]\n```\n\nFor development, install with the dev extras:\n\n```bash\npip install porcupy[dev]\n```\n\n## Quick Start\n\n### Object-Oriented Interface\n\n```python\nimport numpy as np\nfrom porcupy import CPO\nfrom porcupy.functions import sphere, get_function_bounds\nfrom porcupy.utils.visualization_manager import CPOVisualizer\n\n# Define the problem\ndimensions = 2  # Using 2D for visualization\nlb = [-5.12] * dimensions  # Lower bounds for sphere function\nub = [5.12] * dimensions   # Upper bounds for sphere function\nbounds = (np.array(lb), np.array(ub))\n\n# Create the optimizer with custom options\noptimizer = CPO(\n    dimensions=dimensions,\n    bounds=bounds,\n    pop_size=30,\n    max_iter=100,\n    options={\n        'reduction_strategy': 'cosine',  # Population reduction strategy\n        'min_pop_size': 10,              # Minimum population size\n        'parallel': True,                # Enable parallel processing\n        'defense_weights': [0.3, 0.3, 0.2, 0.2]  # Custom defense mechanism weights\n    },\n    ftol=1e-6,  # Convergence tolerance\n    ftol_iter=5  # Number of iterations for convergence check\n)\n\n# Run the optimization with progress tracking\nbest_pos, best_cost, cost_history = optimizer.optimize(\n    objective_func=sphere,\n    verbose=True,\n    track_history=True  # Enable history tracking for visualization\n)\n\nprint(f\"Best position: {best_pos}\")\nprint(f\"Best cost: {best_cost}\")\n\n# Create visualizer\nvisualizer = CPOVisualizer(objective_func=sphere, bounds=bounds)\n\n# Visualize the optimization process\nif dimensions == 2:\n    # Create animation of the optimization process\n    visualizer.animate_optimization(\n        position_history=optimizer.positions_history,\n        best_pos_history=optimizer.best_positions_history,\n        save_path='optimization_animation.gif'\n    )\n    \n    # Show convergence plot\n    visualizer.plot_convergence(cost_history)\n    \n    # Show search space with final positions\n    visualizer.plot_search_space(positions=optimizer.positions, best_pos=best_pos)\n```\n\n### Procedural Interface\n\n```python\nimport numpy as np\nfrom porcupy.cpo import cpo\nfrom porcupy.functions import rastrigin\nfrom porcupy.utils.visualization_manager import CPOVisualizer\n\n# Define the problem\ndimensions = 2  # Using 2D for visualization\nlb = [-5.12] * dimensions  # Lower bounds for Rastrigin function\nub = [5.12] * dimensions   # Upper bounds for Rastrigin function\n\n# Run the optimization with default parameters\nbest_pos, best_cost, cost_history = cpo(\n    objective_func=rastrigin,\n    lb=lb,\n    ub=ub,\n    pop_size=30,\n    max_iter=100,\n    verbose=True,\n    track_history=True  # Enable history tracking for visualization\n)\n\nprint(f\"Best position: {best_pos}\")\nprint(f\"Best cost: {best_cost}\")\n\n# Create visualizer\nvisualizer = CPOVisualizer(objective_func=rastrigin, bounds=(np.array(lb), np.array(ub)))\n\n# Visualize the optimization process\nif dimensions == 2:\n    # Create animation of the optimization process\n    visualizer.animate_optimization(\n        position_history=optimizer.positions_history,\n        best_pos_history=optimizer.best_positions_history,\n        save_path='rastrigin_optimization.gif'\n    )\n    \n    # Show convergence plot\n    visualizer.plot_convergence(cost_history)\n    \n    # Show search space with final positions\n    visualizer.plot_search_space(positions=optimizer.positions, best_pos=best_pos)\n```\n\n## Documentation\n\nPorcupy comes with comprehensive documentation to help you get started and make the most of the library:\n\n- [**User Guide**](docs/user_guide.md): A step-by-step guide to using Porcupy, including installation, basic usage, advanced features, and examples.\n- [**API Reference**](docs/api_reference.md): Detailed documentation of all classes, methods, and functions in the library.\n- [**Examples**](examples/): A collection of example scripts demonstrating various features of the library.\n\nThe documentation covers:\n\n- Core optimization algorithms and their parameters\n- Population management strategies\n- Visualization tools and techniques\n- Benchmark functions and their characteristics\n- Advanced usage patterns and customization options\n\n## Algorithm\n\nThe Crested Porcupine Optimizer (CPO) algorithm is inspired by the defensive behaviors of crested porcupines, which use four distinct mechanisms to protect themselves from predators:\n\n1. **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.\n\n2. **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.\n\n3. **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.\n\n4. **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.\n\nWhat 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.\n\nThe 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.\n\n## Citing\n\nIf you use Porcupy in your research, please cite the original paper:\n\n```\n@article{article,\nauthor = {Abdel-Basset, Mohamed and Mohamed, Reda and Abouhawwash, Mohamed},\nyear = {2023},\nmonth = {12},\npages = {111257},\ntitle = {Crested Porcupine Optimizer: A new nature-inspired metaheuristic},\nvolume = {284},\njournal = {Knowledge-Based Systems},\ndoi = {10.1016/j.knosys.2023.111257}\n}\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Development and Testing\n\n### Setting Up the Development Environment\n\nTo set up the development environment for contributing to Porcupy:\n\n```bash\n# Clone the repository\ngit clone https://github.com/SammanSarkar/Porcupy.git\ncd Porcupy\n\n# Install in development mode with all extras\npip install -e .[all]\n```\n\n### Core Components\n\n1. **Optimization Algorithms**\n   - `cpo.py`: Main implementation of the Crested Porcupine Optimizer\n   - `gpu_cpo.py`: GPU-accelerated version using CuPy\n   - `base.py`: Base optimizer class with common functionality\n\n2. **Algorithm Components**\n   - `porcupines.py`: Core implementation of porcupine behaviors and population management\n   - Defense mechanisms (sight, sound, odor, physical attack)\n   - Population management and selection strategies\n\n3. **Benchmark Functions**\n   - Built-in test functions for optimization\n   - Both unimodal and multimodal functions\n   - Easy integration with custom objective functions\n\n4. **Utilities**\n   - Visualization tools for optimization progress\n   - Parallel processing support\n   - Input validation and helper functions\n\n5. **Documentation**\n   - User guides and tutorials\n   - API reference\n   - Example scripts\n\n6. **Tests**\n   - Unit tests for all components\n   - Integration tests\n   - Performance benchmarks\n\n\n### Running Tests\n\nPorcupy has a comprehensive test suite with over 80% code coverage. To run the tests:\n\n```bash\n# Run all tests\npython -m pytest tests/\n\n# Run tests for a specific module\npython -m pytest tests/test_porcupines.py\n\n# Run tests with verbose output\npython -m pytest tests/ -v\n\n# Generate test coverage report\npython -m pytest tests/ --cov=porcupy\n\n# Generate detailed HTML coverage report\npython -m pytest tests/ --cov=porcupy --cov-report=html\n```\n\n\u003e **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.\n\n### Continuous Integration\n\nThe codebase is continuously tested to ensure high quality and reliability. All pull requests must pass the test suite before being merged.\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsammansarkar%2Fporcupy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsammansarkar%2Fporcupy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsammansarkar%2Fporcupy/lists"}