diff --git a/.github/CHANGELOG.md b/.github/CHANGELOG.md index 851f9025a..10773ae50 100644 --- a/.github/CHANGELOG.md +++ b/.github/CHANGELOG.md @@ -53,6 +53,8 @@ which uses the old Numba code. When setting to a higher value, the new Julia cod [(#303)](https://github.com/XanaduAI/MrMustard/pull/303) [(#304)](https://github.com/XanaduAI/MrMustard/pull/304) +* Changed the ``cast`` functions in the numpy and tensorflow backends to avoid ``ComplexWarning``s. + ### Bug fixes * Added the missing `shape` input parameters to all methods `U` in the `gates.py` file. diff --git a/mrmustard/math/backend_numpy.py b/mrmustard/math/backend_numpy.py index cabf9e245..36452835d 100644 --- a/mrmustard/math/backend_numpy.py +++ b/mrmustard/math/backend_numpy.py @@ -43,8 +43,8 @@ class BackendNumpy(BackendBase): # pragma: no cover """ int32 = np.int32 - float64 = np.float64 float32 = np.float32 + float64 = np.float64 complex64 = np.complex64 complex128 = np.complex128 @@ -90,6 +90,8 @@ def cast(self, array: np.array, dtype=None) -> np.array: if dtype is None: return array + if dtype not in [self.complex64, self.complex128, "complex64", "complex128"]: + array = self.real(array) return np.array(array, dtype=dtype) def clip(self, array, a_min, a_max) -> np.array: diff --git a/mrmustard/math/backend_tensorflow.py b/mrmustard/math/backend_tensorflow.py index 8930bf46a..8534717c6 100644 --- a/mrmustard/math/backend_tensorflow.py +++ b/mrmustard/math/backend_tensorflow.py @@ -42,8 +42,8 @@ class BackendTensorflow(BackendBase): # pragma: no cover """ int32 = tf.int32 - float64 = tf.float64 float32 = tf.float32 + float64 = tf.float64 complex64 = tf.complex64 complex128 = tf.complex128 @@ -87,6 +87,9 @@ def boolean_mask(self, tensor: tf.Tensor, mask: tf.Tensor) -> Tensor: def cast(self, array: tf.Tensor, dtype=None) -> tf.Tensor: if dtype is None: return array + + if dtype not in [self.complex64, self.complex128, "complex64", "complex128"]: + array = self.real(array) return tf.cast(array, dtype) def clip(self, array, a_min, a_max) -> tf.Tensor: @@ -467,7 +470,9 @@ def reorder_AB_bargmann(self, A: tf.Tensor, B: tf.Tensor) -> Tuple[tf.Tensor, tf r"""In mrmustard.math.compactFock.compactFock~ dimensions of the Fock representation are ordered like [mode0,mode0,mode1,mode1,...] while in mrmustard.physics.bargmann the ordering is [mode0,mode1,...,mode0,mode1,...]. Here we reorder A and B. """ - ordering = np.arange(2 * A.shape[0] // 2).reshape(2, -1).T.flatten() + ordering = ( + np.arange(2 * A.shape[0] // 2).reshape(2, -1).T.flatten() + ) # ordering is [0,2,4,...,1,3,5,...] A = tf.gather(A, ordering, axis=1) A = tf.gather(A, ordering) B = tf.gather(B, ordering)