#4920 2D Orthogonal Constraint Satisfaction Problems (CSPs)

#4920 2D Orthogonal Constraint Satisfaction Problems (CSPs)

#4920 Tell me about 2D Orthogonal Constraint Satisfaction Problems (CSPs)

A 2D Orthogonal Constraint Satisfaction Problem (CSP) is a specialized class of spatial combinatorial problem where a set of discrete two-dimensional entities (typically axis-aligned rectangles, intervals, or rectilinear polygons) must be positioned, ordered, or packed within a bounded or unbounded 2D domain such that all spatial boundaries are parallel to the Cartesian axes (X and Y), and a set of explicit qualitative or metric constraints is completely satisfied.

Unlike continuous non-linear spatial optimization or arbitrary polygonal collision modeling, 2D orthogonal CSPs exploit the decoupling and algebraic simplicity of perpendicular axes. This makes them solvable using discrete combinatorial techniques: SAT/SMT solvers (e.g., Z3), Constraint Programming with Lazy Clause Generation (e.g., OR-Tools CP-SAT, Choco), or qualitative spatial reasoning calculi.

1. Mathematical Formalization

A 2D Orthogonal CSP is formally defined as a triplet (V, D, C):

  • Variables (V): A set of N objects {O_1, O_2, ..., O_n}. For each object i, its spatial placement is defined by coordinate variables:

    • Origin / Lower-Left Anchor: (x_i, y_i) in D_{x_i} x D_{y_i}

    • Extents / Dimensions: (w_i, h_i) in mathbb{Z}^+ x mathbb{Z}^+ (fixed constants or bounded variables)

    • Upper-Right Boundary: (x_i + w_i, y_i + h_i)

  • Domains (D): Typically discrete grids or continuous intervals on mathbb{Z}^2 or mathbb{R}^2:

    x_i in [0, W - w_i], quad y_i in [0, H - h_i]

    where W, H are the bounding frame dimensions.

  • Constraints (C): A conjunction of spatial, topological, and operational predicates:

    C = C_non-overlap land C_containment land C_relative land C_domain-specific

2. Core Constraint Primitives

A. The Non-Overlap Constraint (Mutual Exclusion)

The cornerstone of metric 2D orthogonal problems is pairwise non-overlapping. For two axis-aligned bounding boxes A and B, the condition (A cap B = emptyset) translates to a 4-way disjunctive constraint:

(x_A + w_A <= x_B) lor (x_B + w_B <= x_A) lor (y_A + h_A <= y_B) lor (y_B + h_B <= y_A)

In logic-based solvers, this disjunction is often encoded using Boolean selection variables b_{i, j}^{left}, b_{i, j}^{right}, b_{i, j}^{below}, b_{i, j}^{above} enforced via Big-M reformulations or SMT theory clauses.

In dedicated CP solvers, this is encapsulated in global propagator constraints such as:

  • diffn([x_1, ..., x_n], [y_1, ..., y_n], [w_1, ..., w_n], [h_1, ..., h_n])

  • 2D-NoOverlap / Cumulative sweep-line propagators (tracking profile heights across intervals).

B. Rotation (Orientation Variables)

If entities can rotate by 90-degrees:

r_i in {0, 1}
w_i = (1 - r_i) W_i + r_i H_i, quad h_i = r_i W_i + (1 - r_i) H_i

C. Topological & Qualitative Spatial Relations

Rather than absolute numeric coordinates, some 2D orthogonal CSPs deal with relational topology:

  • Allen’s Interval Algebra in 2D (Rectangle Algebra / Block Algebra): Projects spatial relationships onto independent horizontal and vertical interval relations (13 x 13 = 169 atomic qualitative relations such as meets, before, overlaps, during, starts, finishes).

  • Cardinal Direction Calculus (CDC): Enforces directional orientation (e.g., Object A is strictly North-West of Object B, bounding the projection cones orthogonally).

3. Canonical Problem Archetypes

DomainProblem ArchetypePrimary Solver Formulation
VLSI Physical DesignMacro/Cell Floorplanning, Wire-length minimizationSMT / Branch-and-Cut, B*Trees, Sequence Pairs
Digital FabricationGuillotine & 2D Orthogonal Strip Packing (CNC/Laser cutting)CP-SAT (diffn), Column Generation, Integer Linear Programming (ILP)
Automated LayoutUI Dashboards, Tiled Window Managers, PCB silkscreen/pad routingSMT / Linear Difference Constraints (x_j - x_i \ge c)
Logistics & WarehousingPallet/bin orthogonal cross-sections, 2D container loadingConstraint Programming + Sweep-line energetic reasoning
Spatial Graph DrawingOrthogonal Grid Embedding (edges as sequences of horizontal/vertical segments)SAT reduction + Flow networks on grid graphs

