Skip to content

Comments

Centralize magic numbers into constants module#45

Merged
Anselmoo merged 9 commits intomainfrom
copilot/centralize-magic-numbers
Dec 21, 2025
Merged

Centralize magic numbers into constants module#45
Anselmoo merged 9 commits intomainfrom
copilot/centralize-magic-numbers

Conversation

Copy link
Contributor

Copilot AI commented Dec 21, 2025

The codebase had 381 PLR2004 violations (magic number comparisons) with values scattered across 100+ files. This creates a centralized constants module as foundation for incremental migration.

Changes

Created opt/constants.py

  • 50+ constants organized by category: population defaults, convergence thresholds, PSO parameters, gradient optimizer constants, benchmark function bounds
  • Each constant documented with purpose and typical usage

Migrated 4 core files (proof of concept)

  • abstract_optimizer.py: DEFAULT_MAX_ITERATIONS, DEFAULT_POPULATION_SIZE, DEFAULT_SEED
  • particle_swarm.py: PSO_INERTIA_WEIGHT, PSO_COGNITIVE_COEFFICIENT, PSO_SOCIAL_COEFFICIENT
  • nadam.py: ADAM_BETA1, ADAM_BETA2, ADAM_EPSILON, NADAM_LEARNING_RATE
  • adamw.py: All above plus ADAMW_LEARNING_RATE, ADAMW_WEIGHT_DECAY

Test coverage

  • opt/test/test_constants.py: 20 tests validating types, ranges, mathematical relationships

Documentation

  • opt/CONSTANTS.md: Usage guide, migration status, contributing guidelines
  • pyproject.toml: Added migration strategy comments explaining incremental approach

Example

Before:

def __init__(self, ..., max_iter: int = 1000, c1: float = 1.5, c2: float = 1.5, w: float = 0.5):

After:

from opt.constants import DEFAULT_MAX_ITERATIONS, PSO_COGNITIVE_COEFFICIENT, PSO_SOCIAL_COEFFICIENT, PSO_INERTIA_WEIGHT

def __init__(self, ..., max_iter: int = DEFAULT_MAX_ITERATIONS, c1: float = PSO_COGNITIVE_COEFFICIENT, 
             c2: float = PSO_SOCIAL_COEFFICIENT, w: float = PSO_INERTIA_WEIGHT):

Impact

  • PLR2004 violations: 381 → 377 (4 eliminated, pattern established for remaining)
  • No breaking changes: all default values identical to previous hard-coded values
  • Remaining gradient-based optimizers (6 files), swarm algorithms (50+ files), and other categories can follow this pattern
Original prompt

This section details on the original issue you should resolve

<issue_title>Centralize magic numbers and remove temporary ruff ignore workarounds</issue_title>
<issue_description>## Summary

The pyproject.toml currently ignores several linting rules as a temporary workaround rather than properly addressing the underlying code quality issues. Magic numbers and other code patterns should be centralized and properly managed.

Current State

The following rules are currently ignored in pyproject.toml:

ignore = [
    "PLR0913",   # Too many arguments - should use config objects
    "PLR1704",   # Redefining argument - needs refactor
    "N803",      # Argument name not lowercase
    "N806",      # Variable name not lowercase
    "E741",      # Ambiguous variable name
    "E501",      # Line too long
    "T201",      # Print statements
    "COM812",    # Missing trailing comma
    "NPY002",    # Legacy numpy random calls
    "D107",      # Missing docstring in __init__
    "D103",      # Missing docstring in public function
    "PLR2004",   # Magic value comparisons - COMMON IN OPTIMIZATION ALGORITHMS
    "PLR0912",   # Too many branches
    "PLR0915",   # Too many statements
    "C901",      # Too complex
    # ... and more
]

Tasks

Phase 1: Centralize Constants

  • Create opt/constants.py module for algorithm-specific constants
  • Define named constants for commonly used values (convergence thresholds, population sizes, etc.)
  • Group constants by category (e.g., DEFAULT_MAX_ITER, DEFAULT_TOLERANCE, GOLDEN_RATIO, etc.)

Phase 2: Address Code Quality

  • Replace magic numbers with named constants (PLR2004)
  • Add missing docstrings (D103, D107)
  • Refactor functions with too many arguments to use configuration dataclasses (PLR0913)
  • Address legacy numpy random calls (NPY002) - migrate to np.random.default_rng()
  • Remove unnecessary print statements or convert to proper logging (T201)

