import cmath
import math

def validate_square(matrix):
    if not matrix or any(len(row) != len(matrix) for row in matrix):
        raise ValueError("unitary candidate must be a nonempty square matrix")

def adjoint(matrix):
    validate_square(matrix)
    return tuple(tuple(matrix[column][row].conjugate() for column in range(len(matrix)))
                 for row in range(len(matrix)))

def matmul(left, right):
    validate_square(left)
    validate_square(right)
    if len(left) != len(right):
        raise ValueError("matrix dimensions must agree")
    size = len(left)
    return tuple(tuple(sum(left[row][k] * right[k][column] for k in range(size))
                       for column in range(size)) for row in range(size))

def unitary_deviation(matrix):
    product = matmul(adjoint(matrix), matrix)
    return max(abs(product[row][column] - (1 if row == column else 0))
               for row in range(len(matrix)) for column in range(len(matrix)))

def matvec(matrix, vector):
    validate_square(matrix)
    if len(matrix) != len(vector):
        raise ValueError("state dimension mismatch")
    return tuple(sum(matrix[row][column] * vector[column] for column in range(len(vector)))
                 for row in range(len(vector)))

scale = math.sqrt(0.5)
H = ((scale, scale), (scale, -scale))
X = ((0, 1), (1, 0))
S = ((1, 0), (0, 1j))
CNOT = ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0))
phase_gates = tuple(((1, 0), (0, cmath.exp(1j * theta)))
                    for theta in (0.0, 0.2, -1.7, math.pi))
good_gates = (H, X, S, CNOT, *phase_gates)
deviations = [unitary_deviation(gate) for gate in good_gates]
assert max(deviations) < 1e-12

states = ((0.6, 0.8), (scale, 1j * scale), (1, 0))
for gate in (H, X, S, *phase_gates):
    for state in states:
        before = sum(abs(value) ** 2 for value in state)
        after = sum(abs(value) ** 2 for value in matvec(gate, state))
        assert abs(before - after) < 1e-12

bad_gates = (((1, 0), (0, 0)), ((2, 0), (0, 0.5)), ((1, 1), (0, 1)))
bad_deviations = [unitary_deviation(gate) for gate in bad_gates]
assert min(bad_deviations) > 0.5
near = ((1, 0), (0, 1 + 5e-10))
near_deviation = unitary_deviation(near)
assert near_deviation < 1e-8 and near_deviation > 1e-12
ragged_rejected = False
try:
    unitary_deviation(((1, 0), (0,)))
except ValueError:
    ragged_rejected = True
assert ragged_rejected
print(f"PASS: 12 unitary validator accepts {len(good_gates)} gates with max deviation={max(deviations):.2e}, rejects {len(bad_gates)} matrices with min deviation={min(bad_deviations):.2f}, tolerance boundary={near_deviation:.2e}")
