Problem: Simplex Tableau Pivot Operations Implementation

The problem focuses on creating robust simplex algorithm functions—pivot column/row selection, pivot row normalization, and column elimination—supporting dense/sparse matrices, ensuring numerical stability, handling degeneracy, and validating inputs to enable solving linear programming maximization problems.

Background: ### Industry & Mathematical Background for Simplex Method Core Functions
Linear Programming (LP) is a cornerstone of operations research, with widespread adoption across supply chain optimization, manufacturing scheduling, financial portfolio management, energy grid dispatch, and global transportation routing. Real-world LP models often feature large-scale, sparse coefficient matrices, demanding efficient, numerically stable implementations of the simplex method—the gold-standard algorithm for solving LP problems.

The provided functions implement core components of an enhanced simplex method, with industry-focused optimizations:

1. **`find_pivot_column` (Entering Variable Selection)**
   - **Mathematical Foundation**: For maximization LP problems, the entering variable is identified by the most negative coefficient in the objective function (Z) row. This variable, when increased, yields the largest marginal improvement to the objective value.
   - **Industry-Critical Features**:
     - **Sparse Matrix Support**: Large-scale LP models (e.g., national energy grids) have sparse Z-rows; traversing only non-zero elements reduces computation time by orders of magnitude.
     - **Numerical Precision Handling**: Floating-point noise in real-world calculations is filtered using an epsilon threshold (1e-12) to avoid selecting spurious negative values.
     - **Cycling Avoidance**: Degenerate LP problems (common in tight resource allocation scenarios) can cause infinite loops (cycling). Random selection among tied most-negative coefficients provides a practical alternative to Bland's rule for performance while preventing cycling.

2. **`find_pivot_row` (Leaving Variable Selection)**
   - **Mathematical Foundation**: The Minimum Ratio Test (MRT) calculates the ratio of right-hand side (RHS) values to positive coefficients in the entering variable column. The smallest valid ratio identifies the leaving variable, ensuring the resulting basic solution remains feasible and avoids unboundedness.
   - **Industry-Critical Features**:
     - **Degeneracy Resolution**: Tiny random perturbations to ratios (when numpy is available) break ties in MRT, eliminating cycling in degenerate cases such as manufacturing lines with exact resource limits.
     - **Sparse Optimization**: For sparse tableaus, only non-zero elements in the entering column are processed, optimizing performance for logistics models with 10k+ constraints.
     - **Numerical Stability**: Epsilon comparisons (1e-9) prevent division by near-zero values, a common source of errors in financial LP models with minimal coefficient differences.

3. **`normalize_pivot_row` (Pivot Row Scaling)**
   - **Mathematical Foundation**: The pivot row (intersection of entering column and leaving row) is scaled to set the pivot element to 1, a prerequisite for Gaussian elimination to zero out the pivot column in other rows.
   - **Industry-Critical Features**:
     - **Near-Zero Pivot Stabilization**: Real-world LP problems (e.g., high-dimensional portfolio optimization) often encounter near-zero pivots, which cause numerical instability. Random perturbations are added to these pivots to stabilize calculations without sacrificing solution validity.
     - **Multi-Data-Type Support**: Dense lists, numpy arrays, and scipy sparse matrices are supported to match workflow needs—dense for small-scale scheduling, sparse for large grid optimization.
     - **Complex Number Compatibility**: Extends utility to complex LP problems in telecommunications (signal processing optimization) and quantum computing (quantum state allocation).

4. **`eliminate_other_rows` (Gaussian Elimination)**
   - **Mathematical Foundation**: Gaussian elimination is applied to zero out the pivot column in all non-pivot rows, updating the tableau to reflect the new basic feasible solution.
   - **Industry-Critical Features**:
     - **Sparse Dictionary Representation**: Ultra-large LP models (e.g., global supply chains with 100k+ variables) use row-wise dictionaries to store non-zero elements, drastically reducing memory overhead and speeding up element-wise operations.
     - **Noise Reduction**: Values below an epsilon threshold are removed from sparse rows to keep the tableau compact, improving long-term computation efficiency for repeated LP runs (e.g., daily inventory optimization).
     - **Stability for Repeated Runs**: Perturbing near-zero pivots ensures elimination does not introduce numerical artifacts, critical for consistent results in automated, high-frequency LP applications like real-time routing.

These functions implement an enhanced revised simplex method, optimized for the numerical and scale challenges of real-world industrial LP deployments. Understanding this background ensures accurate reproduction of the code, as each feature addresses a specific pain point in industry LP implementations.

Input/Output: The problem receives a simplex tableau (supporting dense formats: list of lists, numpy ndarray; sparse formats: scipy sparse matrix, list of dictionaries) where the last row is the objective function and the last column is the right-hand side (RHS). It also accepts a pivot column index (col_idx, integer) for pivot row selection and both pivot row (row_idx, integer) and column (col_idx, integer) indices for row normalization and column elimination steps.  

