Python tensorflow.complex() Examples

The following are 30 code examples of tensorflow.complex(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tensorflow , or try the search function .
Example #1
Source File: models.py    From DeepLearningImplementations with MIT License 6 votes vote down vote up
def compute_fft(x, direction="C2C", inverse=False):

    if direction == 'C2R':
        inverse = True

    x_shape = x.get_shape().as_list()
    h, w = x_shape[-2], x_shape[-3]

    x_complex = tf.complex(x[..., 0], x[..., 1])

    if direction == 'C2R':
        out = tf.real(tf.ifft2d(x_complex)) * h * w
        return out

    else:
        if inverse:
            out = stack_real_imag(tf.ifft2d(x_complex)) * h * w
        else:
            out = stack_real_imag(tf.fft2d(x_complex))
        return out 
Example #2
Source File: tfmri_test.py    From dl-cs with MIT License 6 votes vote down vote up
def test_fftc(self):
        shape = [10, 10, 2]
        data = tf.complex(
            tf.random_uniform(shape), tf.random_uniform(shape))
        fdata = tfmri.fftc(data)
        fdata_np = self._fftnc(data, axes=(-2,))
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)

        fdata = tfmri.fftc(data, data_format='channels_first')
        fdata_np = self._fftnc(data, axes=(-1,))
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)

        fdata = tfmri.fftc(data, orthonorm=False)
        fdata_np = self._fftnc(data, axes=(-2,), norm=None)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps) 
Example #3
Source File: fft_ops_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def _checkGrad(self, func, x, y, use_gpu=False):
    with self.test_session(use_gpu=use_gpu):
      inx = tf.convert_to_tensor(x)
      iny = tf.convert_to_tensor(y)
      # func is a forward or inverse FFT function (batched or unbatched)
      z = func(tf.complex(inx, iny))
      # loss = sum(|z|^2)
      loss = tf.reduce_sum(tf.real(z * tf.conj(z)))
      ((x_jacob_t, x_jacob_n),
       (y_jacob_t, y_jacob_n)) = tf.test.compute_gradient(
           [inx, iny],
           [list(x.shape), list(y.shape)],
           loss,
           [1],
           x_init_value=[x, y],
           delta=1e-2)
    self.assertAllClose(x_jacob_t, x_jacob_n, rtol=1e-2, atol=1e-2)
    self.assertAllClose(y_jacob_t, y_jacob_n, rtol=1e-2, atol=1e-2) 
Example #4
Source File: tfmri_test.py    From dl-cs with MIT License 6 votes vote down vote up
def test_ifftc(self):
        shape = [10, 10, 2]
        data = tf.complex(
            tf.random_uniform(shape), tf.random_uniform(shape))
        fdata_np = self._fftnc(data, axes=(-2,), transpose=True)
        fdata = tfmri.ifftc(data)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)
        fdata = tfmri.fftc(data, transpose=True)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)

        fdata = tfmri.ifftc(data, data_format='channels_first')
        fdata_np = self._fftnc(data, axes=(-1,), transpose=True)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)

        fdata = tfmri.ifftc(data, orthonorm=False)
        fdata_np = self._fftnc(data, axes=(-2,), norm=None, transpose=True)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps) 
Example #5
Source File: tfmri_test.py    From dl-cs with MIT License 6 votes vote down vote up
def test_fft2c(self):
        shape = [10, 10, 2]
        data = tf.complex(
            tf.random_uniform(shape), tf.random_uniform(shape))
        fdata = tfmri.fft2c(data)
        fdata_np = self._fftnc(data, axes=(-3, -2))
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)

        fdata = tfmri.fft2c(data, data_format='channels_first')
        fdata_np = self._fftnc(data, axes=(-2, -1))
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)

        fdata = tfmri.fft2c(data, orthonorm=False)
        fdata_np = self._fftnc(data, axes=(-3, -2), norm=None)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps) 
Example #6
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def _compareGradient(self, x):
    # x[:, 0] is real, x[:, 1] is imag.  We combine real and imag into
    # complex numbers. Then, we extract real and imag parts and
    # computes the squared sum. This is obviously the same as sum(real
    # * real) + sum(imag * imag). We just want to make sure the
    # gradient function is checked.
    with self.test_session():
      inx = tf.convert_to_tensor(x)
      real, imag = tf.split(1, 2, inx)
      real, imag = tf.reshape(real, [-1]), tf.reshape(imag, [-1])
      cplx = tf.complex(real, imag)
      cplx = tf.conj(cplx)
      loss = tf.reduce_sum(
          tf.square(tf.real(cplx))) + tf.reduce_sum(
              tf.square(tf.imag(cplx)))
      epsilon = 1e-3
      jacob_t, jacob_n = tf.test.compute_gradient(inx,
                                                  list(x.shape),
                                                  loss,
                                                  [1],
                                                  x_init_value=x,
                                                  delta=epsilon)
    self.assertAllClose(jacob_t, jacob_n, rtol=epsilon, atol=epsilon) 
Example #7
Source File: tfmri_test.py    From dl-cs with MIT License 6 votes vote down vote up
def test_ifft2c(self):
        shape = [10, 10, 2]
        data = tf.complex(
            tf.random_uniform(shape), tf.random_uniform(shape))
        fdata_np = self._fftnc(data, axes=(-3, -2), transpose=True)
        fdata = tfmri.ifft2c(data)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)
        fdata = tfmri.fft2c(data, transpose=True)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)

        fdata = tfmri.ifft2c(data, data_format='channels_first')
        fdata_np = self._fftnc(data, axes=(-2, -1), transpose=True)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps)

        fdata = tfmri.ifft2c(data, orthonorm=False)
        fdata_np = self._fftnc(data, axes=(-3, -2), norm=None, transpose=True)
        diff = np.mean(np.abs(fdata_np - fdata) ** 2)
        self.assertTrue(diff < eps) 
Example #8
Source File: cwise_ops_test.py    From deep_image_model with Apache License 2.0 6 votes vote down vote up
def _testBCastByFunc(self, funcs, xs, ys):
    dtypes = [
        np.float16,
        np.float32,
        np.float64,
        np.int32,
        np.int64,
        np.complex64,
        np.complex128,
    ]
    for dtype in dtypes:
      for (np_func, tf_func) in funcs:
        if (dtype in (np.complex64, np.complex128) and
              tf_func in (_FLOORDIV, tf.floordiv)):
          continue  # floordiv makes no sense for complex numbers
        self._compareBCast(xs, ys, dtype, np_func, tf_func)
        self._compareBCast(ys, xs, dtype, np_func, tf_func) 
Example #9
Source File: tfmri.py    From dl-cs with MIT License 6 votes vote down vote up
def channels_to_complex(image,
                        data_format='channels_last',
                        name='channels2complex'):
    """Convert data from channels to complex."""
    if len(image.shape) != 3 and len(image.shape) != 4:
        raise TypeError('Input data must be have 3 or 4 dimensions')

    axis_c = -1 if data_format == 'channels_last' else -3
    shape_c = image.shape[axis_c].value

    if shape_c and (shape_c % 2 != 0):
        raise TypeError(
            'Number of channels (%d) must be divisible by 2' % shape_c)
    if image.dtype is tf.complex64 or image.dtype is tf.complex128:
        raise TypeError('Input data cannot be complex')

    with tf.name_scope(name):
        image_real, image_imag = tf.split(image, 2, axis=axis_c)
        image_out = tf.complex(image_real, image_imag)
    return image_out 
Example #10
Source File: tf_image.py    From burst-denoising with Apache License 2.0 6 votes vote down vote up
def hdrplus_merge(imgs, N, c, sig):
    ccast_tf = lambda x : tf.complex(x, tf.zeros_like(x))

    # imgs is [batch, h, w, ch]
    rcw = tf.expand_dims(rcwindow(N), axis=-1)
    imgs = imgs * rcw
    imgs = tf.transpose(imgs, [0, 3, 1, 2])
    imgs_f = tf.fft2d(ccast_tf(imgs))
    imgs_f = tf.transpose(imgs_f, [0, 2, 3, 1])
    Dz2 = tf.square(tf.abs(imgs_f[...,0:1] - imgs_f))
    Az = Dz2 / (Dz2 + c*sig**2)
    filt0 = 1 + tf.expand_dims(tf.reduce_sum(Az[...,1:], axis=-1), axis=-1)
    filts = tf.concat([filt0, 1 - Az[...,1:]], axis=-1)
    output_f = tf.reduce_mean(imgs_f * ccast_tf(filts), axis=-1)
    output_f = tf.real(tf.ifft2d(output_f))

    return output_f 
Example #11
Source File: train_specgan.py    From wavegan with MIT License 6 votes vote down vote up
def invert_spectra_griffin_lim(X_mag, nfft, nhop, ngl):
    X = tf.complex(X_mag, tf.zeros_like(X_mag))

    def b(i, X_best):
        x = tf.contrib.signal.inverse_stft(X_best, nfft, nhop)
        X_est = tf.contrib.signal.stft(x, nfft, nhop)
        phase = X_est / tf.cast(tf.maximum(1e-8, tf.abs(X_est)), tf.complex64)
        X_best = X * phase
        return i + 1, X_best

    i = tf.constant(0)
    c = lambda i, _: tf.less(i, ngl)
    _, X = tf.while_loop(c, b, [i, X], back_prop=False)

    x = tf.contrib.signal.inverse_stft(X, nfft, nhop)
    x = x[:, :_SLICE_LEN]

    return x 
Example #12
Source File: tensorflow_backend.py    From kymatio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def complex_modulus(x):
    """Computes complex modulus.

        Parameters
        ----------
        x : tensor
            Input tensor whose complex modulus is to be calculated.

        Returns
        -------
        modulus : tensor
            Tensor the same size as input_array. modulus holds the
            result of the complex modulus.

    """
    modulus = tf.abs(x)
    return modulus 
Example #13
Source File: layers.py    From neuron with GNU General Public License v3.0 6 votes vote down vote up
def call(self, inputx):
        
        if not inputx.dtype in [tf.complex64, tf.complex128]:
            print('Warning: inputx is not complex. Converting.', file=sys.stderr)
        
            # if inputx is float, this will assume 0 imag channel
            inputx = tf.cast(inputx, tf.complex64)
        
        # get the right fft
        if self.ndims == 1:
            ifft = tf.ifft
        elif self.ndims == 2:
            ifft = tf.ifft2d
        else:
            ifft = tf.ifft3d

        perm_dims = [0, self.ndims + 1] + list(range(1, self.ndims + 1))
        invert_perm_ndims = [0] + list(range(2, self.ndims + 2)) + [1]
        
        perm_inputx = K.permute_dimensions(inputx, perm_dims)  # [batch_size, nb_features, *vol_size]
        ifft_inputx = ifft(perm_inputx)
        return K.permute_dimensions(ifft_inputx, invert_perm_ndims) 
Example #14
Source File: layers.py    From neuron with GNU General Public License v3.0 6 votes vote down vote up
def call(self, inputx):
        
        if not inputx.dtype in [tf.complex64, tf.complex128]:
            print('Warning: inputx is not complex. Converting.', file=sys.stderr)
        
            # if inputx is float, this will assume 0 imag channel
            inputx = tf.cast(inputx, tf.complex64)

        # get the right fft
        if self.ndims == 1:
            fft = tf.fft
        elif self.ndims == 2:
            fft = tf.fft2d
        else:
            fft = tf.fft3d

        perm_dims = [0, self.ndims + 1] + list(range(1, self.ndims + 1))
        invert_perm_ndims = [0] + list(range(2, self.ndims + 2)) + [1]
        
        perm_inputx = K.permute_dimensions(inputx, perm_dims)  # [batch_size, nb_features, *vol_size]
        fft_inputx = fft(perm_inputx)
        return K.permute_dimensions(fft_inputx, invert_perm_ndims) 
Example #15
Source File: scattering.py    From DeepLearningImplementations with MIT License 6 votes vote down vote up
def compute_fft(x, direction="C2C", inverse=False):

    if direction == 'C2R':
        inverse = True

    x_shape = x.get_shape().as_list()
    h, w = x_shape[-2], x_shape[-3]

    x_complex = tf.complex(x[..., 0], x[..., 1])

    if direction == 'C2R':
        out = tf.real(tf.ifft2d(x_complex)) * h * w
        return out

    else:
        if inverse:
            out = stack_real_imag(tf.ifft2d(x_complex)) * h * w
        else:
            out = stack_real_imag(tf.fft2d(x_complex))
        return out 
Example #16
Source File: tfmri.py    From dl-cs with MIT License 5 votes vote down vote up
def complex_to_channels(image,
                        data_format='channels_last',
                        name='complex2channels'):
    """Convert data from complex to channels."""
    if len(image.shape) != 3 and len(image.shape) != 4:
        raise TypeError('Input data must be have 3 or 4 dimensions')

    axis_c = -1 if data_format == 'channels_last' else -3

    if image.dtype is not tf.complex64 and image.dtype is not tf.complex128:
        raise TypeError('Input data must be complex')

    with tf.name_scope(name):
        image_out = tf.concat((tf.real(image), tf.imag(image)), axis_c)
    return image_out 
Example #17
Source File: train_mri_vn.py    From mri-variationalnetwork with MIT License 5 votes vote down vote up
def mriAdjointOp(self, f, coil_sens, sampling_mask):
        with tf.variable_scope('mriAdjointOp'):
            # apply mask and perform inverse centered Fourier transform
            mask = tf.expand_dims(sampling_mask, axis=1)
            Finv = tf.contrib.icg.ifftc2d(tf.complex(tf.real(f) * mask, tf.imag(f) * mask))
            # multiply coil images with sensitivities and sum up over channels
            img = tf.reduce_sum(Finv * tf.conj(coil_sens), 1)
        return img 
Example #18
Source File: tfmri_test.py    From dl-cs with MIT License 5 votes vote down vote up
def test_complex_to_channels(self):
        data_r = tf.random_uniform([3, 10, 10, 2])
        data_i = tf.random_uniform([3, 10, 10, 2])
        data = tf.complex(data_r, data_i)
        data_out = tfmri.complex_to_channels(data)
        diff_r = data_r - tf.real(data)
        diff_i = data_i - tf.imag(data)
        diff = np.mean(diff_r ** 2 + diff_i ** 2)
        self.assertTrue(diff < eps)
        self.assertEqual(data_out.shape[-1], 4)

        data_out = tfmri.complex_to_channels(
            data, data_format='channels_first')
        diff_r = data_r - tf.real(data)
        diff_i = data_i - tf.imag(data)
        diff = np.mean(diff_r ** 2 + diff_i ** 2)
        self.assertTrue(diff < eps)
        self.assertEqual(data_out.shape[1], 20)

        with self.assertRaises(TypeError):
            # Input must be complex
            data_out = tfmri.complex_to_channels(data_r)
        with self.assertRaises(TypeError):
            # shape error
            data_r = tf.random_uniform([1, 3, 10, 10, 2])
            data_i = tf.random_uniform([1, 3, 10, 10, 2])
            data = tf.complex(data_r, data_i)
            data_out = tfmri.complex_to_channels(data)
        with self.assertRaises(TypeError):
            # shape error
            data_r = tf.random_uniform([10, 2])
            data_i = tf.random_uniform([10, 2])
            data = tf.complex(data_r, data_i)
            data_out = tfmri.complex_to_channels(data) 
Example #19
Source File: train_mri_vn.py    From mri-variationalnetwork with MIT License 5 votes vote down vote up
def mriForwardOpWithOS(self, u, coil_sens, sampling_mask):
        with tf.variable_scope('mriForwardOp'):
            # add frequency encoding oversampling
            pad_u = tf.cast(tf.multiply(tf.cast(tf.shape(sampling_mask)[1], tf.float32), 0.25) + 1, tf.int32)
            pad_l = tf.cast(tf.multiply(tf.cast(tf.shape(sampling_mask)[1], tf.float32), 0.25) - 1, tf.int32)
            u_pad = tf.pad(u, [[0, 0], [pad_u, pad_l], [0, 0]])
            u_pad = tf.expand_dims(u_pad, axis=1)
            # apply sensitivites
            coil_imgs = u_pad * coil_sens
            # centered Fourier transform
            Fu = tf.contrib.icg.fftc2d(coil_imgs)
            # apply sampling mask
            mask = tf.expand_dims(sampling_mask, axis=1)
            kspace = tf.complex(tf.real(Fu) * mask, tf.imag(Fu) * mask)
        return kspace 
Example #20
Source File: generic.py    From neurophox with MIT License 5 votes vote down vote up
def transform(self, inputs: tf.Tensor) -> tf.Tensor:
        """
        Performs the operation (where :math:`U` represents the matrix for this layer):

        .. math::
            V_{\mathrm{out}} = V_{\mathrm{in}} U,

        where :math:`U \in \mathrm{U}(N)` and :math:`V_{\mathrm{out}}, V_{\mathrm{in}} \in \mathbb{C}^{M \\times N}`.

        Args:
            inputs: :code:`inputs` batch represented by the matrix :math:`V_{\mathrm{in}} \in \mathbb{C}^{M \\times N}`

        Returns:
            Transformed :code:`inputs`, :math:`V_{\mathrm{out}}`
        """
        _inputs = np.eye(self.units, dtype=np.complex64) if self.incoherent else inputs
        mesh_phases, mesh_layers = self.phases_and_layers
        outputs = _inputs * mesh_phases.input_phase_shift_layer if self.include_diagonal_phases else _inputs
        for layer in range(self.num_layers):
            outputs = mesh_layers[layer].transform(outputs)
        if self.incoherent:
            power_matrix = tf.math.real(outputs) ** 2 + tf.math.imag(outputs) ** 2
            power_inputs = tf.math.real(inputs) ** 2 + tf.math.imag(inputs) ** 2
            outputs = power_inputs @ power_matrix
            return tf.complex(tf.sqrt(outputs), tf.zeros_like(outputs))
        return outputs 
Example #21
Source File: generic.py    From neurophox with MIT License 5 votes vote down vote up
def external_phase_shift_layers(self):
        """Elementwise applying complex exponential to :code:`external_phase_shifts`.

        Returns:
            External phase shift layers corresponding to :math:`\\boldsymbol{\\phi}`
        """
        external_ps = self.external_phase_shifts
        return tf.complex(tf.cos(external_ps), tf.sin(external_ps)) 
Example #22
Source File: generic.py    From neurophox with MIT License 5 votes vote down vote up
def internal_phase_shift_layers(self):
        """Elementwise applying complex exponential to :code:`internal_phase_shifts`.

        Returns:
            Internal phase shift layers corresponding to :math:`\\boldsymbol{\\theta}`
        """
        internal_ps = self.internal_phase_shifts
        return tf.complex(tf.cos(internal_ps), tf.sin(internal_ps)) 
Example #23
Source File: generic.py    From neurophox with MIT License 5 votes vote down vote up
def __init__(self, theta: tf.Variable, phi: tf.Variable, mask: np.ndarray, gamma: tf.Variable, units: int,
                 basis: str = SINGLEMODE, hadamard: bool = False):
        self.mask = mask if mask is not None else np.ones_like(theta)
        self.theta = MeshParamTensorflow(theta * mask + (1 - mask) * (1 - hadamard) * np.pi, units=units)
        self.phi = MeshParamTensorflow(phi * mask + (1 - mask) * (1 - hadamard) * np.pi, units=units)
        self.gamma = gamma
        self.basis = basis
        self.input_phase_shift_layer = tf.complex(tf.cos(gamma), tf.sin(gamma))
        if self.theta.param.shape != self.phi.param.shape:
            raise ValueError("Internal phases (theta) and external phases (phi) need to have the same shape.") 
Example #24
Source File: layers.py    From neurophox with MIT License 5 votes vote down vote up
def __init__(self, units: int, **kwargs):
        super(DiagonalPhaseLayer, self).__init__(units=units)
        self.gamma = tf.Variable(
            name="gamma",
            initial_value=tf.constant(2 * np.pi * np.random.rand(units), dtype=TF_FLOAT),
            dtype=TF_FLOAT,
            **kwargs
        )
        self.diag_vec = tf.complex(tf.cos(self.gamma), tf.sin(self.gamma))
        self.inv_diag_vec = tf.complex(tf.cos(-self.gamma), tf.sin(-self.gamma))
        self.variables.append(self.gamma) 
Example #25
Source File: helper.py    From claude with MIT License 5 votes vote down vote up
def gaussianLLR( constellation, constellation_bits, Y, SNR_lin, M ):
    """
        Computes log likelihood ratio with Gaussian auxiliary channel assumption
        
        constellation: (1, M), where M is the constellation order
        constellation_bits: (m, M), where m=log2(M) the number of bits per symbol and M is the constellation order
        Y: (1, N), N normalized complex observations at the receiver, where N is the batchSize/sampleSize
        SNR_lin: SNR (linear) of Gaussian auxiliary channel
        M: Constellation order
    """
    
    M = int(M) # Order of constellations
    m = int(np.log2(M)) # Number of bits per symbol

    expAbs = lambda x,y,SNR_lin: tf.exp( -SNR_lin * tf.square( tf.abs( y - x ) ) )

    constellation_zero = tf.stack( [tf.boolean_mask( constellation, item ) for item in tf.split( tf.equal( constellation_bits, 0 ), num_or_size_splits=m, axis=0 )], axis=1 )
    constellation_zero.set_shape((int(M/2),m))
    constellation_one = tf.stack( [tf.boolean_mask( constellation, item ) for item in tf.split( tf.equal( constellation_bits, 1 ), num_or_size_splits=m, axis=0 )], axis=1 )
    constellation_one.set_shape((int(M/2),m))

    constellation_zero_flat = tf.reshape(constellation_zero,[-1])
    constellation_one_flat = tf.reshape(constellation_one,[-1])

    sum_zeros = tf.reduce_sum( tf.reshape( expAbs( tf.expand_dims(constellation_zero_flat, axis=1), Y, SNR_lin ), [int(M/2),m,-1] ), axis=0 )
    sum_ones = tf.reduce_sum( tf.reshape( expAbs( tf.expand_dims(constellation_one_flat, axis=1), Y, SNR_lin ), [int(M/2),m,-1] ), axis=0 )

    LLRs = tf.math.log( sum_zeros / sum_ones )

    return LLRs 
Example #26
Source File: model.py    From DeepMRI with GNU General Public License v3.0 5 votes vote down vote up
def real2complex(x):
    channel = x.shape[-1] // 2
    if x.shape.ndims == 3:
        return tf.complex(x[:,:,:channel], x[:,:,channel:])
    elif x.shape.ndims == 4:
        return tf.complex(x[:,:,:,:channel], x[:,:,:,channel:]) 
Example #27
Source File: wavefunctions_test.py    From TensorNetwork with Apache License 2.0 5 votes vote down vote up
def test_evolve_trotter(num_sites, phys_dim, graph):
  tf.random.set_seed(10)
  psi = tf.complex(
      tf.random.normal([phys_dim] * num_sites, dtype=tf.float64),
      tf.random.normal([phys_dim] * num_sites, dtype=tf.float64))
  h = tf.complex(
      tf.random.normal((phys_dim**2, phys_dim**2), dtype=tf.float64),
      tf.random.normal((phys_dim**2, phys_dim**2), dtype=tf.float64))
  h = 0.5 * (h + tf.linalg.adjoint(h))
  h = tf.reshape(h, (phys_dim, phys_dim, phys_dim, phys_dim))
  H = [h] * (num_sites - 1)

  norm1 = wavefunctions.inner(psi, psi)
  en1 = sum(wavefunctions.expval(psi, H[i], i) for i in range(num_sites - 1))

  if graph:
    psi, t = wavefunctions.evolve_trotter_defun(psi, H, 0.001, 10)
  else:
    psi, t = wavefunctions.evolve_trotter(psi, H, 0.001, 10)

  norm2 = wavefunctions.inner(psi, psi)
  en2 = sum(wavefunctions.expval(psi, H[i], i) for i in range(num_sites - 1))

  np.testing.assert_allclose(t, 0.01)
  np.testing.assert_almost_equal(norm1 / norm2, 1.0)
  np.testing.assert_almost_equal(en1 / en2, 1.0, decimal=2) 
Example #28
Source File: wavefunctions_test.py    From TensorNetwork with Apache License 2.0 5 votes vote down vote up
def test_evolve_trotter_euclidean(num_sites, phys_dim, graph):
  tf.random.set_seed(10)
  psi = tf.complex(
      tf.random.normal([phys_dim] * num_sites, dtype=tf.float64),
      tf.random.normal([phys_dim] * num_sites, dtype=tf.float64))
  h = tf.complex(
      tf.random.normal((phys_dim**2, phys_dim**2), dtype=tf.float64),
      tf.random.normal((phys_dim**2, phys_dim**2), dtype=tf.float64))
  h = 0.5 * (h + tf.linalg.adjoint(h))
  h = tf.reshape(h, (phys_dim, phys_dim, phys_dim, phys_dim))
  H = [h] * (num_sites - 1)

  norm1 = wavefunctions.inner(psi, psi)
  en1 = sum(wavefunctions.expval(psi, H[i], i) for i in range(num_sites - 1))

  if graph:
    psi, t = wavefunctions.evolve_trotter_defun(psi, H, 0.1, 10, euclidean=True)
  else:
    psi, t = wavefunctions.evolve_trotter(psi, H, 0.1, 10, euclidean=True)

  norm2 = wavefunctions.inner(psi, psi)
  en2 = sum(wavefunctions.expval(psi, H[i], i) for i in range(num_sites - 1))

  np.testing.assert_allclose(t, 1.0)
  np.testing.assert_almost_equal(norm2, 1.0)
  assert en2.numpy() / norm2.numpy() < en1.numpy() / norm1.numpy() 
Example #29
Source File: utils.py    From joie-kdd19 with MIT License 5 votes vote down vote up
def circular_correlation(h, t):
    return tf.real(tf.spectral.ifft(tf.multiply(tf.conj(tf.spectral.fft(tf.complex(h, 0.))), tf.spectral.fft(tf.complex(t, 0.))))) 
Example #30
Source File: tensorflow_backend.py    From kymatio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cdgmm3d(A, B, inplace=False):
    """Complex pointwise multiplication.

        Complex pointwise multiplication between (batched) tensor A and tensor B.

        Parameters
        ----------
        A : tensor
            Complex tensor.
        B : tensor
            Complex tensor of the same size as A.
        inplace : boolean, optional
            If set True, all the operations are performed inplace.

        Returns
        -------
        output : tensor
            Tensor of the same size as A containing the result of the elementwise
            complex multiplication of A with B.

    """
    if B.ndim != 3:
        raise RuntimeError('The dimension of the second input must be 3.')

    Cr = tf.cast(tf.math.real(A) * np.real(B) - tf.math.imag(A) * np.imag(B), tf.complex64)
    Ci = tf.cast(tf.math.real(A) * np.imag(B) + tf.math.imag(A) * np.real(B), tf.complex64)

    return Cr + 1.0j * Ci