Back to Laboratory
Systems Engineering & Operations ResearchOctober 2026 • 6 min read

Why Operations Research Beats Large Language Models: Spatial Optimization and Hard Constraints with Google OR-Tools

When addressing spatial allocation and NP-hard problems, probabilistic generative models fail on non-negotiable physical constraints. Here is why deterministic solvers like Google OR-Tools CP-SAT remain the gold standard in software engineering.

Author: Giorgio Di Cristofalo•Software Engineer @ ENAV Group
Key Principle:Large Language Models excel at synthesis, document ingestion, and conversational UX. However, when a problem demands mathematical enforcement of hard physical constraints (bathymetric draft, millimeter tolerances, zero spatial overlap), statistical probability must yield to deterministic correctness.

1. The Illusion of Spatial Intuition in LLMs

Transformer models generate sequences by predicting conditional token probabilities learned during training. They possess neither an internal Euclidean coordinate grid nor a geometric constraint propagation engine.

Relying on prompt engineering to allocate dozens of vessels of varying length, beam, and draft (the problem solved in the Harbor Manager project) exposes production systems to three critical vulnerabilities:

  • Zero guarantees on hard constraints: An LLM might produce plausible JSON coordinates, but it cannot formally ensure that two hulls do not overlap by 15 cm or that low-tide draft depth is respected. In a maritime environment, a single violation causes physical hull damage or liability.
  • Combinatorial hallucination: As vessel count and dock density scale, combinatorial complexity explodes. LLMs routinely ignore negative constraints or fabricate non-existent dock coordinates.
  • Computational latency and non-determinism: Heavy LLM inference takes multiple seconds, incurs recurring API token costs, and yields fluctuating output on each run. A mathematical solver converges to a global optimum (or proves infeasibility) in milliseconds on local hardware.

2. Formal Formulation: Constraint Programming & SAT

Constraint Programming reverses the paradigm: instead of guessing solutions by trial and error, it defines the space of admissible states through decision variables and algebraic constraints. The search engine traverses the solution space, pruning infeasible branches via logical propagation.

// 2D Disjoint Interval Bin Packing Formulation
• Spatial variables: x_i (dock position), y_i (fairway distance)
• Temporal windows: [t_start, t_end]
• Physical geometry: Length (L_i), Beam (B_i) + safety clearance buffers
• Bathymetric constraint: Draft_i ≤ WaterDepth(x_i, y_i) ∀ i
• Non-overlap constraint: Overlap(Boat_i, Boat_j) = 0 ∀ i ≠ j

3. Implementation with Google OR-Tools (CP-SAT)

Google OR-Tools provides CP-SAT, a premier constraint solver combining SAT conflict clauses with integer propagation. In Python, 2D disjoint allocation is handled using the native AddNoOverlap2D constraint:

berth_allocation_solver.pyPython 3.12 + OR-Tools CP-SAT
from ortools.sat.python import cp_model

def solve_berth_allocation(boats, dock_length, dock_depth):
    model = cp_model.CpModel()
    x_intervals, y_intervals = [], []
    assigned_vars = {}

    for boat in boats:
        # Decision variables for dock placement (x, y)
        x_start = model.NewIntVar(0, dock_length - boat["length"], f"x_start_{boat['id']}")
        x_end = model.NewIntVar(0, dock_length, f"x_end_{boat['id']}")
        x_int = model.NewIntervalVar(x_start, boat["length"] + boat["buffer_x"], x_end, f"x_int_{boat['id']}")

        y_start = model.NewIntVar(0, dock_depth - boat["width"], f"y_start_{boat['id']}")
        y_end = model.NewIntVar(0, dock_depth, f"y_end_{boat['id']}")
        y_int = model.NewIntervalVar(y_start, boat["width"] + boat["buffer_y"], y_end, f"y_int_{boat['id']}")

        is_assigned = model.NewBoolVar(f"assigned_{boat['id']}")
        assigned_vars[boat['id']] = is_assigned

        x_intervals.append(x_int)
        y_intervals.append(y_int)

    # Core mathematical constraint: zero 2D geometric overlap
    model.AddNoOverlap2D(x_intervals, y_intervals)

    # Objective: maximize economic yield of assigned fleet
    model.Maximize(sum(assigned_vars[b['id']] * b['revenue'] for b in boats))

    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = 5.0
    status = solver.Solve(model)

    if status in (cp_model.OPTIMAL, cp_model.FEASIBLE):
        return {
            b['id']: (solver.Value(model.GetIntVar(f"x_start_{b['id']}")),
                      solver.Value(model.GetIntVar(f"y_start_{b['id']}")))
            for b in boats if solver.Value(assigned_vars[b['id']]) == 1
        }
    return None

4. Real-World Benchmarks: The Harbor Manager Case

In the marina management system engineered by Giorgio, decoupling Google OR-Tools computation inside Celery asynchronous workers yielded definitive results:

+22%Berth space recovered over manual charting
< 2.4sFull marina layout calculation time
0%Hallucinations & maritime safety buffer breaches

5. Proper AI Alignment Across the Production Stack

Engineering maturity does not mean forcing LLMs everywhere; it means assigning the right computational tool to the specific operational challenge:

System ResponsibilityProper Architecture ComponentEngineering Rationale
Natural language parsingLLM (Gemini / Claude / GPT)Extracting structured parameters from unstructured customer emails and chats.
Physical & spatial optimizationGoogle OR-Tools (CP-SAT)Zero hallucinations, deterministic adherence to distance, capacity, and time.
Ultra-fast in-database matchingVector kNN in PostgreSQL<30ms Euclidean similarity queries directly in SQL without API network overhead.
Client streaming dispatchCelery + Redis Pub/Sub + SSEComplete decoupling of heavy computation from synchronous web request threads.

Conclusion

Generative models are invaluable for resolving conversational ambiguity. However, when computational failure results in physical damage, inventory loss, or security liability, discrete mathematics and operations research solvers remain unmatched.

Related Case Study

Harbor Manager — Marina Optimization with OR-Tools

Inspect the end-to-end architecture, PostGIS ➔ Celery ➔ Angular dataflow pipelines, and production metrics.