Pymoo nsga2 constrained

From XuShuwenn/RedAct · View interactive version

Pymoo nsga2 constrained is an AI agent skill from the GitHub repository XuShuwenn/RedAct. Solve bounded single-objective optimization problems with inequality constraints using pymoo's NSGA-II, extract the best solution robustly, and verify feasibility before formatting output.

How to use this skill

Skill file

Constrained Single-Objective Optimization with pymoo (NSGA-II)

Reusable workflow for minimizing a scalar objective under bounds and inequality constraints using pymoo's NSGA-II. It includes robust result extraction, feasibility verification, and output formatting.

When to Use

Activate this skill when you need to:

Core Workflow

  1. Define the problem with ElementwiseProblem
from pymoo.core.problem import ElementwiseProblem
import numpy as np

class MyProblem(ElementwiseProblem):
    def __init__(self, n_var, xl, xu, n_ieq):
        super().__init__(
            n_var=n_var,
            n_obj=1,
            n_ieq_constr=n_ieq,
            xl=np.asarray(xl, dtype=float),
            xu=np.asarray(xu, dtype=float),
        )

    def _evaluate(self, x, out, **kwargs):
        # Define objective f(x)
        f = ...  # e.g., float expression using x

        # Define inequality constraints G(x) <= 0
        # Example placeholders (ensure length == n_ieq):
        G = [ ... ]  # each entry is a float constraint value

        out["F"] = f
        out["G"] = np.asarray(G, dtype=float)
  1. Configure and run NSGA-II
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.optimize import minimize

algorithm = NSGA2(pop_size=100, n_offsprings=100, eliminate_duplicates=True)
res = minimize(MyProblem(...), algorithm, ('n_gen', 200), seed=1, verbose=False)
  1. Robustly extract the best solution
import numpy as np

X = np.atleast_2d(res.X)
F = np.asarray(res.F).reshape(-1)
idx = int(np.argmin(F))
best_x = X[idx]
best_f = float(F[idx])
  1. Verify feasibility and bounds before finalizing
# Recompute G(x) for best_x exactly as in _evaluate
G_best = np.asarray([ ... ], dtype=float)  # same expressions used to populate out["G"]
violation = float(np.maximum(G_best, 0.0).max()) if G_best.size else 0.0
assert violation <= 1e-6, "Best solution is not feasible within tolerance."

# Bound check
tol = 1e-8
xl = np.asarray(..., dtype=float)
xu = np.asarray(..., dtype=float)
assert np.all(best_x >= xl - tol) and np.all(best_x <= xu + tol), "Bounds violated."
  1. Format and write output
with open(output_path, 'w') as f:
    for i, v in enumerate(best_x, start=1):
        f.write(f"Optimal x{i}: {v:.2f}\n")
    f.write(f"Objective: {best_f:.2f}\n")

Verification

Common Pitfalls and How to Avoid Them

Optional Script Usage

Use scripts/pymoo_utils.py to simplify robust extraction, feasibility checks, and output formatting.

from pymoo.optimize import minimize
from pymoo.algorithms.moo.nsga2 import NSGA2
import numpy as np
from scripts.pymoo_utils import best_from_result, max_constraint_violation, write_rounded_solution

# ... define MyProblem as above
problem = MyProblem(...)
algorithm = NSGA2(pop_size=100, n_offsprings=100, eliminate_duplicates=True)
res = minimize(problem, algorithm, ('n_gen', 200), seed=1, verbose=False)

best_x, best_f, _ = best_from_result(res)

# Recompute G(best_x) as in _evaluate
G_best = np.asarray([ ... ], dtype=float)
assert max_constraint_violation(G_best) <= 1e-6

write_rounded_solution(output_path, best_x, best_f, decimals=2)

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.