4. Complexity and Theoretical Profile

  1. NP-Completeness: Metric 2D orthogonal packing and layout problems are generally NP-complete in the decision form (strongly NP-hard in optimization), reducible from 1D Bin Packing and Subset Sum.

  2. Phase Transitions: In dense orthogonal packing, problems exhibit sharp phase transitions between trivial satisfiability and provable unsatisfiability when the total entity area exceeds ~ 78–}85% of the container area, driven by combinatorially explosive "waste slice" fragmentation.

  3. Interval Tractability: If relations are restricted to Horn subsets of Allen’s Rectangle Algebra without disjunctive metric overlaps, the consistency check collapses to polynomial time (mathcal{O}(n^3) via path consistency / Floyd-Warshall variants).

5. Solving Paradigms

                      2D Orthogonal CSP Problem
                                  │
         ┌────────────────────────┴────────────────────────┐
         ▼                                                 ▼
   Discrete / Metric                                Qualitative / Relational
  (Coordinates & Sizes)                             (Topology & Orderings)
         │                                                 │
   ┌─────┴─────────────────────┐                           ▼
   ▼                           ▼                   Allen's Rectangle Algebra /
CP-SAT Solvers             SMT Solvers             Path Consistency (O(n³))
(Lazy Clause Generation,   (Difference Logic,      (Constraint propagation over
 energetic reasoning)      Z3 Bit-Vector/LIA)      composition tables)
   │                           │
   └───────────┬───────────────┘
               ▼
   Dual-Sweep Propagators:
   - Cumulative Profile Sweeping
   - No-Overlap (diffn) Pruning
   - Redundant Area Filtering (Σ area ≤ Container Area)
  1. CP-SAT / Lazy Clause Generation (e.g., OR-Tools CP-SAT):

    • Uses interval variables along the X and Y dimensions.

    • Leverages the AddNoOverlap2D propagator, which coordinates between 1D Cumulative/Sweep reasoning on each dimension to detect 2D space starvation before branching.

  2. SMT (Satisfiability Modulo Theories - e.g., Z3):

    • Encodes coordinates under Quantifier-Free Linear Integer Arithmetic (QF_LIA).

    • Highly effective when spatial placement is coupled with complex discrete logic (e.g., "if component A is adjacent to component B, thermal clearance must increase by Delta").

  3. Topological Encodings (Sequence Pairs / B-Trees):*

    • Encodes relative positions topologically as a pair of permutations (Gamma_+, Gamma_-).

    • Guarantees that any permutation decoded via DAG longest-path produces an overlap-free orthogonal placement, converting the CSP search space into a permutation search space.

6. Minimal Concrete Implementation (OR-Tools CP-SAT)

The following Python script illustrates how a metric 2D Orthogonal CSP is modeled and solved using modern CP-SAT interval primitives:

from ortools.sat.python import cp_model

def solve_2d_orthogonal_placement(container_w, container_h, items):
    """
    items: list of dicts [{'name': 'A', 'w': 4, 'h': 3}, ...]
    """
    model = cp_model.CpModel()
    x_intervals = []
    y_intervals = []
    placements = {}

    for item in items:
        name = item['name']
        w, h = item['w'], item['h']

        # Coordinate variables bounded within container frame
        x = model.NewIntVar(0, container_w - w, f"{name}_x")
        y = model.NewIntVar(0, container_h - h, f"{name}_y")

        # Fixed-size 1D interval variables for each axis
        x_int = model.NewFixedSizeIntervalVar(x, w, f"{name}_x_int")
        y_int = model.NewFixedSizeIntervalVar(y, h, f"{name}_y_int")

        x_intervals.append(x_int)
        y_intervals.append(y_int)
        placements[name] = (x, y, w, h)

    # Core 2D Orthogonal Non-Overlap Global Constraint
    model.AddNoOverlap2D(x_intervals, y_intervals)

    # Global Redundant Constraint: Area conservation pruning
    total_area = sum(it['w'] * it['h'] for it in items)
    assert total_area <= container_w * container_h, "Area exceeds container bound!"

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

    if status in (cp_model.OPTIMAL, cp_model.FEASIBLE):
        results = {}
        for name, (x, y, w, h) in placements.items():
            results[name] = {
                "x": solver.Value(x),
                "y": solver.Value(y),
                "w": w,
                "h": h
            }
        return results
    return None

# Example usage:
blocks = [
    {'name': 'M1', 'w': 6, 'h': 4},
    {'name': 'M2', 'w': 5, 'h': 5},
    {'name': 'M3', 'w': 3, 'h': 7},
    {'name': 'M4', 'w': 4, 'h': 2},
]
layout = solve_2d_orthogonal_placement(container_w=10, container_h=10, items=blocks)
print(layout)

