
Security News
The Nightmare Before Deployment
Season’s greetings from Socket, and here’s to a calm end of year: clean dependencies, boring pipelines, no surprises.
porcupy
Advanced tools
Porcupy 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.
pip install porcupy
from porcupy import CPO
from porcupy.functions import sphere
# Define search space
dim = 10
bounds = [(-5.12, 5.12)] * dim
# Initialize and run optimizer
optimizer = CPO(dimensions=dim, bounds=bounds, max_iter=100)
best_solution, best_fitness, _ = optimizer.optimize(sphere)
print(f"Best solution: {best_solution}")
print(f"Fitness: {best_fitness}")
CPO class) and procedural (cpo function)For GPU acceleration, install with CUDA support:
pip install "porcupy[cuda]"
# Or for specific CUDA version
# pip install "porcupy[cuda]" cupy-cuda11x
Example usage:
from porcupy import GPUCPO
optimizer = GPUCPO(dimensions=30, bounds=([-5.12]*30, [5.12]*30))
best_pos, best_cost, _ = optimizer.optimize(sphere)
Full documentation is available at https://porcupy-cpo.readthedocs.io.
Contributions are welcome! Please see our Contributing Guidelines for details.
This project is licensed under the MIT License - see the LICENSE file for details.
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]
import numpy as np
from porcupy import CPO
from porcupy.functions import sphere, get_function_bounds
from porcupy.utils.visualization_manager import CPOVisualizer
# Define the problem
dimensions = 2 # Using 2D for visualization
lb = [-5.12] * dimensions # Lower bounds for sphere function
ub = [5.12] * dimensions # Upper bounds for sphere function
bounds = (np.array(lb), np.array(ub))
# 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,
track_history=True # Enable history tracking for visualization
)
print(f"Best position: {best_pos}")
print(f"Best cost: {best_cost}")
# Create visualizer
visualizer = CPOVisualizer(objective_func=sphere, bounds=bounds)
# Visualize the optimization process
if dimensions == 2:
# Create animation of the optimization process
visualizer.animate_optimization(
position_history=optimizer.positions_history,
best_pos_history=optimizer.best_positions_history,
save_path='optimization_animation.gif'
)
# Show convergence plot
visualizer.plot_convergence(cost_history)
# Show search space with final positions
visualizer.plot_search_space(positions=optimizer.positions, best_pos=best_pos)
import numpy as np
from porcupy.cpo import cpo
from porcupy.functions import rastrigin
from porcupy.utils.visualization_manager import CPOVisualizer
# Define the problem
dimensions = 2 # Using 2D for visualization
lb = [-5.12] * dimensions # Lower bounds for Rastrigin function
ub = [5.12] * dimensions # Upper bounds for Rastrigin function
# 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,
track_history=True # Enable history tracking for visualization
)
print(f"Best position: {best_pos}")
print(f"Best cost: {best_cost}")
# Create visualizer
visualizer = CPOVisualizer(objective_func=rastrigin, bounds=(np.array(lb), np.array(ub)))
# Visualize the optimization process
if dimensions == 2:
# Create animation of the optimization process
visualizer.animate_optimization(
position_history=optimizer.positions_history,
best_pos_history=optimizer.best_positions_history,
save_path='rastrigin_optimization.gif'
)
# Show convergence plot
visualizer.plot_convergence(cost_history)
# Show search space with final positions
visualizer.plot_search_space(positions=optimizer.positions, best_pos=best_pos)
Porcupy comes with comprehensive documentation to help you get started and make the most of the library:
The documentation covers:
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:
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.
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.
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.
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.
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}
}
This project is licensed under the MIT License - see the LICENSE file for details.
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]
Optimization Algorithms
cpo.py: Main implementation of the Crested Porcupine Optimizergpu_cpo.py: GPU-accelerated version using CuPybase.py: Base optimizer class with common functionalityAlgorithm Components
porcupines.py: Core implementation of porcupine behaviors and population managementBenchmark Functions
Utilities
Documentation
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 pytestis recommended over justpytestas it ensures the current directory is in the Python path, which helps with imports.
The codebase is continuously tested to ensure high quality and reliability. All pull requests must pass the test suite before being merged.
Contributions are welcome! Please feel free to submit a Pull Request.
FAQs
Crested Porcupine Optimizer (CPO) with GPU acceleration for optimization problems
We found that porcupy demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Season’s greetings from Socket, and here’s to a calm end of year: clean dependencies, boring pipelines, no surprises.

Research
/Security News
Impostor NuGet package Tracer.Fody.NLog typosquats Tracer.Fody and its author, using homoglyph tricks, and exfiltrates Stratis wallet JSON/passwords to a Russian IP address.

Security News
Deno 2.6 introduces deno audit with a new --socket flag that plugs directly into Socket to bring supply chain security checks into the Deno CLI.