Extract a "simple" Kronecker delta containing `idx` from `expr`.

    Assuming `expr` can be written as the product of a Kronecker Delta and a
    `new_expr`, return a tuple of the sympy.KroneckerDelta instance and
    `new_expr`. Otherwise, return a tuple of None and the original `expr`
    (possibly converted to a :class:`.QuantumExpression`).

    On input, `expr` can be a :class:`QuantumExpression` or a
    :class:`sympy.Basic` object. On output, `new_expr` is guaranteed to be a
    :class:`QuantumExpression`.

def _extract_delta(expr, idx):
    """Extract a "simple" Kronecker delta containing `idx` from `expr`.

    Assuming `expr` can be written as the product of a Kronecker Delta and a
    `new_expr`, return a tuple of the sympy.KroneckerDelta instance and
    `new_expr`. Otherwise, return a tuple of None and the original `expr`
    (possibly converted to a :class:`.QuantumExpression`).

    On input, `expr` can be a :class:`QuantumExpression` or a
    :class:`sympy.Basic` object. On output, `new_expr` is guaranteed to be a
    :class:`QuantumExpression`.
    """
    from qnet.algebra.core.abstract_quantum_algebra import QuantumExpression
    from qnet.algebra.core.scalar_algebra import ScalarValue
    sympy_factor, quantum_factor = _split_sympy_quantum_factor(expr)
    delta, new_expr = _sympy_extract_delta(sympy_factor, idx)
    if delta is None:
        new_expr = expr
    else:
        new_expr = new_expr * quantum_factor
    if isinstance(new_expr, ScalarValue._val_types):
        new_expr = ScalarValue.create(new_expr)
    assert isinstance(new_expr, QuantumExpression)
    return delta, new_expr