Would you like to explore:

  1. Extending this formulation with variable 90-degree orientation switching and spacing margins?

  2. Formulating qualitative 2D orthogonal relationships using Z3 SMT and Allen's Rectangle Algebra?

  3. Topological intermediate representations (e.g., Sequence Pairs) for floorplan optimization?

Are you targeting metric placement (exact coordinates/packing) or qualitative spatial ordering (topology/graph relations)? What target solver or toolchain do you plan to run (e.g., OR-Tools CP-SAT, Z3, or custom propagation)?


Sudoku and Grid-Poker are two examples of this concept to game play. List and describe 15 additional fun games that could be created from this concept

2D Orthogonal Constraint Satisfaction Problems (CSPs) structure gameplay by treating a board as a coordinate system where orthogonal vectors (rows, columns, and perpendicular adjacencies) govern non-overlap, parity, connectivity, and projection.

1. Graeco-Latin Arena (Bi-Latin Matrix)

  • Components: An N x N board and tokens defined by two orthogonal attributes: Color and Glyph (e.g., 5 colors x 5 glyphs = 25 unique pieces).

  • Orthogonal Constraints: Each row and column must contain exactly one of each color and one of each glyph (dual Latin squares). Globally, no two tokens on the board may share the same (Color, Glyph) pair.

  • Win/End State: Players draft tokens from a common pool; points are scored by completing orthogonal lines, while placing a token that creates an unsatisfiable cell for the opponent scores bonus disruption points.

2. Cross-Sum Dominoes (OrthoDomino)

  • Components: A set of standard double-six dominoes (1 x 2 rectilinear tiles) and an 8 x 8 bounded grid with target sums printed along the margins.

  • Orthogonal Constraints: Dominoes must pack orthogonally without overlap. Where two domino edges touch, the adjacent half-cells must match pips (standard domino adjacency). Simultaneously, the sum of all pips in every row and column must equal the margin's numerical target.

  • Win/End State: Solitaire puzzle or cooperative mode where all tiles must be placed without dead-ending the board's numeric totals.

3. Sonar Fleet (Radar Cross-Sum)

  • Components: A hidden 10x10 ocean grid, fleets of rectilinear ships (1x1 patrol boats to 1x4 carriers), and ping clues.

  • Orthogonal Constraints: Ships cannot touch one another orthogonally or diagonally. Row and column headers display the exact number of occupied cells along that orthogonal line. Numeric "sonar" clues in specific empty cells reveal the Manhattan distance (vert{}x_1 - x_2 vert{} + vert{}y_1 - y_2 vert{}) to the nearest ship hull.

  • Win/End State: Deducing and marking the exact coordinates and orientations of the entire fleet.

4. Photon Grid (Laser & Mirror Reflex)

  • Components: Fixed laser emitters and color filters along the grid boundaries; rotatable 45-degree two-way mirrors and beam-splitters.

  • Orthogonal Constraints: Laser beams propagate strictly along orthogonal grid axes. Every collector must receive its designated wavelength. Mirrors deflect beams 90-degrees; splitters divide them orthogonally. No two beams of the same wavelength may overlap along the same directional segment, and each row and column has a strict capacity limit on placed optical elements.

  • Win/End State: Directing all laser beams from origin to target in a single concurrent propagation tick.

5. Skyscrapers & Zoning Envelopes

  • Components: An N x N city plot with integer building blocks representing heights 1 through N.

  • Orthogonal Constraints: Every row and column must contain heights 1 to N with no duplicates. Perimeter numbers indicate how many buildings are visible along that line of sight (taller buildings obscure shorter ones). Cells marked with color-coded "zoning envelopes" impose additional local inequality constraints (e.g., Height(x, y) <= 3 or Height(A) > Height(B)).

  • Win/End State: Reconstructing the entire skyline configuration satisfying all sightlines and zoning limits.

6. Tents and Trees (Bipartite Orthogonal Matching)

  • Components: A grid containing pre-placed tree tokens; players place tent tokens.

  • Orthogonal Constraints: Every tent must be assigned to an orthogonally adjacent tree (a 1-to-1 bijection). No two tents may touch each other horizontally, vertically, or diagonally. Numbers flanking each row and column dictate the exact tent quota for that orthogonal slice.

  • Win/End State: Placing all required tents without leaving an unassigned tree or violating margin tallies.

7. Circuit Board Routing (Trace-Lock)

  • Components: A PCB breadboard grid with fixed pin components (power sources, ground pins, and microchips).

  • Orthogonal Constraints: Players lay conductive copper traces composed of horizontal and vertical line segments. Traces between matching pin pairs cannot intersect unless passed through a dedicated 2-layer via tile. Total segment lengths along each axis cannot exceed resistance thresholds, and traces must maintain a minimum 1-cell orthogonal clearance from opposite-polarity components.

  • Win/End State: Complete point-to-point pin routing with zero short circuits and minimum wire length.

