### Verify Installation with Python Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Run a quick optimization test to verify the installation works correctly. ```python # Basic import test from opt import ParticleSwarm from opt.benchmark.functions import shifted_ackley # Quick optimization test optimizer = ParticleSwarm( func=shifted_ackley, lower_bound=-2.768, upper_bound=2.768, dim=2, max_iter=50 ) best_solution, best_fitness = optimizer.search() print(f"Installation verified! Best fitness: {best_fitness:.6f}") ``` -------------------------------- ### Quick Install with poetry Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Install the useful-optimizer package using poetry. ```bash poetry add git+https://github.com/Anselmoo/useful-optimizer ``` -------------------------------- ### Development Installation Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Clone the repository and set up a development environment with uv or pip. ```bash # Clone the repository git clone https://github.com/Anselmoo/useful-optimizer.git cd useful-optimizer # Install with uv (recommended) uv sync # Or with pip pip install -e ".[dev]" ``` -------------------------------- ### Install with Visualization Support (uv) Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Install the package with the 'visualization' extra using uv for benchmark visualization capabilities. ```bash uv add git+https://github.com/Anselmoo/useful-optimizer --extra visualization ``` -------------------------------- ### Complete Example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md A full example using the rosenbrock function with custom parameters and formatted output. ```python from opt.swarm_intelligence import ParticleSwarm from opt.benchmark.functions import rosenbrock import numpy as np # Define the problem optimizer = ParticleSwarm( func=rosenbrock, lower_bound=-5.0, upper_bound=10.0, dim=10, max_iter=500, population_size=50, # Number of particles c1=2.0, # Cognitive parameter c2=2.0 # Social parameter ) # Run optimization best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Install with Benchmark Support (uv) Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Install the package with the 'benchmark' extra using uv for running benchmark suites with advanced plotting. ```bash uv add git+https://github.com/Anselmoo/useful-optimizer --extra benchmark ``` -------------------------------- ### Install with Visualization Support (pip) Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Install the package with the 'visualization' extra using pip for benchmark visualization capabilities. ```bash pip install git+https://github.com/Anselmoo/useful-optimizer[visualization] ``` -------------------------------- ### Install with Benchmark Support (pip) Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Install the package with the 'benchmark' extra using pip for running benchmark suites with advanced plotting. ```bash pip install git+https://github.com/Anselmoo/useful-optimizer[benchmark] ``` -------------------------------- ### Run the Optimization Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Executes the search and prints the best solution and fitness. ```python best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness}") ``` -------------------------------- ### Using the Demo Utility Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Runs a built-in demo for any optimizer, with default or custom parameters. ```python from opt.demo import run_demo from opt.swarm_intelligence import ParticleSwarm # Run with default settings run_demo(ParticleSwarm) # Or customize parameters run_demo( ParticleSwarm, max_iter=200, population_size=50, dim=10 ) ``` -------------------------------- ### Install SciPy for Classical Optimizers Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Install SciPy version 1.12.0 or later, required by some classical optimizers. ```bash pip install scipy>=1.12.0 ``` -------------------------------- ### Evolutionary Algorithms Imports Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Imports evolutionary algorithms: GeneticAlgorithm, DifferentialEvolution, and CMAESAlgorithm. ```python from opt.evolutionary import ( GeneticAlgorithm, DifferentialEvolution, CMAESAlgorithm ) ``` -------------------------------- ### Fix NumPy Version Conflicts Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Install a compatible NumPy version to resolve compatibility issues. ```bash pip install numpy>=1.26.4 ``` -------------------------------- ### Import an Optimizer Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Imports the ParticleSwarm optimizer and the shifted_ackley benchmark function. ```python from opt.swarm_intelligence import ParticleSwarm from opt.benchmark.functions import shifted_ackley ``` -------------------------------- ### Start development server with npm run docs:dev Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/README.md Starts the local VitePress development server. The site will be available at http://localhost:5173/useful-optimizer/. ```bash npm run docs:dev ``` -------------------------------- ### Check Installed Package with pip list Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/installation.md Verify that the useful-optimizer package is installed in the active Python environment. ```bash pip list | grep useful-optimizer ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Installs pre-commit hooks for the project. ```bash # Install pre-commit hooks uv run pre-commit install ``` -------------------------------- ### AdaDelta usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/gradient-based/adadelta.md Shows how to instantiate the AdaDelta optimizer with the sphere benchmark function and run the search. The example sets bounds, dimension, and maximum iterations, then prints the best solution and fitness. ```python from opt.gradient_based.adadelta import AdaDelta from opt.benchmark.functions import sphere optimizer = AdaDelta( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Classical Methods Imports Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Imports classical optimization methods: BFGS, NelderMead, and SimulatedAnnealing. ```python from opt.classical import ( BFGS, NelderMead, SimulatedAnnealing ) ``` -------------------------------- ### Install dependencies with npm install Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/README.md Run inside the docs directory to install dependencies. No longer requires the --legacy-peer-deps flag. ```bash cd docs npm install ``` -------------------------------- ### Install with uv Source: https://github.com/anselmoo/useful-optimizer/blob/main/README.md Install the Useful Optimizer package using uv, which is recommended. ```bash uv add git+https://github.com/Anselmoo/useful-optimizer ``` -------------------------------- ### Install core dependencies with uv sync Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Installs core dependencies (numpy, scipy, scikit-learn) for the project. ```bash # Install core dependencies (numpy, scipy, scikit-learn) uv sync ``` -------------------------------- ### Common Interface Example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/index.md All algorithms share the same interface. This example shows how to instantiate a ParticleSwarm optimizer with the common parameters and run the search. ```python from opt.swarm_intelligence import ParticleSwarm optimizer = ParticleSwarm( func=objective_function, # Callable[[np.ndarray], float] lower_bound=-10.0, # Lower bound of search space upper_bound=10.0, # Upper bound of search space dim=10, # Number of dimensions max_iter=100 # Maximum iterations ) best_solution, best_fitness = optimizer.search() ``` -------------------------------- ### Validate MathJax migration setup Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/README.md Run this command to verify the math rendering setup (MathJax) is working. The script checks dependencies in package.json, the VitePress configuration, and that the built output contains rendered MathJax. ```bash npm run validate:migration ``` -------------------------------- ### Create the Optimizer Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Instantiates a ParticleSwarm optimizer with the shifted_ackley function, bounds, dimensions, and iteration limit. ```python optimizer = ParticleSwarm( func=shifted_ackley, # Objective function to minimize lower_bound=-12.768, # Lower bound of search space upper_bound=12.768, # Upper bound of search space dim=2, # Number of dimensions max_iter=100 # Maximum iterations ) ``` -------------------------------- ### Gradient-Based Imports Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Imports gradient-based optimizers: SGDMomentum, AdamW, and RMSprop. ```python from opt.gradient_based import ( SGDMomentum, AdamW, RMSprop ) ``` -------------------------------- ### Install Griffe with uv Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/DOCUMENTATION_GENERATOR.md Installs Griffe as a dev dependency and syncs the environment. ```bash # Install Griffe uv add griffe --group dev uv sync ``` -------------------------------- ### Install with pip Source: https://github.com/anselmoo/useful-optimizer/blob/main/README.md Install the Useful Optimizer package directly from the GitHub repository using pip. ```bash pip install git+https://github.com/Anselmoo/useful-optimizer ``` -------------------------------- ### Install npm dependencies and build docs Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/DOCUMENTATION_GENERATOR.md Installs npm dependencies and builds the VitePress documentation. ```bash # Install npm dependencies cd docs npm install npm run docs:build ``` -------------------------------- ### Dragonfly Algorithm Usage Example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/dragonfly-algorithm.md Shows how to instantiate the DragonflyOptimizer with the sphere benchmark function and run the optimization search. The example sets bounds, dimension, maximum iterations, and population size, then prints the best solution and fitness. ```python from opt.swarm_intelligence.dragonfly_algorithm import DragonflyOptimizer from opt.benchmark.functions import sphere optimizer = DragonflyOptimizer( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Initialize and run SlimeMouldAlgorithm with sphere benchmark Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/slime-mould.md Shows how to instantiate the SlimeMouldAlgorithm optimizer with the sphere benchmark function and run the search. The example sets bounds, dimension, iterations, and population size, then prints the best solution and fitness. ```python from opt.swarm_intelligence.slime_mould import SlimeMouldAlgorithm from opt.benchmark.functions import sphere optimizer = SlimeMouldAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Custom Objective Function Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Defines a custom objective function and optimizes it with ParticleSwarm. ```python import numpy as np from opt.swarm_intelligence import ParticleSwarm # Define your own objective function def my_function(x: np.ndarray) -> float: """Custom objective: sum of squares with a twist.""" return np.sum(x**2) + 10 * np.sin(np.sum(x)) # Optimize it optimizer = ParticleSwarm( func=my_function, lower_bound=-10.0, upper_bound=10.0, dim=5, max_iter=100 ) best_solution, best_fitness = optimizer.search() ``` -------------------------------- ### Usage example for ArtificialGorillaTroopsOptimizer Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/artificial-gorilla-troops.md Shows how to instantiate the optimizer with the sphere benchmark function and run the search. The example sets bounds, dimension, iterations, and population size, then prints the best solution and fitness. ```python from opt.swarm_intelligence.artificial_gorilla_troops import ArtificialGorillaTroopsOptimizer from opt.benchmark.functions import sphere optimizer = ArtificialGorillaTroopsOptimizer( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Cultural Algorithm Example Usage Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/evolutionary/cultural-algorithm.md Shows how to instantiate the CulturalAlgorithm class with the shifted_ackley benchmark function and run the search. The example prints the best solution and fitness found. ```python optimizer = CulturalAlgorithm( func=shifted_ackley, dim=2, lower_bound=-2.768, upper_bound=+2.768 ) best_solution, best_fitness = optimizer.search() print(f"Best solution found: {best_solution}") print(f"Best fitness found: {best_fitness}") ``` -------------------------------- ### Usage example for SquirrelSearchAlgorithm Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/squirrel-search.md Shows how to instantiate the SquirrelSearchAlgorithm with the sphere benchmark function and run the search. The module is under development and not yet ready for use. ```python from opt.swarm_intelligence.squirrel_search import SquirrelSearchAlgorithm from opt.benchmark.functions import sphere optimizer = SquirrelSearchAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Correct Google-style docstring with inline parameter descriptions Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Shows the correct format where parameter descriptions start on the same line as the parameter name, as required by the Google Python Style Guide. ```python Args: func (Callable[[ndarray], float]): Objective function to minimize. lower_bound (float): Lower bound of search space. ``` -------------------------------- ### Docstring Convention: __init__ Method Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/api/index.md Google-style docstring example for an optimizer constructor, documenting parameters and raising ValueError for invalid dimensions or iterations. ```python def __init__( self, func: Callable[[np.ndarray], float], lower_bound: float, upper_bound: float, dim: int, max_iter: int = 100, population_size: int = 30 ) -> None: """Initialize the optimizer. Args: func: Objective function to minimize. Takes a numpy array and returns a scalar fitness value. lower_bound: Lower bound of the search space. upper_bound: Upper bound of the search space. dim: Dimensionality of the problem. max_iter: Maximum number of iterations. population_size: Number of individuals in the population. Raises: ValueError: If dim < 1 or max_iter < 1. """ ``` -------------------------------- ### Example: Accessing History with ParticleSwarm Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/api/abstract-optimizer.md Shows how to create a ParticleSwarm optimizer with history tracking enabled, run the search, and plot the convergence curve using matplotlib. ```python from opt.swarm_intelligence import ParticleSwarm from opt.benchmark.functions import rosenbrock optimizer = ParticleSwarm( func=rosenbrock, lower_bound=-5.0, upper_bound=10.0, dim=10, max_iter=100, track_history=True ) best_solution, best_fitness = optimizer.search() # Plot convergence curve import matplotlib.pyplot as plt plt.plot(optimizer.history["best_fitness"]) plt.xlabel("Iteration") plt.ylabel("Best Fitness") plt.yscale("log") plt.title("Convergence Curve") plt.show() ``` -------------------------------- ### FireflyAlgorithm usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/firefly-algorithm.md Initializes the FireflyAlgorithm optimizer with the sphere benchmark function and runs the search. Prints the best solution and fitness. ```python from opt.swarm_intelligence.firefly_algorithm import FireflyAlgorithm from opt.benchmark.functions import sphere optimizer = FireflyAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Block Math LaTeX Example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/README.md Rendered with MathJax via markdown-it-mathjax3. Use for displaying a centered, block-level equation in VitePress markdown. ```markdown $$ \min_{x \in \mathbb{R}^n} f(x) = \sum_{i=1}^{n} x_i^2 $$ ``` -------------------------------- ### MayflyOptimizer usage example with sphere benchmark Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/mayfly-optimizer.md Initialize the MayflyOptimizer with the sphere function, bounds, dimension, iterations, and population size, then run the search and print the best solution and fitness. ```python from opt.swarm_intelligence.mayfly_optimizer import MayflyOptimizer from opt.benchmark.functions import sphere optimizer = MayflyOptimizer( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### CMAESAlgorithm usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/evolutionary/cma-es.md Shows how to instantiate CMAESAlgorithm with a benchmark function and run the search. The example uses shifted_ackley with dim=2 and bounds -12.768 to 12.768, then prints the best solution and fitness. ```python optimizer = CMAESAlgorithm( func=shifted_ackley, dim=2, lower_bound=-12.768, upper_bound=12.768, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness}") ``` -------------------------------- ### Differential Evolution usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/evolutionary/differential-evolution.md Shows how to instantiate the DifferentialEvolution optimizer with the sphere benchmark function and run the search. The example sets bounds, dimension, max iterations, and population size, then prints the best solution and fitness. ```python from opt.evolutionary.differential_evolution import DifferentialEvolution from opt.benchmark.functions import sphere optimizer = DifferentialEvolution( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### ParticleSwarm optimization with search() Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/index.md Shows the unified interface: instantiate an optimizer with the objective function, bounds, dimension, and max iterations, then call search() to get the best solution and fitness. ```python from opt.swarm_intelligence import ParticleSwarm optimizer = ParticleSwarm( func=objective_function, lower_bound=-10.0, upper_bound=10.0, dim=10, max_iter=100 ) best_solution, best_fitness = optimizer.search() ``` -------------------------------- ### Type Hints Example: search Method Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/api/index.md Shows the type-hinted signature and docstring for the search method, returning a tuple of best solution and fitness. ```python from typing import Callable import numpy as np def search(self) -> tuple[np.ndarray, float]: """Run the optimization search. Returns: tuple: A tuple containing: - best_solution (np.ndarray): The best solution found - best_fitness (float): The fitness value of the best solution """ ... ``` -------------------------------- ### Example doctest for sphere benchmark function Source: https://github.com/anselmoo/useful-optimizer/blob/main/README.md Shows usage of the sphere function with numpy arrays, demonstrating output at optimum and away from it. ```python import numpy as np from opt.benchmark.functions import sphere # At optimum result = sphere(np.array([0.0, 0.0])) print(float(result)) # 0.0 # Away from optimum result = sphere(np.array([1.0, 1.0])) print(float(result)) # 2.0 ``` -------------------------------- ### MOEA/D Usage Example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/multi-objective/moead.md Initialize the MOEAD optimizer with the sphere benchmark function, set bounds, dimension, iterations, and population size, then run the search and print the best solution and fitness. ```python from opt.multi_objective.moead import MOEAD from opt.benchmark.functions import sphere optimizer = MOEAD( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Generate documentation from optimizer source files Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/README.md Run this command to regenerate algorithm pages, category indexes, API pages, and the sidebar from the optimizer source files. Do not edit generated files by hand. See the contributing guide for naming rules. ```bash uv run python scripts/generate_docs.py --all --json --sidebar ``` -------------------------------- ### Example error message from google-docstring-inline-descriptions Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Sample error output indicating a docstring entry missing an inline summary after the type. ```text opt/swarm_intelligence/particle_swarm.py:45: Docstring entry missing inline summary after type: func (Callable[[ndarray], float]): ``` -------------------------------- ### Harmony Search usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/metaheuristic/harmony-search.md Shows how to instantiate HarmonySearch with the sphere benchmark function and run the optimization. The search method returns the best solution and its fitness value, which are printed to the console. ```python from opt.metaheuristic.harmony_search import HarmonySearch from opt.benchmark.functions import sphere optimizer = HarmonySearch( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### OrcaPredatorAlgorithm usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/orca-predator.md Initialize the OrcaPredatorAlgorithm with the sphere benchmark function, set bounds, dimension, iterations, and population size, then run the search and print the best solution and fitness. ```python from opt.swarm_intelligence.orca_predator import OrcaPredatorAlgorithm from opt.benchmark.functions import sphere optimizer = OrcaPredatorAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Quick Example: Particle Swarm Optimization Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/index.md Demonstrates using the ParticleSwarm optimizer from the swarm_intelligence module with the shifted_ackley benchmark function. The optimizer is configured with bounds, dimension, and maximum iterations, then search() returns the best solution and fitness. ```python from opt.swarm_intelligence import ParticleSwarm from opt.benchmark.functions import shifted_ackley # Create optimizer optimizer = ParticleSwarm( func=shifted_ackley, lower_bound=-12.768, upper_bound=12.768, dim=2, max_iter=100 ) # Run optimization best_solution, best_fitness = optimizer.search() print(f"Best fitness: {best_fitness:.6f}") ``` -------------------------------- ### Example usage of StochasticDiffusionSearch Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/metaheuristic/stochastic-diffusion-search.md Shows how to instantiate the optimizer with the shifted_ackley function, set bounds, population size, and iterations, then run the search and print the best solution and fitness. ```python optimizer = StochasticDiffusionSearch( func=shifted_ackley, dim=2, lower_bound=-32.768, upper_bound=+32.768, population_size=100, max_iter=1000, ) best_solution, best_fitness = optimizer.search() print(f"Best solution found: {best_solution}") print(f"Best fitness value: {best_fitness}") ``` -------------------------------- ### Build production site with npm run docs:build Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/README.md Builds the production site. Output will be in .vitepress/dist/. ```bash npm run docs:build ``` -------------------------------- ### Run demos from command line Source: https://github.com/anselmoo/useful-optimizer/blob/main/README.md Shows how to run demos directly from the command line for specific optimizer modules. ```bash python -m opt.swarm_intelligence.particle_swarm python -m opt.gradient_based.adamw python -m opt.classical.simulated_annealing ``` -------------------------------- ### SPEA2 Optimizer Usage Example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/multi-objective/spea2.md Initializes the SPEA2 optimizer with the sphere benchmark function, runs the search, and prints the best solution and fitness. Requires the opt.multi_objective.spea2 and opt.benchmark.functions modules. ```python from opt.multi_objective.spea2 import SPEA2 from opt.benchmark.functions import sphere optimizer = SPEA2( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Honey Badger Algorithm usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/honey-badger.md Shows how to instantiate the HoneyBadgerAlgorithm with the sphere benchmark function and run the search. The optimizer minimizes the objective function within the given bounds and dimensionality, printing the best solution and fitness. ```python from opt.swarm_intelligence.honey_badger import HoneyBadgerAlgorithm from opt.benchmark.functions import sphere optimizer = HoneyBadgerAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### GitHub Actions CI Workflow for Documentation Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/DOCUMENTATION_GENERATOR.md Add these steps to a GitHub Actions workflow to generate documentation and build VitePress in CI. The first step runs the generator, the second installs dependencies and builds. ```yaml - name: Generate Documentation run: | uv run python scripts/generate_docs.py --all --json --full-api --sidebar - name: Build VitePress run: | cd docs npm install npm run docs:build ``` -------------------------------- ### Nadam Optimizer Usage Example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/gradient-based/nadam.md Demonstrates how to instantiate and run the Nadam optimizer on the sphere benchmark function. The optimizer is configured with bounds, dimension, and maximum iterations, then search() returns the best solution and fitness. ```python from opt.gradient_based.nadam import Nadam from opt.benchmark.functions import sphere optimizer = Nadam( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Python usage of EquilibriumOptimizer with sphere function Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/physics-inspired/equilibrium-optimizer.md Shows how to instantiate the EquilibriumOptimizer with the sphere benchmark function and run the search. The example sets bounds, dimension, max iterations, and population size, then prints the best solution and fitness. ```python from opt.physics_inspired.equilibrium_optimizer import EquilibriumOptimizer from opt.benchmark.functions import sphere optimizer = EquilibriumOptimizer( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Creating a Custom Optimizer with AbstractOptimizer Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/advanced.md Extend AbstractOptimizer to implement a custom optimization algorithm. The example shows a random-search-like method that initializes a random solution and iteratively proposes candidates with Gaussian noise, clipping to bounds. Override the search method to return the best solution and fitness. ```python from opt.abstract import AbstractOptimizer import numpy as np class MyOptimizer(AbstractOptimizer): """Custom optimization algorithm.""" def __init__( self, func, lower_bound: float, upper_bound: float, dim: int, max_iter: int = 100, **kwargs ): super().__init__( func=func, lower_bound=lower_bound, upper_bound=upper_bound, dim=dim, max_iter=max_iter, **kwargs ) def search(self) -> tuple[np.ndarray, float]: """Run the optimization.""" # Initialize best_solution = np.random.uniform( self.lower_bound, self.upper_bound, self.dim ) best_fitness = self.func(best_solution) # Main loop for _ in range(self.max_iter): # Your algorithm logic here candidate = best_solution + np.random.randn(self.dim) * 0.1 candidate = np.clip(candidate, self.lower_bound, self.upper_bound) fitness = self.func(candidate) if fitness < best_fitness: best_solution = candidate best_fitness = fitness return best_solution, best_fitness ``` -------------------------------- ### BeeAlgorithm usage with sphere function Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/bee-algorithm.md Usage example importing BeeAlgorithm and sphere from the benchmark functions. It sets bounds -5.12 to 5.12, dimension 10, and 500 iterations, then runs the search and prints the best solution and fitness. ```python from opt.swarm_intelligence.bee_algorithm import BeeAlgorithm from opt.benchmark.functions import sphere optimizer = BeeAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Preview production build with npm run docs:preview Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/README.md Preview the production build locally. ```bash npm run docs:preview ``` -------------------------------- ### Pathfinder Algorithm optimization example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/pathfinder.md Shows how to instantiate and run the PathfinderAlgorithm with the sphere benchmark function. Requires the opt package and Python 3.10+. The optimizer minimizes the function within the given bounds and prints the best solution and fitness. ```python from opt.swarm_intelligence.pathfinder import PathfinderAlgorithm from opt.benchmark.functions import sphere optimizer = PathfinderAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Simulated Annealing optimizer usage with sphere benchmark Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/classical/simulated-annealing.md Initialize the SimulatedAnnealing optimizer with the sphere benchmark function, bounds, dimension, and iteration settings, then run the search and print the best solution and fitness. ```python from opt.classical.simulated_annealing import SimulatedAnnealing from opt.benchmark.functions import sphere optimizer = SimulatedAnnealing( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Swarm Intelligence Imports Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/guide/quickstart.md Imports all swarm intelligence algorithms: ParticleSwarm, AntColony, FireflyAlgorithm, GreyWolfOptimizer, and WhaleOptimizationAlgorithm. ```python from opt.swarm_intelligence import ( ParticleSwarm, AntColony, FireflyAlgorithm, GreyWolfOptimizer, WhaleOptimizationAlgorithm ) ``` -------------------------------- ### Using a classical optimizer (BFGS) with shared interface Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/classical/index.md Every optimizer in this category shares the same interface. This example creates a BFGS optimizer for the sphere benchmark function with bounds -5.12 to 5.12, dimension 10, and 500 iterations, then calls search() to get the best solution and fitness. ```python from opt.classical.bfgs import BFGS from opt.benchmark.functions import sphere optimizer = BFGS( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, ) best_solution, best_fitness = optimizer.search() ``` -------------------------------- ### Common Commands for Development, Docs, and Benchmarks Source: https://github.com/anselmoo/useful-optimizer/blob/main/CLAUDE.md Run these commands from the project root unless noted. Use `uv` for Python tasks, `npm` for docs, and the full docs CI pipeline to mirror the docs.yaml build job. The docs build runs SSR and must be SSR-safe. ```bash # Python uv sync --all-extras # install all deps including dev/benchmark/validate uv run pytest src/opt/test/ -v --tb=short # unit tests uv run pytest --doctest-modules -v # doctests uv run ruff check src/opt/ # lint uv run ruff format src/opt/ # format uv run ty check src/opt/ # type check (non-blocking) # Docs cd docs && npm run docs:dev # dev server cd docs && npm run docs:build # production build (runs SSR — must be SSR-safe) cd docs && npm run docs:api # regenerate Griffe JSON API files # Full docs CI pipeline locally (mirrors docs.yaml build job): uv run python scripts/generate_docs.py --all --json --full-api --sidebar cd docs && npm ci && npm run docs:build && npm run validate:migration # Benchmarks uv run python benchmarks/run_benchmark_suite.py --output-dir benchmarks/output ``` -------------------------------- ### SineCosineAlgorithm optimization example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/metaheuristic/sine-cosine-algorithm.md Shows how to instantiate the SineCosineAlgorithm with the sphere benchmark function, set bounds, dimensionality, and iteration parameters, then run the search to obtain the best solution and fitness. The fitness is printed in scientific notation with six decimal places. ```python from opt.metaheuristic.sine_cosine_algorithm import SineCosineAlgorithm from opt.benchmark.functions import sphere optimizer = SineCosineAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Run tests and checks Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/contributing.md Run unit tests, doctests, linting, and documentation build. The last command fails on dead links. ```bash uv run pytest src/opt/test/ scripts/test/ # unit tests and docs consistency uv run pytest --doctest-modules src/opt # doctests uv run ruff check src/opt/ && uv run ruff format --check src/opt/ cd docs && npm ci && npm run docs:build # fails on dead links ``` -------------------------------- ### Using SocialGroupOptimizer with sphere function Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/social-inspired/social-group-optimizer.md Import SocialGroupOptimizer and sphere, configure the optimizer with bounds, dimension, iterations, and population size, then run search() to obtain the best solution and fitness. The example prints the results with formatted fitness. ```python from opt.social_inspired.social_group_optimizer import SocialGroupOptimizer from opt.benchmark.functions import sphere optimizer = SocialGroupOptimizer( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Usage: MothSearchAlgorithm with sphere function Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/moth-search.md Shows how to instantiate the MothSearchAlgorithm optimizer with the sphere benchmark function and run the search. The example sets bounds to -5.12 and 5.12, dimension 10, 500 iterations, and population size 50. After search, it prints the best solution and fitness. ```python from opt.swarm_intelligence.moth_search import MothSearchAlgorithm from opt.benchmark.functions import sphere optimizer = MothSearchAlgorithm( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Using MothFlameOptimizer with sphere benchmark Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/moth-flame-optimization.md Initialize the MothFlameOptimizer with the sphere benchmark function, bounds, dimension, and iteration settings, then call search() to obtain the best solution and fitness. The optimizer minimizes the objective function; the example prints the best solution and fitness with scientific notation. ```python from opt.swarm_intelligence.moth_flame_optimization import MothFlameOptimizer from opt.benchmark.functions import sphere optimizer = MothFlameOptimizer( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Quick demo with run_demo Source: https://github.com/anselmoo/useful-optimizer/blob/main/README.md Shows how to run a standardized demo for an optimizer (ParticleSwarm) with default settings or customized parameters like max_iter, population_size, and c1/c2 coefficients. ```python from opt.demo import run_demo from opt.swarm_intelligence import ParticleSwarm # Run with default settings run_demo(ParticleSwarm) # Or customize parameters run_demo( ParticleSwarm, max_iter=200, population_size=50, c1=2.0, c2=2.0 ) ``` -------------------------------- ### Generate all documentation with uv Source: https://github.com/anselmoo/useful-optimizer/blob/main/README.md Command to generate all documentation (markdown, JSON, API) using the project's script. Includes flags for full API and sidebar. ```bash # Generate all documentation (markdown + JSON + API) uv run python scripts/generate_docs.py --all --json --full-api --sidebar ``` -------------------------------- ### Run all pre-commit hooks Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Runs all pre-commit hooks on all files. ```bash # Run all hooks uv run pre-commit run --all-files ``` -------------------------------- ### Generate documentation via npm shortcut Source: https://github.com/anselmoo/useful-optimizer/blob/main/README.md Alternative command to generate documentation using npm from the docs directory. ```bash # Or use the npm shortcut cd docs && npm run docs:api:all ``` -------------------------------- ### Install validation dependencies with uv sync --group validate Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Installs code hygiene and validation tools, including Pydantic and jsonschema, which are optional dependencies in the validate group. ```bash # Install code hygiene and validation tools (includes Pydantic and jsonschema) uv sync --group validate ``` -------------------------------- ### Using SoccerLeagueOptimizer with sphere benchmark Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/social-inspired/soccer-league-optimizer.md Initializes the SoccerLeagueOptimizer with the sphere function, bounds, dimension, iterations, and population size, then runs the search and prints the best solution and fitness. ```python from opt.social_inspired.soccer_league_optimizer import SoccerLeagueOptimizer from opt.benchmark.functions import sphere optimizer = SoccerLeagueOptimizer( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### ShuffledFrogLeapingAlgorithm usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/metaheuristic/shuffled-frog-leaping-algorithm.md Example usage of the ShuffledFrogLeapingAlgorithm class with a shifted Ackley function. The optimizer is initialized with the objective function, bounds, and dimension, then search() returns the best solution and fitness. ```python optimizer = ShuffledFrogLeapingAlgorithm( func=shifted_ackley, lower_bound=-32.768, upper_bound=+32.768, dim=2 ) best_solution, best_fitness = optimizer.search() print(f"Best solution found: {best_solution}") print(f"Fitness value: {best_fitness}") ``` -------------------------------- ### BeeAlgorithm usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/bee-algorithm.md Example usage of the BeeAlgorithm class with the shifted_ackley function. It creates an optimizer with dimension 2, bounds -2.768 to 2.768, and 4000 iterations, then runs the search and prints the best solution and fitness. ```python optimizer = BeeAlgorithm( func=shifted_ackley, dim=2, lower_bound=-2.768, upper_bound=+2.768, max_iter=4000, ) best_solution, best_fitness = optimizer.search() print(f"Best solution found: {best_solution}") print(f"Best fitness found: {best_fitness}") ``` -------------------------------- ### LDAnalysis usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/probabilistic/linear-discriminant-analysis.md Initialize the LDAnalysis optimizer with the sphere benchmark function and run the search. The example sets bounds, dimensionality, iteration limit, and population size, then prints the best solution and fitness. ```python from opt.probabilistic.linear_discriminant_analysis import LDAnalysis from opt.benchmark.functions import sphere optimizer = LDAnalysis( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Show help for batch_update_docstrings.py Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Display the help message for the script, listing all available command-line options. ```bash uv run python scripts/batch_update_docstrings.py --help ``` -------------------------------- ### Verify formatting with ruff Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Checks code formatting of the optimizer directory using ruff. Run from the repository root. ```bash uv run ruff check opt/ ``` -------------------------------- ### Ant Colony Optimization usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/ant-colony.md Initialize the AntColony optimizer with the sphere benchmark function and run the search. The example sets bounds from -5.12 to 5.12, dimension 10, 500 iterations, and a population size of 50, then prints the best solution and fitness. ```python from opt.swarm_intelligence.ant_colony import AntColony from opt.benchmark.functions import sphere optimizer = AntColony( func=sphere, lower_bound=-5.12, upper_bound=5.12, dim=10, max_iter=500, population_size=50, ) best_solution, best_fitness = optimizer.search() print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness:.6e}") ``` -------------------------------- ### Colliding Bodies Optimization example usage Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/metaheuristic/colliding-bodies-optimization.md Example usage of the Colliding Bodies Optimization algorithm with the shifted_ackley function. It sets the dimension to 2, bounds to -32.768 and +32.768, population size to 100, and max iterations to 1000. The search method returns the best solution and fitness, which are printed. ```python optimizer = CollidingBodiesOptimization( func=shifted_ackley, dim=2, lower_bound=-32.768, upper_bound=+32.768, population_size=100, max_iter=1000, ) best_solution, best_fitness = optimizer.search() print(f"Best solution found: {best_solution}") print(f"Best fitness found: {best_fitness}") print(f"Best solution: {best_solution}") print(f"Best fitness: {best_fitness}") ``` -------------------------------- ### FireflyAlgorithm usage example Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/algorithms/swarm-intelligence/firefly-algorithm.md Example usage of the FireflyAlgorithm class with the shifted_ackley objective function. The optimizer is configured with a 2D search space, bounds from -32.768 to 32.768, population size 100, max iterations 1000, and parameters alpha=0.5, beta_0=1, gamma=1. The search method returns the best solution and its fitness, which are then printed. ```python optimizer = FireflyAlgorithm( func=shifted_ackley, dim=2, lower_bound=-32.768, upper_bound=32.768, population_size=100, max_iter=1000, alpha=0.5, beta_0=1, gamma=1, ) best_solution, best_fitness = optimizer.search() print(f"Best solution found: {best_solution}") print(f"Best fitness found: {best_fitness}") ``` -------------------------------- ### Test VitePress Locally and Build Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/DOCUMENTATION_GENERATOR.md Navigate to the docs directory and preview the site locally with docs:dev or create a production build with docs:build. ```bash cd docs npm run docs:dev # Preview locally npm run docs:build # Production build ``` -------------------------------- ### Run google-docstring-inline-summaries pre-commit hook Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Runs the Google docstring inline summaries hook on all files. ```bash # Run Google docstring inline summaries hook uv run pre-commit run google-docstring-inline-summaries --all-files ``` -------------------------------- ### Generate Documentation with uv run Source: https://github.com/anselmoo/useful-optimizer/blob/main/docs/DOCUMENTATION_GENERATOR.md Run the documentation generator to produce all outputs including JSON, full API, and sidebar. Use this command in the project root. ```bash uv run python scripts/generate_docs.py --all --json --full-api --sidebar ``` -------------------------------- ### Run parser tests Source: https://github.com/anselmoo/useful-optimizer/blob/main/scripts/README.md Runs the parser tests for docstring parsing. ```bash # Run parser tests uv run pytest scripts/test/test_docstring_parser.py -v ```