Phase 3: Update Configuration

  • Gradually remove ignore rules from pyproject.toml as code is fixed
  • Add per-file ignores only where truly necessary (e.g., test files)
  • Document any rules that remain ignored with clear justification

Example Structure

# opt/constants.py
from __future__ import annotations

# Population defaults
DEFAULT_POPULATION_SIZE = 100
DEFAULT_MAX_ITERATIONS = 1000

# Convergence thresholds
DEFAULT_TOLERANCE = 1e-6
DEFAULT_CONVERGENCE_THRESHOLD = 1e-8

# Algorithm-specific constants
GOLDEN_RATIO = 1.618033988749895
PSO_INERTIA_WEIGHT = 0.7298
PSO_COGNITIVE_COEFFICIENT = 1.49618
PSO_SOCIAL_COEFFICIENT = 1.49618

# KDE bandwidth defaults
DEFAULT_BANDWIDTH = 0.2
DEFAULT_GAMMA = 0.15

Labels

refactor, code-quality, technical-debt</issue_description>

Comments on the Issue (you are @copilot in this section)


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Co-authored-by: Anselmoo <13209783+Anselmoo@users.noreply.github.com>
Co-authored-by: Anselmoo <13209783+Anselmoo@users.noreply.github.com>
Co-authored-by: Anselmoo <13209783+Anselmoo@users.noreply.github.com>
Copilot AI changed the title [WIP] Centralize magic numbers and remove linting ignores Centralize magic numbers into constants module Dec 21, 2025
Copilot AI requested a review from Anselmoo December 21, 2025 16:35
@Anselmoo Anselmoo marked this pull request as ready for review December 21, 2025 16:52
Copilot AI review requested due to automatic review settings December 21, 2025 16:52
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request establishes a foundation for incremental migration of magic numbers to a centralized constants module, addressing PLR2004 linting violations. The PR introduces opt/constants.py with 50+ well-documented constants and migrates 4 core files as a proof of concept.

Key Changes

  • Created centralized constants module with comprehensive documentation covering population defaults, convergence thresholds, PSO parameters, gradient optimizer constants, and benchmark function bounds
  • Migrated 4 core optimizer files (abstract_optimizer, particle_swarm, nadam, adamw) to use named constants instead of hardcoded values
  • Added comprehensive test suite with 20 tests validating constant types, ranges, and mathematical relationships

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
opt/constants.py New centralized constants module with 50+ documented constants organized by category (population, convergence, PSO, gradient-based, etc.)
opt/test/test_constants.py Comprehensive test suite validating constant types, ranges, and relationships
opt/CONSTANTS.md Documentation covering usage patterns, migration status, and contributing guidelines
opt/abstract_optimizer.py Migrated to use DEFAULT_MAX_ITERATIONS, DEFAULT_POPULATION_SIZE, DEFAULT_SEED, and POWER_THIRTY_TWO constants
opt/swarm_intelligence/particle_swarm.py Migrated PSO-specific parameters to use PSO_INERTIA_WEIGHT, PSO_COGNITIVE_COEFFICIENT, and PSO_SOCIAL_COEFFICIENT
opt/gradient_based/nadam.py Migrated to use ADAM_BETA1, ADAM_BETA2, ADAM_EPSILON, and NADAM_LEARNING_RATE constants
opt/gradient_based/adamw.py Migrated to use Adam constants plus ADAMW_LEARNING_RATE and ADAMW_WEIGHT_DECAY
pyproject.toml Added explanatory comments documenting the incremental migration strategy for PLR2004

opt/constants.py Outdated
Comment on lines 133 to 134
ACKLEY_C = 2.0
"""Ackley function constant 'c' (typically 2*pi)."""
Copy link

Copilot AI Dec 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ACKLEY_C constant is set to 2.0, but the docstring states it's "typically 2*pi". Looking at the actual Ackley function implementation in opt/benchmark/functions.py (line 59), it uses 2.0 * np.pi which equals approximately 6.283185307179586, not 2.0.

If this constant is intended to represent the 'c' parameter in the standard Ackley function formula, it should be:

  • ACKLEY_C = 2.0 * np.pi (approximately 6.283185307179586)

Alternatively, if the intent is to have a separate constant for the multiplier (2.0) and use it as ACKLEY_C * np.pi, the docstring should be updated to clarify this usage pattern. However, this would be non-standard and potentially confusing.

Copilot uses AI. Check for mistakes.
@Anselmoo Anselmoo merged commit bd94f2f into main Dec 21, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Centralize magic numbers and remove temporary ruff ignore workarounds

2 participants