8. Aquarium Water Levels

  • Components: A grid partitioned into irregular, non-overlapping polyomino regions ("aquarium tanks").

  • Orthogonal Constraints: Cells are either filled with water or air. Water obeys virtual gravity: within any single polyomino tank, if a cell is filled, all cells in that same tank sharing the same horizontal row (or rows below it) must also be filled. Marginal column and row counters indicate exact total water-cell counts.

  • Win/End State: Identifying the equilibrium fill-pattern matching all perimeter counts.

9. Orthogonal Word Cross-Boggle (Cross-Lexicon)

  • Components: A letter tile rack and an N x N grid with blocked cells.

  • Orthogonal Constraints: Players place tiles into empty cells. Every continuous orthogonal run of letters horizontally and vertically must form an accepted word from a designated dictionary. Letters placed must satisfy intersecting word constraints simultaneously in both directions, and each row/column must meet a vowel-to-consonant parity check.

  • Win/End State: Scoring points proportional to word length and rare letter placements, ending when no legal orthogonal insertions remain.

10. Yin-Yang Territory (Dual-Shade Contiguity)

  • Components: A grid partially seeded with black and white circular markers.

  • Orthogonal Constraints: Every cell must be designated Black or White. All black cells must form a single, unbroken, orthogonally contiguous cluster. All white cells must form a single, unbroken, orthogonally contiguous cluster. Neither color may form a 2 x 2 solid monochromatic block anywhere on the board.

  • Win/End State: Fully coloring the board while proving topological connectivity for both sets.

11. Hydro-Grid (Pipe Pressure Balance)

  • Components: Square tiles featuring straight lines, 90-degree elbows, cross-connectors, and blank dead-ends.

  • Orthogonal Constraints: Placed tiles must match open pipe interfaces with adjacent orthogonal neighbors (no open ends facing a closed wall or blank face). Water pumps supply input pressure, and pressure drops by 1 unit for every orthogonal cell traversed; all designated factory terminals must receive pressure >= P_min.

  • Win/End State: Building a continuous, leak-free distribution network from source to sinks.

12. Slitherlink Rail (Eulerian Edge Loop)

  • Components: A grid of dots where interior squares display clues from 0 to 3.

  • Orthogonal Constraints: Players draw orthogonal horizontal and vertical line segments between adjacent dots. The segments must form a single, closed, continuous loop with no branches or dead ends. A number inside a cell indicates exactly how many of its 4 orthogonal edges are segments of the loop.

  • Win/End State: Closing the global loop without sub-loops or edge count discrepancies.

13. TetraLock (Orthogonal Gravity Packing)

  • Components: Classic polyomino shapes (monominoes through pentominoes).

  • Orthogonal Constraints: Standard 2D non-overlap (diffn) constraints across all placed blocks. Every piece must be grounded: each piece requires at least one of its lower boundary cells to rest on the container floor or on the top edge of another piece (no floating overhangs without vertical support). Columns must alternate parity (e.g., odd total volume in odd columns, even in even columns).

  • Win/End State: Maximizing packing density within a tight bounding box while clearing completed horizontal lines.

14. Rectilinear Dungeon Architect

  • Components: Rectangular room cards of dimensions w_i x h_i and 1-cell corridor strips.

  • Orthogonal Constraints: Rooms cannot overlap and must be placed axis-aligned. Corridors must run strictly north-south or east-west, entering rooms only through predefined orthogonal portal cells. The shortest-path Manhattan distance from the Entrance chamber to the Boss chamber through the corridor network must fall between D_min and D_max, with fire hazards imposing minimum orthogonal buffers between adjacent chambers.

  • Win/End State: Completing the floorplan within a fixed bounding lot size while hitting pacing and distance metrics.

15. CalcCross (Orthogonal Cryptarithm Matrix)

  • Components: An N x N matrix pre-populated with arithmetic symbols (+, -, x, /, =) at alternating intersections.

  • Orthogonal Constraints: Players place digits $0\text{–}9$ into the remaining empty slots. Every horizontal equation must evaluate correctly from left to right, and every vertical equation must evaluate correctly from top to bottom. Each sub-quadrant must adhere to an All-Different constraint on its assigned digits.

  • Win/End State: Complete arithmetic balance across all intersecting equations without repeating restricted digits.


From <https://gemini.google.com/app/b61c749b16d92aeb>  Google Gemini (3.8 Flash)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#3356 PHP and JavaScript to Retrieve and Set an API_Key

#4188 Hybrid/GraphRAG