def _strat_unitary_from_decompose(val: Any) -> np.ndarray | None:
    """Attempts to compute a value's unitary via its _decompose_ method."""
    # Check if there's a decomposition.
    operations, qubits, val_qid_shape = _try_decompose_into_operations_and_qubits(val)
    if operations is None:
        return NotImplemented

    all_qubits = frozenset(q for op in operations for q in op.qubits)
    work_qubits = frozenset(qubits)
    ancillas = tuple(sorted(all_qubits.difference(work_qubits)))

    ordered_qubits = ancillas + tuple(qubits)
    val_qid_shape = qid_shape_protocol.qid_shape(ancillas) + val_qid_shape

    # Apply sub-operations' unitary effects to an identity matrix.
    result = apply_unitaries(
        operations, ordered_qubits, ApplyUnitaryArgs.for_unitary(qid_shape=val_qid_shape), None
    )

    # Package result.
    if result is None:
        return None

    state_len = np.prod(val_qid_shape, dtype=np.int64)
    result = result.reshape((state_len, state_len))
    # Assuming borrowable qubits are restored to their original state and
    # clean qubits restord to the zero state then the desired unitary is
    # the upper left square.
    work_state_len = np.prod(val_qid_shape[len(ancillas) :], dtype=np.int64)
    return result[:work_state_len, :work_state_len]
Attempts to compute a value's unitary via its _decompose_ method.
cirq-core/cirq/protocols/unitary_protocol.py