def _strat_unitary_from_apply_unitary(val: Any) -> np.ndarray | None:
    """Attempts to compute a value's unitary via its _apply_unitary_ method."""
    # Check for the magic method.
    method = getattr(val, '_apply_unitary_', None)
    if method is None:
        return NotImplemented

    # Get the qid_shape.
    val_qid_shape = qid_shape_protocol.qid_shape(val, None)
    if val_qid_shape is None:
        return NotImplemented

    # Apply unitary effect to an identity matrix.
    result = method(ApplyUnitaryArgs.for_unitary(qid_shape=val_qid_shape))

    if result is NotImplemented or result is None:
        return result
    state_len = np.prod(val_qid_shape, dtype=np.int64)
    return result.reshape((state_len, state_len))
Attempts to compute a value's unitary via its _apply_unitary_ method.
cirq-core/cirq/protocols/unitary_protocol.py