The problem generates: 1) An integer pivot column index (-1 if no negative coefficients exist in the objective row’s non-RHS part); 2) An integer pivot row index (-1 if the problem is unbounded); 3) A modified tableau after normalizing the pivot row (scaled to a unit pivot, with near-zero pivots perturbed to avoid numerical issues); 4) A modified tableau after eliminating the pivot column from non-pivot rows (after scaling the pivot row to unit pivot). All outputs preserve the input’s data format (dense remains dense, sparse remains sparse).

Required dependencies:
import random
import math
import warnings
from typing import Union, List, Optional, Dict
import numpy as np
from scipy import sparse as sp
from scipy.sparse import csr_matrix, isspmatrix

Sub-steps:
step_number: 1
step_description_prompt: Please write a Python function named find_pivot_column that finds the pivot column in a simplex tableau for maximization. It supports list of lists, numpy arrays, scipy sparse matrices, handles precision with epsilon, selects from tied candidates considering feasibility, returns -1 if no negative coefficients exist in the objective row (excluding RHS).
function_header: def find_pivot_column(tableau):
test_cases: import math
for tab, expected in [
    ([[1, 2, 10], [-3, -5, 0]], 1),     # -5 最负，索引为 1
    ([[1, 0, 5], [1, 2, 0]], -1),        # 无负数，已达到最优解
    ([[2, 4, 8], [-10, -2, 0]], 0)       # -10 最负，索引为 0
]:
    assert find_pivot_column(tab) == expected

step_number: 2
step_description_prompt: Please write a Python function named find_pivot_row. It identifies the pivot row in a simplex tableau for a specified column using the minimum ratio test with numerical stability (epsilon comparisons), sparse matrix optimization, degeneracy handling via tiny perturbations (if numpy exists), and input validation. Return the pivot row index or -1 if unbounded.
function_header: def find_pivot_row(tableau, col_idx):
test_cases: import math
for tab, col_idx, expected in [
    ([[2, 1, 8], [4, 1, 12], [0, 0, 0]], 0, 1),   
    ([[1, 2, 5], [-1, 1, 10], [0, 0, 0]], 0, 0),  
    ([[1, 1, 10], [2, 1, 10], [0, 0, 0]], 0, 1)   
]:
    assert find_pivot_row(tab, col_idx) == expected

step_number: 3
step_description_prompt: Please write a Python function named normalize_pivot_row. It takes a tableau (2D list, numpy array, or scipy sparse matrix), row_idx, col_idx. Validate inputs, check if pivot at (row_idx, col_idx) is near zero (add perturbation if so), then divide the row by the pivot value. Return the modified tableau.

This prompt is concise, specifies the function name, input types, key steps (validation, pivot check with perturbation, row normalization), and return value, ensuring another model can reproduce the code without excessive detail. It meets all requirements: correct function name, English only, 50-100 words, and clear instructions for code复现.

**Answer:**  
Please write a Python function named normalize_pivot_row. It accepts a tableau (2D list, numpy array, or scipy sparse matrix), row_idx, col_idx. Validate inputs, check if pivot at (row_idx, col_idx) is near zero (perturb if needed), then divide the row by the pivot. Return the modified tableau.
function_header: def normalize_pivot_row(tableau, row_idx, col_idx):
test_cases: import math
for tab, r_idx, c_idx, exp_row in [
    ([[2, 4, 6], [0, 0, 0]], 0, 0, [1.0, 2.0, 3.0]),    
    ([[0.5, 1, 1.5], [0, 0, 0]], 0, 0, [1.0, 2.0, 3.0]), 
    ([[1, 5, 10], [0, 0, 0]], 0, 0, [1.0, 5.0, 10.0])    
]:

    res = normalize_pivot_row([list(r) for r in tab], r_idx, c_idx)
    assert all(math.isclose(res[r_idx][j], exp_row[j]) for j in range(len(exp_row)))

step_number: 4
step_description_prompt: Please write a Python function named eliminate_other_rows that takes tableau (dense list of lists or sparse list of dicts), pivot_row_idx, pivot_col_idx. It validates inputs, handles near-zero pivots with perturbation, scales pivot row to unit pivot, then eliminates the pivot column from other rows. Return modified tableau.
function_header: def eliminate_other_rows(tableau, pivot_row_idx, pivot_col_idx):
test_cases: import math
for tab, r_idx, c_idx, exp_other in [
    ([[1, 2, 3], [2, 5, 7]], 0, 0, [0.0, 1.0, 1.0]),     
    ([[0, 1, 5], [1, 0, 10]], 1, 0, [0.0, 1.0, 5.0]),    
    ([[1, 0], [5, 1]], 0, 0, [0.0, 1.0])                 
]:
    res = eliminate_other_rows([list(r) for r in tab], r_idx, c_idx)
    target_idx = 1 if r_idx == 0 else 0
    assert all(math.isclose(res[target_idx][j], exp_other[j], abs_tol=1e-9) for j in range(len(exp_other)))

General solution:

General tests: