numpy.complex64

Here are the examples of the python api numpy.complex64 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

103 Examples 7

Example 1

Project: f2py Source File: test_py_support.py
    def check_numpy_scalar_argument_return_complex(self):
        f = PyCFunction('foo')
        f += Variable('a1', numpy.complex64, 'in, out')
        f += Variable('a2', numpy.complex128, 'in, out')
        f += Variable('a3', numpy.complex256, 'in, out')
        foo = f.build()
        args = 1+2j,1+2j,1+2j
        results = (numpy.complex64(1+2j),numpy.complex128(1+2j),numpy.complex256(1+2j))
        assert_equal(foo(*args),results)

        f = PyCFunction('foo')
        f += Variable('a1', 'npy_complex64', 'in, out')
        f += Variable('a2', 'npy_complex128', 'in, out')
        f += Variable('a3', 'npy_complex256', 'in, out')

        foo = f.build()
        args = (1+2j, 1+2j, 1+2j)
        results = (numpy.complex64(1+2j),numpy.complex128(1+2j),numpy.complex256(1+2j))
        assert_equal(foo(*args),results)

Example 2

Project: deep_recommend_system Source File: tensor_util_test.py
  def testComplex64N(self):
    t = tensor_util.make_tensor_proto([(1+2j), (3+4j), (5+6j)], shape=[1, 3],
                                      dtype=tf.complex64)
    self.assertProtoEquals("""
      dtype: DT_COMPLEX64
      tensor_shape { dim { size: 1 } dim { size: 3 } }
      scomplex_val: 1
      scomplex_val: 2
      scomplex_val: 3
      scomplex_val: 4
      scomplex_val: 5
      scomplex_val: 6
      """, t)
    a = tensor_util.MakeNdarray(t)
    self.assertEquals(np.complex64, a.dtype)
    self.assertAllEqual(np.array([[(1+2j), (3+4j), (5+6j)]]), a)

Example 3

Project: reikna Source File: test_dht.py
@pytest.mark.parametrize('fo_shape', fo_shape_vals, ids=list(map(str, fo_shape_vals)))
@pytest.mark.parametrize('fo_batch', [1, 10])
@pytest.mark.parametrize('fo_add_points', ['0', '1', '1,2,...'])
def test_first_order_errors(thr, fo_shape, fo_batch, fo_add_points):
    """
    Checks that after the transformation of the manually constructed function in coordinate space
    we get exactly mode numbers used for its construction.
    Also checks that inverse transform returns the initial array.
    """

    if fo_add_points == '0':
        add_points = None
    elif fo_add_points == '1':
        add_points = [1] * len(fo_shape)
    else:
        add_points = list(range(1, len(fo_shape) + 1))

    check_errors_first_order(thr, fo_shape, fo_batch,
        add_points=add_points, dtype=numpy.complex64)

Example 4

Project: numba Source File: test_conversion.py
    def test_complex_identity(self):
        pyfunc = identity
        cres = compile_isolated(pyfunc, [types.complex64],
                                return_type=types.complex64)

        xs = [1.0j, (1+1j), (-1-1j), (1+0j)]
        for x in xs:
            self.assertEqual(cres.entry_point(x), x)
        for x in np.complex64(xs):
            self.assertEqual(cres.entry_point(x), x)

        cres = compile_isolated(pyfunc, [types.complex128],
                                return_type=types.complex128)

        xs = [1.0j, (1+1j), (-1-1j), (1+0j)]
        for x in xs:
            self.assertEqual(cres.entry_point(x), x)
        for x in np.complex128(xs):
            self.assertEqual(cres.entry_point(x), x)

Example 5

Project: reikna Source File: test_computation.py
def test_computation_adhoc_array(some_thr):
    """
    Tests that passing an array as an ad hoc argument to a computation
    while creating a plan raises an exception.
    """

    N = 200
    A = get_test_array((N, N), numpy.complex64)
    B = get_test_array(N, numpy.complex64)

    d = DummyNested(A, B, numpy.float32, 3, test_computation_adhoc_array=True)
    with pytest.raises(ValueError):
        dc = d.compile(some_thr)

Example 6

Project: pyFFTW Source File: test_pyfftw_complex.py
    def test_different_dtypes_fail(self):
        in_shape = self.input_shapes['2d']
        out_shape = self.output_shapes['2d']

        axes=(-1,)
        a, b = self.create_test_arrays(in_shape, out_shape)

        a_ = numpy.complex64(a)
        b_ = numpy.complex128(b)
        self.assertRaisesRegex(ValueError, 'Invalid scheme',
                FFTW, *(a_,b_))

        a_ = numpy.complex128(a)
        b_ = numpy.complex64(b)
        self.assertRaisesRegex(ValueError, 'Invalid scheme',
                FFTW, *(a_,b_))

Example 7

Project: spimagine Source File: imageprocessor.py
Function: apply
    def apply(self,data):
        dshape = data.shape
        
        res = gputools.pad_to_power2(data.astype(np.complex64), mode = "wrap")

        res = 1./np.sqrt(res.size)*np.fft.fftshift(abs(gputools.fft(res)))
        
        res = gputools.pad_to_shape(res,dshape)
        
        if self.log:
            return np.log2(0.001+res)
        else:
            return res

Example 8

Project: pyFFTW Source File: test_pyfftw_real_backward.py
Function: set_up
    def setUp(self):

        self.input_dtype = numpy.complex64
        self.output_dtype = numpy.float32
        self.np_fft_comparison = numpy.fft.irfft

        self.direction = 'FFTW_BACKWARD'

Example 9

Project: scipy Source File: test_blas.py
def test_get_blas_funcs_alias():
    # check alias for get_blas_funcs
    f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64)
    assert f.typecode == 'c'
    assert g.typecode == 'c'

    f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64)
    assert f is g
    assert f is h

Example 10

Project: deep_recommend_system Source File: diag_op_test.py
  def testRankTwoComplexTensor(self):
    for dtype in [np.complex64, np.complex128]:
      x = np.array([[1.1 + 1.1j, 2.2 + 2.2j, 3.3 + 3.3j],
                    [4.4 + 4.4j, 5.5 + 5.5j, 6.6 + 6.6j]], dtype=dtype)
      expected_ans = np.array(
          [[[[1.1 + 1.1j, 0 + 0j, 0 + 0j], [0 + 0j, 0 + 0j, 0 + 0j]],
            [[0 + 0j, 2.2 + 2.2j, 0 + 0j], [0 + 0j, 0 + 0j, 0 + 0j]],
            [[0 + 0j, 0 + 0j, 3.3 + 3.3j], [0 + 0j, 0 + 0j, 0 + 0j]]],
           [[[0 + 0j, 0 + 0j, 0 + 0j], [4.4 + 4.4j, 0 + 0j, 0 + 0j]],
            [[0 + 0j, 0 + 0j, 0 + 0j], [0 + 0j, 5.5 + 5.5j, 0 + 0j]],
            [[0 + 0j, 0 + 0j, 0 + 0j], [0 + 0j, 0 + 0j, 6.6 + 6.6j]]]],
           dtype=dtype)
      self.diagOp(x, dtype, expected_ans)

Example 11

Project: deep_recommend_system Source File: fft_ops_test.py
Function: test_error
  def testError(self):
    if tf.test.is_gpu_available():
      for rank in VALID_FFT_RANKS:
        for dims in xrange(0, rank):
          x = np.zeros((1,) * dims).astype(np.complex64)
          with self.assertRaisesWithPredicateMatch(
              ValueError,
              "Shape must be .*rank {}.*".format(rank)):
            self._tfFFT(x, rank)
          with self.assertRaisesWithPredicateMatch(
              ValueError,
              "Shape must be .*rank {}.*".format(rank)):
            self._tfIFFT(x, rank)

Example 12

Project: reikna Source File: test_computation.py
def test_untyped_scalar(some_thr):
    """
    Tests that passing an untyped (i.e. not a ndarray with shape==tuple())
    scalar as an argument to a kernel while creating a plan raises an exception.
    """

    N = 200
    A = get_test_array((N, N), numpy.complex64)
    B = get_test_array(N, numpy.complex64)

    d = Dummy(A, B, numpy.float32, test_untyped_scalar=True)
    with pytest.raises(TypeError):
        dc = d.compile(some_thr)

Example 13

Project: scipy Source File: test_matfuncs.py
    def test_padecases_dtype_complex(self):
        for dtype in [np.complex64, np.complex128]:
            for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
                A = scale * eye(3, dtype=dtype)
                observed = expm(A)
                expected = exp(scale) * eye(3, dtype=dtype)
                assert_array_almost_equal_nulp(observed, expected, nulp=100)

Example 14

Project: reikna Source File: test_computation.py
def test_computation_incorrect_type(some_thr):
    """
    Tests that passing an argument with an incorrect type as an argument to a computation
    while creating a plan raises an exception.
    """

    N = 200
    A = get_test_array((N, N), numpy.complex64)
    B = get_test_array(N, numpy.complex64)

    d = DummyNested(A, B, numpy.float32, 3, test_computation_incorrect_type=True)
    with pytest.raises(TypeError):
        dc = d.compile(some_thr)

Example 15

Project: numba Source File: test_dyn_array.py
Function: test_2d_dtype_kwarg
    @tag('important')
    def test_2d_dtype_kwarg(self):
        pyfunc = self.pyfunc
        def func(m, n):
            return pyfunc((m, n), dtype=np.complex64)
        self.check_2d(func)

Example 16

Project: pytools Source File: __init__.py
def to_uncomplex_dtype(dtype):
    import numpy
    if dtype == numpy.complex64:
        return numpy.float32
    elif dtype == numpy.complex128:
        return numpy.float64
    if dtype == numpy.float32:
        return numpy.float32
    elif dtype == numpy.float64:
        return numpy.float64
    else:
        raise TypeError("unrecgonized dtype '%s'" % dtype)

Example 17

Project: deep_recommend_system Source File: tensor_util_test.py
Function: test_complex64
  def testComplex64(self):
    t = tensor_util.make_tensor_proto((1+2j), dtype=tf.complex64)
    self.assertProtoEquals("""
      dtype: DT_COMPLEX64
      tensor_shape {}
      scomplex_val: 1
      scomplex_val: 2
      """, t)
    a = tensor_util.MakeNdarray(t)
    self.assertEquals(np.complex64, a.dtype)
    self.assertAllEqual(np.array(1 + 2j), a)

Example 18

Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test_print.py
Function: test_complex_types
def test_complex_types():
    """Check formatting of complex types.

        This is only for the str function, and only for simple types.
        The precision of np.float and np.longdouble aren't the same as the
        python float precision.

    """
    for t in [np.complex64, np.cdouble, np.clongdouble]:
        yield check_complex_type, t

Example 19

Project: numba Source File: test_array_iterators.py
    def basic_inputs(self):
        yield np.arange(4).astype(np.complex64)
        yield np.arange(8)[::2]
        a = np.arange(12).reshape((3, 4))
        yield a
        yield a.copy(order='F')

Example 20

Project: numba Source File: test_typeof.py
Function: test_complex
    def test_complex(self):
        s = compute_fingerprint(1j)
        self.assertEqual(s, compute_fingerprint(1+0j))
        s = compute_fingerprint(np.complex64())
        self.assertEqual(compute_fingerprint(np.complex64(2.0)), s)
        self.assertNotEqual(compute_fingerprint(np.complex128()), s)

Example 21

Project: scipy Source File: basic.py
def _raw_fftn_dispatch(x, shape, axes, overwrite_x, direction):
    tmp = _asfarray(x)

    try:
        work_function = _DTYPE_TO_FFTN[tmp.dtype]
    except KeyError:
        raise ValueError("type %s is not supported" % tmp.dtype)

    if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)):
        overwrite_x = 1

    overwrite_x = overwrite_x or _datacopied(tmp, x)
    return _raw_fftnd(tmp,shape,axes,direction,overwrite_x,work_function)

Example 22

Project: deep_recommend_system Source File: fft_ops_test.py
Function: test_empty
  def testEmpty(self):
    if tf.test.is_gpu_available():
      for rank in VALID_FFT_RANKS:
        for dims in xrange(rank, rank + 3):
          x = np.zeros((0,) * dims).astype(np.complex64)
          self.assertEqual(x.shape, self._tfFFT(x, rank).shape)
          self.assertEqual(x.shape, self._tfIFFT(x, rank).shape)

Example 23

Project: pyFFTW Source File: test_pyfftw_base.py
Function: set_up
    def setUp(self):

        self.input_dtype = numpy.complex64
        self.output_dtype = numpy.complex64
        self.np_fft_comparison = numpy.fft.fft

        self.direction = 'FFTW_FORWARD'
        return

Example 24

Project: scipy Source File: fourier.py
def _get_output_fourier(output, input):
    if output is None:
        if input.dtype.type in [numpy.complex64, numpy.complex128,
                                numpy.float32]:
            output = numpy.zeros(input.shape, dtype=input.dtype)
        else:
            output = numpy.zeros(input.shape, dtype=numpy.float64)
        return_value = output
    elif type(output) is type:
        if output not in [numpy.complex64, numpy.complex128,
                          numpy.float32, numpy.float64]:
            raise RuntimeError("output type not supported")
        output = numpy.zeros(input.shape, dtype=output)
        return_value = output
    else:
        if output.shape != input.shape:
            raise RuntimeError("output shape not correct")
        return_value = None
    return output, return_value

Example 25

Project: deep_recommend_system Source File: matmul_op_test.py
Function: randmatrix
  def _randMatrix(self, rows, cols, dtype):
    if dtype in (np.complex64, np.complex128):
      if dtype == np.complex64:
        float_dtype = np.float32
      else:
        float_dtype = np.float64
      real = self._randMatrix(rows, cols, float_dtype)
      imag = self._randMatrix(rows, cols, float_dtype)
      return real + 1j * imag
    else:
      return np.random.uniform(low=1.0, high=100.0, size=rows * cols).reshape(
          [rows, cols]).astype(dtype)

Example 26

Project: deep_recommend_system Source File: pad_op_test.py
Function: test_complex_types
  def testComplexTypes(self):
    for t in [np.complex64, np.complex128]:
      x = np.random.rand(2, 5).astype(t)
      self._testAll(x + 1j * x, [[1, 0], [2, 0]])
      x = np.random.rand(3, 2, 1, 1).astype(t)
      self._testAll(x + 1j * x, [[0, 0], [0, 0], [0, 0], [0, 0]])

Example 27

Project: reikna Source File: test_computation.py
def test_incorrect_parameter_name():
    """
    Tests that setting incorrect parameter name
    in the Computation constructor raises an exception.
    """

    N = 200
    A = get_test_array((N, N), numpy.complex64)
    B = get_test_array(N, numpy.complex64)

    with pytest.raises(ValueError):
        d = Dummy(A, B, numpy.float32, test_incorrect_parameter_name=True)

Example 28

Project: scipy Source File: test_linsolve.py
Function: test_bad_inputs
    def test_bad_inputs(self):
        A = self.A.tocsc()

        assert_raises(ValueError, splu, A[:,:4])
        assert_raises(ValueError, spilu, A[:,:4])

        for lu in [splu(A), spilu(A)]:
            b = random.rand(42)
            B = random.rand(42, 3)
            BB = random.rand(self.n, 3, 9)
            assert_raises(ValueError, lu.solve, b)
            assert_raises(ValueError, lu.solve, B)
            assert_raises(ValueError, lu.solve, BB)
            assert_raises(TypeError, lu.solve,
                          b.astype(np.complex64))
            assert_raises(TypeError, lu.solve,
                          b.astype(np.complex128))

Example 29

Project: reikna Source File: test_computation.py
def test_kernel_adhoc_array(some_thr):
    """
    Tests that passing an array as an ad hoc argument to a kernel
    while creating a plan raises an exception.
    """

    N = 200
    A = get_test_array((N, N), numpy.complex64)
    B = get_test_array(N, numpy.complex64)

    d = Dummy(A, B, numpy.float32, test_kernel_adhoc_array=True)
    with pytest.raises(ValueError):
        dc = d.compile(some_thr)

Example 30

Project: deep_recommend_system Source File: diag_op_test.py
  def testRankOneComplexTensor(self):
    for dtype in [np.complex64, np.complex128]:
      x = np.array([1.1 + 1.1j, 2.2 + 2.2j, 3.3 + 3.3j], dtype=dtype)
      expected_ans = np.array(
          [[1.1 + 1.1j, 0 + 0j, 0 + 0j],
           [0 + 0j, 2.2 + 2.2j, 0 + 0j],
           [0 + 0j, 0 + 0j, 3.3 + 3.3j]], dtype=dtype)
      self.diagOp(x, dtype, expected_ans)

Example 31

Project: reikna Source File: test_computation.py
def test_computation_incorrect_role(some_thr):
    """
    Tests that passing an array which does not support a required role
    (e.g. a role=='i' for role=='o' parameter) as an argument to a computation
    while creating a plan raises an exception.
    """

    N = 200
    A = get_test_array((N, N), numpy.complex64)
    B = get_test_array(N, numpy.complex64)

    d = DummyNested(A, B, numpy.float32, 3, test_computation_incorrect_role=True)
    with pytest.raises(TypeError):
        dc = d.compile(some_thr)

Example 32

Project: statsmodels Source File: test_kalman.py
Function: setup_class
    @classmethod
    def setup_class(cls):
        raise SkipTest('Not implemented')
        super(TestClark1987SingleComplex, cls).setup_class(
            dtype=np.complex64, conserve_memory=0
        )
        cls.model, cls.filter = cls.init_filter()
        cls.result = cls.run_filter()

Example 33

Project: statsmodels Source File: test_representation.py
Function: setup_class
    @classmethod
    def setup_class(cls):
        raise SkipTest('Not implemented')
        super(TestClark1987SingleComplex, cls).setup_class(
            dtype=np.complex64, conserve_memory=0
        )
        cls.results = cls.run_filter()

Example 34

Project: pyFFTW Source File: test_pyfftw_class_misc.py
    def test_input_dtype(self):
        '''Test to see if the input_dtype property returns the correct thing
        '''
        self.assertEqual(self.fft.input_dtype, self.input_array.dtype)

        new_input_array = numpy.complex64(self.input_array)
        new_output_array = numpy.complex64(self.output_array)

        new_fft = FFTW(new_input_array, new_output_array)

        self.assertEqual(new_fft.input_dtype, new_input_array.dtype)

Example 35

Project: PySAR Source File: _readfile.py
def read_complex64(file):
  '''Reads roi_pac int or slc data.
  
  Requires the file path and returns amplitude and phase
  Usage:
    amp, phase, rscDictionary = readInt('/Users/sbaker/Desktop/geo_070603-070721_0048_00018.int')
  '''
  rscContents = read_rsc_file(file + '.rsc')
  width  = int(rscContents['WIDTH'])
  length = int(rscContents['FILE_LENGTH'])
  data = np.fromfile(file,np.complex64,length*2*width).reshape(length,width)
  amplitude = np.array([np.hypot(  data.real,data.imag)]).reshape(length,width)
  phase     = np.array([np.arctan2(data.imag,data.real)]).reshape(length,width)
  return amplitude, phase, rscContents

Example 36

Project: globalstar Source File: capture_cc.py
Function: init
    def __init__(self):
        gr.sync_block.__init__(self,
            name="capture_cc",
            #in_sig=[<+numpy.float+>],
            in_sig=[numpy.complex64, numpy.float32],
            out_sig=None)

Example 37

Project: librosa Source File: test_failures.py
@raises(librosa.ParameterError)
def test_istft_bad_window():

    D = np.zeros((1025, 10), dtype=np.complex64)

    n_fft = 2 * (D.shape[0] - 1)

    window = np.ones(n_fft // 2)

    librosa.istft(D, window=window)

Example 38

Project: tfdeploy Source File: ops.py
Function: random
    def random(self, *shapes, **kwargs):
        if all(isinstance(i, int) for i in shapes):
            if kwargs.get("complex", False):
                return (self.random(*shapes) + 1j * self.random(*shapes)).astype(np.complex64)
            else:
                return np.random.rand(*shapes)
        else:
            return tuple(self.random(*shape) for shape in shapes)

Example 39

Project: pybladeRF Source File: waterfall.py
Function: update_image
def update_image(i):

    data[:] = numpy.fromstring(
        sys.stdin.read(8192),
        dtype=numpy.complex64,
        )

    fft = numpy.fft.rfft(data)
    line = numpy.sqrt(numpy.real(fft)**2+numpy.imag(fft)**2)
    im_data[:,:WIDTH-1] = im_data[:,1:]
    im_data[:,WIDTH-1] = line
    im.set_array(im_data)
    return (im,)

Example 40

Project: deep_recommend_system Source File: tensor_util_test.py
  def testComplexWithImplicitRepeat(self):
    for dtype, np_dtype in [(tf.complex64, np.complex64),
                            (tf.complex128, np.complex128)]:
      t = tensor_util.make_tensor_proto((1+1j), shape=[3, 4],
                                        dtype=dtype)
      a = tensor_util.MakeNdarray(t)
      self.assertAllClose(np.array([[(1+1j), (1+1j), (1+1j), (1+1j)],
                                    [(1+1j), (1+1j), (1+1j), (1+1j)],
                                    [(1+1j), (1+1j), (1+1j), (1+1j)]],
                                   dtype=np_dtype), a)

Example 41

Project: pandas-qt Source File: test_DataFrameModel.py
Function: test_unhandleddtype
    def test_unhandledDtype(self, model, index):
        dataFrame = pandas.DataFrame([92.289+151.96j], columns=['A'])
        dataFrame['A'] = dataFrame['A'].astype(numpy.complex64)
        model.setDataFrame(dataFrame)
        assert not model.dataFrame().empty
        assert model.dataFrame() is dataFrame

        assert index.isValid()
        assert model.data(index) == None

Example 42

Project: pyFFTW Source File: test_pyfftw_class_misc.py
    def test_output_dtype(self):
        '''Test to see if the output_dtype property returns the correct thing
        '''
        self.assertEqual(self.fft.output_dtype, self.output_array.dtype)

        new_input_array = numpy.complex64(self.input_array)
        new_output_array = numpy.complex64(self.output_array)

        new_fft = FFTW(new_input_array, new_output_array)

        self.assertEqual(new_fft.output_dtype, new_output_array.dtype)

Example 43

Project: scipy Source File: fourier.py
def _get_output_fourier_complex(output, input):
    if output is None:
        if input.dtype.type in [numpy.complex64, numpy.complex128]:
            output = numpy.zeros(input.shape, dtype=input.dtype)
        else:
            output = numpy.zeros(input.shape, dtype=numpy.complex128)
        return_value = output
    elif type(output) is type:
        if output not in [numpy.complex64, numpy.complex128]:
            raise RuntimeError("output type not supported")
        output = numpy.zeros(input.shape, dtype=output)
        return_value = output
    else:
        if output.shape != input.shape:
            raise RuntimeError("output shape not correct")
        return_value = None
    return output, return_value

Example 44

Project: pandas-qt Source File: test_DataFrameModel.py
Function: test_unhandleddtype
    def test_unhandledDtype(self, model, index):
        dataFrame = pandas.DataFrame([92.289+151.96j], columns=['A'])
        dataFrame['A'] = dataFrame['A'].astype(numpy.complex64)
        model.setDataFrame(dataFrame)
        assert not model.dataFrame().empty
        assert model.dataFrame() is dataFrame

        assert index.isValid()
        model.enableEditing(True)
        with pytest.raises(TypeError) as excinfo:
            model.setData(index, numpy.complex64(92+151j))
        assert "unhandled data type" in unicode(excinfo.value)

Example 45

Project: reikna Source File: test_computation.py
def test_same_arg_as_i_and_o(some_thr):
    """
    Tests that the same 'io' array can be used both as an input and as an output argument
    of the same nested computation.
    """

    N = 2000
    coeff = 2
    second_coeff = 3
    A = numpy.ones((N,N)).astype(numpy.complex64) # get_test_array((N, N), numpy.complex64)
    B = numpy.ones(N).astype(numpy.complex64) # get_test_array(N, numpy.complex64)

    A_dev = some_thr.to_device(A)
    B_dev = some_thr.to_device(B)
    C_dev = some_thr.empty_like(A_dev)
    D_dev = some_thr.empty_like(B_dev)

    d = DummyNested(
        A_dev, B_dev, numpy.float32, second_coeff, test_same_arg_as_i_and_o=True).compile(some_thr)
    d(C_dev, D_dev, A_dev, B_dev, coeff)
    C = C_dev.get()
    D = D_dev.get()

    C_ref, D_ref = mock_dummy_nested(A, B, coeff, second_coeff, test_same_arg_as_i_and_o=True)

    assert diff_is_negligible(C, C_ref)
    assert diff_is_negligible(D, D_ref)

Example 46

Project: lowrank-gru Source File: fftconv.py
def to_complex_gpuarray(x, copyif=False):
    """
    Adapted version of theano.misc.pycuda_utils.to_gpuarray that takes
    an array with an extra trailing dimension of length 2 for
    real/imaginary parts, and turns it into a complex64 PyCUDA
    GPUArray.

    """
    if not isinstance(x, CudaNdarray):
        raise ValueError("We can transfer only CudaNdarray "
                         "to pycuda.gpuarray.GPUArray")
    else:
        # Check if trailing dimension has length 2
        assert x.shape[-1] == 2

        # check if dtype is float32
        assert x.dtype == 'float32'

        # Check if it is c contiguous
        size = 1
        c_contiguous = True
        for i in range(x.ndim - 1, -1, -1):
            if x.shape[i] == 1:
                continue
            if x._strides[i] != size:
                c_contiguous = False
                break
            size *= x.shape[i]
        if not c_contiguous:
            if copyif:
                x = x.copy()
            else:
                raise ValueError("We were asked to not copy memory, "
                                 "but the memory is not c contiguous.")

        # Now x is always c contiguous
        px = pycuda.gpuarray.GPUArray(x.shape[:-1], np.complex64, base=x,
                                      gpudata=x.gpudata)
        return px

Example 47

Project: lowrank-gru Source File: fftconv.py
def sc_complex_dot_batched(bx_gpu, by_gpu, bc_gpu, transa='N', transb='N',
                           handle=None):
    """
    Uses cublasCgemmBatched to compute a bunch of complex dot products
    in parallel.

    """
    if handle is None:
        handle = scikits.cuda.misc._global_cublas_handle

    assert len(bx_gpu.shape) == 3
    assert len(by_gpu.shape) == 3
    assert len(bc_gpu.shape) == 3
    assert bx_gpu.dtype == np.complex64
    assert by_gpu.dtype == np.complex64
    assert bc_gpu.dtype == np.complex64

    # Get the shapes of the arguments
    bx_shape = bx_gpu.shape
    by_shape = by_gpu.shape

    # Perform matrix multiplication for 2D arrays:
    alpha = np.complex64(1.0)
    beta = np.complex64(0.0)

    transa = string.lower(transa)
    transb = string.lower(transb)

    if transb in ['t', 'c']:
        N, m, k = by_shape
    elif transb in ['n']:
        N, k, m = by_shape
    else:
        raise ValueError('invalid value for transb')

    if transa in ['t', 'c']:
        N2, l, n = bx_shape
    elif transa in ['n']:
        N2, n, l = bx_shape
    else:
        raise ValueError('invalid value for transa')

    if l != k:
        raise ValueError('objects are not aligned')

    if N != N2:
        raise ValueError('batch sizes are not the same')

    if transb == 'n':
        lda = max(1, m)
    else:
        lda = max(1, k)

    if transa == 'n':
        ldb = max(1, k)
    else:
        ldb = max(1, n)

    ldc = max(1, m)

    # construct pointer arrays needed for cublasCgemmBatched
    bx_arr = bptrs(bx_gpu)
    by_arr = bptrs(by_gpu)
    bc_arr = bptrs(bc_gpu)

    cublas.cublasCgemmBatched(handle, transb, transa, m, n, k, alpha,
                              by_arr.gpudata, lda, bx_arr.gpudata, ldb,
                              beta, bc_arr.gpudata, ldc, N)

Example 48

Project: attention-lvcsr Source File: fftconv.py
Function: make_thunk
    def make_thunk(self, node, storage_map, _, _2):
        super(CuIFFTOp, self).make_thunk(node, storage_map, _, _2)

        from theano.misc.pycuda_utils import to_gpuarray
        inputs = [storage_map[v] for v in node.inputs]
        outputs = [storage_map[v] for v in node.outputs]

        plan_input_shape = [None]
        plan = [None]

        def thunk():
            input_shape = inputs[0][0].shape

            # construct output shape
            # chop off the extra length-2 dimension for real/imag
            output_shape = list(input_shape[:-1])
            # restore full signal length
            output_shape[-1] = (output_shape[-1] - 1) * 2
            output_shape = tuple(output_shape)

            z = outputs[0]

            # only allocate if there is no previous allocation of the
            # right size.
            if z[0] is None or z[0].shape != output_shape:
                z[0] = CudaNdarray.zeros(output_shape)

            input_pycuda = to_gpuarray(inputs[0][0])
            # input_pycuda is a float32 array with an extra dimension,
            # but will be interpreted by scikits.cuda as a complex64
            # array instead.
            output_pycuda = to_gpuarray(z[0])

            # only initialise plan if necessary
            if plan[0] is None or plan_input_shape[0] != input_shape:
                plan_input_shape[0] = input_shape
                plan[0] = fft.Plan(output_shape[1:], np.complex64, np.float32,
                                   batch=output_shape[0])

            fft.ifft(input_pycuda, output_pycuda, plan[0])
            # strangely enough, enabling rescaling here makes it run
            # very, very slowly.  so do this rescaling manually
            # afterwards!

        thunk.inputs = inputs
        thunk.outputs = outputs
        thunk.lazy = False

        return thunk

Example 49

Project: lowrank-gru Source File: fftconv.py
Function: make_thunk
    def make_thunk(self, node, storage_map, compute_map, no_recycling):
        super(CuFFTOp, self).make_thunk(node, storage_map, compute_map, no_recycling)

        from theano.misc.pycuda_utils import to_gpuarray
        inputs = [storage_map[v] for v in node.inputs]
        outputs = [storage_map[v] for v in node.outputs]

        plan_input_shape = [None]
        plan = [None]

        def thunk():
            input_shape = inputs[0][0].shape
            output_shape = input_shape

            z = outputs[0]

            # only allocate if there is no previous allocation of the
            # right size.
            if z[0] is None or z[0].shape != output_shape:
                z[0] = CudaNdarray.zeros(output_shape)

            input_pycuda = to_gpuarray(inputs[0][0])
            # I thought we'd need to change the type on output_pycuda
            # so it is complex64, but as it turns out scikits.cuda.fft
            # doesn't really care either way and treats the array as
            # if it is complex64 anyway.
            output_pycuda = to_gpuarray(z[0])

            # only initialise plan if necessary
            if plan[0] is None or plan_input_shape[0] != input_shape:
                plan_input_shape[0] = input_shape
                plan[0] = fft.Plan(input_shape[1:-1], np.complex64, np.complex64,
                                   batch=input_shape[0])

            fft.fft(input_pycuda, output_pycuda, plan[0])
            compute_map[node.outputs[0]][0] = True

        thunk.inputs = inputs
        thunk.outputs = outputs
        thunk.lazy = False

        return thunk

Example 50

Project: lowrank-gru Source File: fftconv.py
Function: make_thunk
    def make_thunk(self, node, storage_map, compute_map, no_recycling):
        super(CuIFFTOp, self).make_thunk(node, storage_map, compute_map, no_recycling)

        from theano.misc.pycuda_utils import to_gpuarray
        inputs = [storage_map[v] for v in node.inputs]
        outputs = [storage_map[v] for v in node.outputs]

        plan_input_shape = [None]
        plan = [None]

        def thunk():
            input_shape = inputs[0][0].shape
            output_shape = input_shape

            z = outputs[0]

            # only allocate if there is no previous allocation of the
            # right size.
            if z[0] is None or z[0].shape != output_shape:
                z[0] = CudaNdarray.zeros(output_shape)

            input_pycuda = to_gpuarray(inputs[0][0])
            # input_pycuda is a float32 array with an extra dimension,
            # but will be interpreted by scikits.cuda as a complex64
            # array instead.
            output_pycuda = to_gpuarray(z[0])

            # only initialise plan if necessary
            if plan[0] is None or plan_input_shape[0] != input_shape:
                plan_input_shape[0] = input_shape
                plan[0] = fft.Plan(output_shape[1:-1], np.complex64, np.complex64,
                                   batch=output_shape[0])

            fft.ifft(input_pycuda, output_pycuda, plan[0])
            compute_map[node.outputs[0]][0] = True
            # strangely enough, enabling rescaling here makes it run
            # very, very slowly.  so do this rescaling manually
            # afterwards!

        thunk.inputs = inputs
        thunk.outputs = outputs
        thunk.lazy = False

        return thunk
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3