Python numpy.angle() Examples

The following are 30 code examples of numpy.angle(). 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 numpy , or try the search function .
Example #1
Source File: dsss-bpsk-reverse.py    From clock-recovery with MIT License 7 votes vote down vote up
def extract_chip_samples(samples):
    a = array(samples)
    f = scipy.fft(a*a)
    p = find_clock_frequency(abs(f))
    if 0 == p:
        return []
    cycles_per_sample = (p*1.0)/len(f)
    clock_phase = 0.25 + numpy.angle(f[p])/(tau)
    if clock_phase <= 0.5:
        clock_phase += 1
    chip_samples = []
    for i in range(len(a)):
        if clock_phase >= 1:
            clock_phase -= 1
            chip_samples.append(a[i])
        clock_phase += cycles_per_sample
    return chip_samples

# input: complex valued samples, FFT bin number of chip rate
#        input signal must be centered at 0 frequency
# output: number of chips found in repetitive chip sequence 
Example #2
Source File: retinotopy.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def _retinotopic_field_sign_triangles(m, retinotopy):
    t = m.tess if isinstance(m, geo.Mesh) or isinstance(m, geo.Topology) else m
    # get the polar angle and eccen data as a complex number in degrees
    if pimms.is_str(retinotopy):
        (x,y) = as_retinotopy(retinotopy_data(m, retinotopy), 'geographical')
    elif retinotopy is Ellipsis:
        (x,y) = as_retinotopy(retinotopy_data(m, 'any'),      'geographical')
    else:
        (x,y) = as_retinotopy(retinotopy,                     'geographical')
    # Okay, now we want to make some coordinates...
    coords = np.asarray([x, y])
    us = coords[:, t.indexed_faces[1]] - coords[:, t.indexed_faces[0]]
    vs = coords[:, t.indexed_faces[2]] - coords[:, t.indexed_faces[0]]
    (us,vs) = [np.concatenate((xs, np.full((1, t.face_count), 0.0))) for xs in [us,vs]]
    xs = np.cross(us, vs, axis=0)[2]
    xs[np.isclose(xs, 0)] = 0
    return np.sign(xs) 
Example #3
Source File: test_galario.py    From galario with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_get_coords_meshgrid(nxy, inc, dxy, Dx, Dy, real_type, tol, acc_lib):

    ncol, nrow = nxy, nxy

    # create the referencemesh grid
    inc_cos = np.cos(inc)
    x = (np.linspace(0.5, -0.5 + 1./float(ncol), ncol, dtype=real_type)) * dxy * ncol
    y = (np.linspace(0.5, -0.5 + 1./float(nrow), nrow, dtype=real_type)) * dxy * nrow

    # we shrink the x axis, since PA is the angle East of North of the
    # the plane of the disk (orthogonal to the angular momentum axis)
    # PA=0 is a disk with vertical orbital node (aligned along North-South)
    x_m, y_m = np.meshgrid((x - Dx)/ inc_cos, y - Dy)
    R_m = np.sqrt(x_m ** 2. + y_m ** 2.)

    x_test, y_test, x_m_test, y_m_test, R_m_test = acc_lib.get_coords_meshgrid(nrow, ncol, dxy, inc, Dx=Dx, Dy=Dy, origin='upper')

    assert_allclose(x, x_test, atol=0, rtol=tol)
    assert_allclose(y, y_test, atol=0, rtol=tol)
    assert_allclose(x_m, x_m_test, atol=0, rtol=tol)
    assert_allclose(y_m, y_m_test, atol=0, rtol=tol)
    assert_allclose(R_m, R_m_test, atol=0, rtol=tol) 
Example #4
Source File: wave.py    From ocelot with GNU General Public License v3.0 6 votes vote down vote up
def psi(self):
        # psi angle 0 - horizontal, pi/2 - vertical
        with np.errstate(divide='ignore'):
            psi = np.arctan(self.s2 / self.s1) / 2

        idx1 = np.where((self.s1 < 0) & (self.s2 > 0))
        idx2 = np.where((self.s1 < 0) & (self.s2 < 0))
        if np.size(psi) == 1:
            # continue
            # psi = psi
            if np.size(idx1): psi += np.pi / 2
            if np.size(idx2): psi -= np.pi / 2
        else:
            psi[idx1] += np.pi / 2
            psi[idx2] -= np.pi / 2
        return psi 
Example #5
Source File: comp_angle_opening.py    From pyleecan with Apache License 2.0 6 votes vote down vote up
def comp_angle_opening(self):
    """Compute the average opening angle of the Slot

    Parameters
    ----------
    self : Slot
        A Slot object

    Returns
    -------
    alpha: float
        Average opening angle of the slot [rad]

    """

    line_list = self.build_geometry()
    Z1 = line_list[0].get_begin()
    Z2 = line_list[-1].get_end()

    return angle(Z2) - angle(Z1) 
Example #6
Source File: fermionic_simulation.py    From OpenFermion-Cirq with Apache License 2.0 6 votes vote down vote up
def _eigen_components(self):
        # projector onto subspace spanned by basis states with
        # Hamming weight != 2
        zero_component = np.diag(
            [int(bin(i).count('1') != 2) for i in range(16)])

        state_pairs = (('0110', '1001'), ('0101', '1010'), ('0011', '1100'))

        plus_minus_components = tuple(
            (-abs(weight) * sign / np.pi,
             state_swap_eigen_component(state_pair[0], state_pair[1], sign,
                                        np.angle(weight)))
            for weight, state_pair in zip(self.weights, state_pairs)
            for sign in (-1, 1))

        return ((0, zero_component),) + plus_minus_components 
Example #7
Source File: _ffft_test.py    From OpenFermion-ProjectQ with Apache License 2.0 5 votes vote down vote up
def test_correct_phase_after_reordering_1qubit(self):
        H | self.reg1
        Rz(0.03) | self.reg1
        self.eng1.flush()
        angle0 = numpy.angle(ordered_wavefunction(self.eng1)[0])
        angle1 = numpy.angle(ordered_wavefunction(self.eng1)[1])
        self.assertAlmostEqual(angle1 - angle0, 0.03) 
Example #8
Source File: _ffft_test.py    From OpenFermion-ProjectQ with Apache License 2.0 5 votes vote down vote up
def test_2mode_ffft_correct_frequencies(self):
        n_qubits = 2
        frequencies_seen = numpy.zeros(n_qubits)

        for qubit in range(n_qubits):
            engine = MainEngine()
            register = engine.allocate_qureg(n_qubits)
            X | register[qubit]
            ffft(engine, register, n_qubits)
            engine.flush()

            wavefunction = ordered_wavefunction(engine)
            nonzero_wavefunction_elmts = []
            for el in wavefunction:
                if abs(el) > 10 ** -5:
                    nonzero_wavefunction_elmts.append(el)
            All(Measure) | register

            phase_factor = (nonzero_wavefunction_elmts[1] /
                            nonzero_wavefunction_elmts[0])
            offset = numpy.angle(nonzero_wavefunction_elmts[0])

            self.assertAlmostEqual(offset, 0.0)
            for i in range(1, len(nonzero_wavefunction_elmts)):
                self.assertAlmostEqual(phase_factor,
                                       (nonzero_wavefunction_elmts[i] /
                                        nonzero_wavefunction_elmts[i - 1]))
            frequencies_seen[qubit] = numpy.angle(phase_factor)

        frequencies_seen = numpy.sort(frequencies_seen)
        expected = numpy.sort(2 * numpy.pi * numpy.arange(n_qubits) / n_qubits)

        self.assertTrue(numpy.allclose(frequencies_seen, expected)) 
Example #9
Source File: _ffft_test.py    From OpenFermion-ProjectQ with Apache License 2.0 5 votes vote down vote up
def test_correct_phase_after_reordering_multiple_qubits(self):
        All(H) | self.reg3
        Rz(0.07) | self.reg3[1]
        self.eng3.flush()
        wavefunction = ordered_wavefunction(self.eng3)
        self.assertAlmostEqual(numpy.angle(wavefunction[1]),
                               numpy.angle(wavefunction[0]))
        self.assertAlmostEqual(numpy.angle(wavefunction[6]),
                               numpy.angle(wavefunction[2]))
        self.assertAlmostEqual(numpy.angle(wavefunction[2]) -
                               numpy.angle(wavefunction[0]),
                               0.07) 
Example #10
Source File: wave.py    From ocelot with GNU General Public License v3.0 5 votes vote down vote up
def save_trf(trf, attr, flePath):
    if hasattr(trf, attr):
        filt = getattr(trf, attr)
    else:
        raise ValueError('no attribute', attr, 'in fransfer function')

    f = open(flePath, 'wb')
    header = 'Energy[eV] Filter_Abs Filter_Ang'
    np.savetxt(f, np.c_[trf.ev(), np.abs(trf.tr), np.angle(trf.tr)], header=header, fmt="%.8e", newline='\n',
               comments='')
    f.close() 
Example #11
Source File: audio.py    From Griffin_lim with MIT License 5 votes vote down vote up
def _griffin_lim(S):
    angles = np.exp(2j * np.pi * np.random.rand(*S.shape))
    S_complex = np.abs(S).astype(np.complex)
    for i in range(hparams.griffin_lim_iters):
        if i > 0:
            angles = np.exp(1j * np.angle(_stft(y)))
        y = _istft(S_complex * angles)
    return y 
Example #12
Source File: get_lines.py    From pyleecan with Apache License 2.0 5 votes vote down vote up
def get_lines(self):
    """return the list of lines that delimits the PolarArc

    Parameters
    ----------
    self : PolarArc
        a PolarArc object

    Returns
    -------
    line_list: list
        List of line need to draw the slot (2 Segment + 2 Arc1)
    """
    # check if the PolarArc is correct
    self.check()

    Z_ref = self.point_ref
    center = Z_ref * exp(-1j * angle(Z_ref))
    H = self.height
    A = self.angle
    # the points of the PolarArc
    Z2 = (center - (H / 2)) * exp(1j * (-(A / 2))) * exp(1j * angle(Z_ref))
    Z3 = (center + (H / 2)) * exp(1j * (-(A / 2))) * exp(1j * angle(Z_ref))
    Z4 = (center + (H / 2)) * exp(1j * (A / 2)) * exp(1j * angle(Z_ref))
    Z1 = (center - (H / 2)) * exp(1j * (A / 2)) * exp(1j * angle(Z_ref))

    # Lines that delimit the PolarArc
    line1 = Arc1(Z1, Z2, -abs(Z1), is_trigo_direction=False)
    line2 = Segment(Z2, Z3)
    line3 = Arc1(Z3, Z4, abs(Z3))
    line4 = Segment(Z4, Z1)

    return [line1, line2, line3, line4] 
Example #13
Source File: get_middle.py    From pyleecan with Apache License 2.0 5 votes vote down vote up
def get_middle(self):
    """Return the point at the middle of the arc

    Parameters
    ----------
    self : Arc3
        An Arc3 object

    Returns
    -------
    Zmid: complex
        Complex coordinates of the middle of the Arc3
    """

    # We use the complex representation of the point
    z1 = self.begin
    zc = self.get_center()
    R = self.comp_radius()

    # Generation of the point by rotation
    if self.is_trigo_direction:  # Top
        Zmid = R * exp(1j * pi / 2.0)
    else:  # Bottom
        Zmid = R * exp(-1j * pi / 2.0)

    # Geometric transformation : return to the main axis
    Zmid = Zmid * exp(1j * np_angle(z1 - zc)) + zc

    # Return (0,0) if the point is too close from 0
    if np_abs(Zmid) < 1e-6:
        Zmid = 0

    return Zmid 
Example #14
Source File: get_lines.py    From pyleecan with Apache License 2.0 5 votes vote down vote up
def get_lines(self):
    """Returns the Lines that delimit the Trapeze

    Parameters
    ----------
    self : Trapeze
        a Trapeze object


    Returns
    -------
    line_list : list
        list of 4 segments

    """
    # Check if the Trapeze is correct
    self.check()
    Z_ref = self.point_ref
    H = self.height
    W1 = self.W1
    W2 = self.W2

    # The 4 points of the Trapeze object
    Z1 = (complex(-H / 2, W1 / 2) * exp(1j * (angle(Z_ref)))) + Z_ref
    Z2 = (complex(-H / 2, -W1 / 2) * exp(1j * (angle(Z_ref)))) + Z_ref
    Z3 = (complex(H / 2, -W2 / 2) * exp(1j * (angle(Z_ref)))) + Z_ref
    Z4 = (complex(H / 2, W2 / 2) * exp(1j * (angle(Z_ref)))) + Z_ref

    # The lines that delimit the Trapeze
    line1 = Segment(Z1, Z2)
    line2 = Segment(Z2, Z3)
    line3 = Segment(Z3, Z4)
    line4 = Segment(Z4, Z1)

    return [line1, line2, line3, line4] 
Example #15
Source File: get_middle.py    From pyleecan with Apache License 2.0 5 votes vote down vote up
def get_middle(self):
    """Return the point at the middle of the arc

    Parameters
    ----------
    self : Arc2
        An Arc2 object

    Returns
    -------
    Zmid: complex
        Complex coordinates of the middle of the Arc2
    """

    self.check()

    # We use the complex representation of the point
    z1 = self.begin
    zc = self.center

    # Geometric transformation : center is the origine, angle(begin) = 0
    Zstart = (z1 - zc) * exp(-1j * np_angle(z1 - zc))

    # Generation of the point by rotation
    Zmid = Zstart * exp(1j * self.angle / 2.0)

    # Geometric transformation : return to the main axis
    Zmid = Zmid * exp(1j * np_angle(z1 - zc)) + zc

    # Return (0,0) if the point is too close from 0
    if np_abs(Zmid) < 1e-6:
        Zmid = 0

    return Zmid 
Example #16
Source File: get_angle.py    From pyleecan with Apache License 2.0 5 votes vote down vote up
def get_angle(self, is_deg=False):
    """Return the angle of the arc

    Parameters
    ----------
    self : Arc1
        An Arc1 object
    is_deg: bool
        True to convert to degree

    Returns
    -------
    angle: float
        Angle of the arc
    """
    # Go to center ref with begin on the X > 0 axis
    Zc = self.get_center()
    Z2 = (self.end - Zc) * exp(-1j * angle(self.begin - Zc))

    if Z2.imag > 0 and self.is_trigo_direction:
        alpha = angle(Z2)
    elif Z2.imag > 0 and not self.is_trigo_direction:
        alpha = -(2 * pi - angle(Z2))
    elif Z2.imag < 0 and self.is_trigo_direction:
        alpha = 2 * pi - abs(angle(Z2))
    elif Z2.imag < 0 and not self.is_trigo_direction:
        alpha = angle(Z2)
    elif Z2.imag == 0 and self.is_trigo_direction:
        alpha = abs(angle(Z2))
    elif Z2.imag == 0 and not self.is_trigo_direction:
        alpha = -abs(angle(Z2))
    else:
        alpha = 0

    if is_deg:
        return alpha * 180 / pi
    else:
        return alpha 
Example #17
Source File: get_middle.py    From pyleecan with Apache License 2.0 5 votes vote down vote up
def get_middle(self):
    """Return the point at the middle of the arc

    Parameters
    ----------
    self : Arc1
        An Arc1 object

    Returns
    -------
    Zmid: complex
        Complex coordinates of the middle of the Arc1
    """

    # We use the complex representation of the point
    z1 = self.begin
    z2 = self.end
    zc = self.get_center()

    # Geometric transformation : center is the origine, angle(begin) = 0
    Zstart = (z1 - zc) * exp(-1j * np_angle(z1 - zc))

    # Generation of the point by rotation
    alpha = self.get_angle()
    Zmid = Zstart * exp(1j * alpha / 2)

    # Geometric transformation : return to the main axis
    Zmid = Zmid * exp(1j * np_angle(z1 - zc)) + zc

    # Return (0,0) if the point is too close from 0
    if np_abs(Zmid) < 1e-6:
        Zmid = 0

    return Zmid 
Example #18
Source File: angle.py    From mars with Apache License 2.0 5 votes vote down vote up
def execute(cls, ctx, op):
        (z,), device_id, xp = as_same_device(
            [ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)

        with device(device_id):
            ctx[op.outputs[0].key] = xp.angle(z, deg=op.deg) 
Example #19
Source File: Input.py    From vimss with GNU General Public License v3.0 5 votes vote down vote up
def reconPhase(magnitude, fftWindowSize, hopSize, phaseIterations=10, initPhase=None, length=None):
    '''
    Griffin-Lim algorithm for reconstructing the phase for a given magnitude spectrogram, optionally with a given
    intial phase.
    :param magnitude: Magnitudes to be converted to audio
    :param fftWindowSize: Size of FFT window used to create magnitudes
    :param hopSize: Hop size in frames used to create magnitudes
    :param phaseIterations: Number of Griffin-Lim iterations to recover phase
    :param initPhase: If given, starts reconstruction with this particular phase matrix
    :param length: If given, audio signal is clipped/padded to this number of frames
    :return: 
    '''
    for i in range(phaseIterations):
        if i == 0:
            if initPhase is None:
                reconstruction = np.random.random_sample(magnitude.shape) + 1j * (2 * np.pi * np.random.random_sample(magnitude.shape) - np.pi)
            else:
                reconstruction = np.exp(initPhase * 1j) # e^(j*phase), so that angle => phase
        else:
            reconstruction = librosa.stft(audio, fftWindowSize, hopSize)
        spectrum = magnitude * np.exp(1j * np.angle(reconstruction))
        if i == phaseIterations - 1:
            audio = librosa.istft(spectrum, hopSize, length=length)
        else:
            audio = librosa.istft(spectrum, hopSize)
    return audio 
Example #20
Source File: basic.py    From D-VAE with MIT License 5 votes vote down vote up
def impl(self, x):
        return numpy.angle(x) 
Example #21
Source File: basic.py    From D-VAE with MIT License 5 votes vote down vote up
def cast(x, dtype):
    """
    Symbolically cast `x` to a Scalar of given `dtype`.

    """
    if dtype == 'floatX':
        dtype = config.floatX

    _x = as_scalar(x)
    if _x.type.dtype == dtype:
        return _x
    if _x.type.dtype.startswith('complex') and not dtype.startswith('complex'):
        raise TypeError('Casting from complex to real is ambiguous: consider'
                        ' real(), imag(), angle() or abs()')
    return _cast_mapping[dtype](_x) 
Example #22
Source File: test_umath_complex.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_simple(self):
        x = np.array([1+0j, 1+2j])
        y_r = np.log(np.abs(x)) + 1j * np.angle(x)
        y = np.log(x)
        for i in range(len(x)):
            assert_almost_equal(y[i], y_r[i]) 
Example #23
Source File: test_core.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_basic_ufuncs(self):
        # Test various functions such as sin, cos.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
        assert_equal(np.cos(x), cos(xm))
        assert_equal(np.cosh(x), cosh(xm))
        assert_equal(np.sin(x), sin(xm))
        assert_equal(np.sinh(x), sinh(xm))
        assert_equal(np.tan(x), tan(xm))
        assert_equal(np.tanh(x), tanh(xm))
        assert_equal(np.sqrt(abs(x)), sqrt(xm))
        assert_equal(np.log(abs(x)), log(xm))
        assert_equal(np.log10(abs(x)), log10(xm))
        assert_equal(np.exp(x), exp(xm))
        assert_equal(np.arcsin(z), arcsin(zm))
        assert_equal(np.arccos(z), arccos(zm))
        assert_equal(np.arctan(z), arctan(zm))
        assert_equal(np.arctan2(x, y), arctan2(xm, ym))
        assert_equal(np.absolute(x), absolute(xm))
        assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym))
        assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True))
        assert_equal(np.equal(x, y), equal(xm, ym))
        assert_equal(np.not_equal(x, y), not_equal(xm, ym))
        assert_equal(np.less(x, y), less(xm, ym))
        assert_equal(np.greater(x, y), greater(xm, ym))
        assert_equal(np.less_equal(x, y), less_equal(xm, ym))
        assert_equal(np.greater_equal(x, y), greater_equal(xm, ym))
        assert_equal(np.conjugate(x), conjugate(xm)) 
Example #24
Source File: audio.py    From vae_tacotron with MIT License 5 votes vote down vote up
def _griffin_lim(S):
  '''librosa implementation of Griffin-Lim
  Based on https://github.com/librosa/librosa/issues/434
  '''
  angles = np.exp(2j * np.pi * np.random.rand(*S.shape))
  S_complex = np.abs(S).astype(np.complex)
  y = _istft(S_complex * angles)
  for i in range(hparams.griffin_lim_iters):
    angles = np.exp(1j * np.angle(_stft(y)))
    y = _istft(S_complex * angles)
  return y 
Example #25
Source File: reco.py    From video-quality with GNU General Public License v2.0 5 votes vote down vote up
def eco(img):
    l10 = Laguerre_Gauss_Circular_Harmonic_1_0(17, 2)
    l30 = Laguerre_Gauss_Circular_Harmonic_3_0(17, 2)
    y10 = scipy.ndimage.filters.convolve(img, numpy.real(l10)) + 1j * scipy.ndimage.filters.convolve(img, numpy.imag(l10))
    y30 = scipy.ndimage.filters.convolve(img, numpy.real(l30)) + 1j * scipy.ndimage.filters.convolve(img, numpy.imag(l30))
    eco = numpy.sum( - (numpy.absolute(y30) * numpy.absolute(y10)) * numpy.cos( numpy.angle(y30) - 3 * numpy.angle(y10) ) )
    return eco 
Example #26
Source File: reco.py    From video-quality with GNU General Public License v2.0 5 votes vote down vote up
def pec(img):
    # TODO scale parameter should depend on resolution
    l10 = Laguerre_Gauss_Circular_Harmonic_1_0(17, 2)
    l30 = Laguerre_Gauss_Circular_Harmonic_3_0(17, 2)
    y10 = scipy.ndimage.filters.convolve(img, numpy.real(l10)) + 1j * scipy.ndimage.filters.convolve(img, numpy.imag(l10))
    y30 = scipy.ndimage.filters.convolve(img, numpy.real(l30)) + 1j * scipy.ndimage.filters.convolve(img, numpy.imag(l30))
    pec_map = - (numpy.absolute(y30) / numpy.absolute(y10)) * numpy.cos( numpy.angle(y30) - 3 * numpy.angle(y10) )
    return pec_map 
Example #27
Source File: test_core.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_basic_ufuncs(self):
        # Test various functions such as sin, cos.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
        assert_equal(np.cos(x), cos(xm))
        assert_equal(np.cosh(x), cosh(xm))
        assert_equal(np.sin(x), sin(xm))
        assert_equal(np.sinh(x), sinh(xm))
        assert_equal(np.tan(x), tan(xm))
        assert_equal(np.tanh(x), tanh(xm))
        assert_equal(np.sqrt(abs(x)), sqrt(xm))
        assert_equal(np.log(abs(x)), log(xm))
        assert_equal(np.log10(abs(x)), log10(xm))
        assert_equal(np.exp(x), exp(xm))
        assert_equal(np.arcsin(z), arcsin(zm))
        assert_equal(np.arccos(z), arccos(zm))
        assert_equal(np.arctan(z), arctan(zm))
        assert_equal(np.arctan2(x, y), arctan2(xm, ym))
        assert_equal(np.absolute(x), absolute(xm))
        assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym))
        assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True))
        assert_equal(np.equal(x, y), equal(xm, ym))
        assert_equal(np.not_equal(x, y), not_equal(xm, ym))
        assert_equal(np.less(x, y), less(xm, ym))
        assert_equal(np.greater(x, y), greater(xm, ym))
        assert_equal(np.less_equal(x, y), less_equal(xm, ym))
        assert_equal(np.greater_equal(x, y), greater_equal(xm, ym))
        assert_equal(np.conjugate(x), conjugate(xm)) 
Example #28
Source File: utils.py    From Tacotron-pytorch with MIT License 5 votes vote down vote up
def _griffin_lim(self, S):
        '''librosa implementation of Griffin-Lim
        Based on https://github.com/librosa/librosa/issues/434
        '''
        angles = np.exp(2j * np.pi * np.random.rand(*S.shape))
        S_complex = np.abs(S).astype(np.complex)
        y = self._istft(S_complex * angles)
        for i in range(self.GL_iter):
          angles = np.exp(1j * np.angle(self._stft(y)))
          y = self._istft(S_complex * angles)
        return y 
Example #29
Source File: angle.py    From mars with Apache License 2.0 5 votes vote down vote up
def angle(z, deg=0, **kwargs):
    """
    Return the angle of the complex argument.

    Parameters
    ----------
    z : array_like
        A complex number or sequence of complex numbers.
    deg : bool, optional
        Return angle in degrees if True, radians if False (default).

    Returns
    -------
    angle : Tensor or scalar
        The counterclockwise angle from the positive real axis on
        the complex plane, with dtype as numpy.float64.

    See Also
    --------
    arctan2
    absolute

    Examples
    --------
    >>> import mars.tensor as mt

    >>> mt.angle([1.0, 1.0j, 1+1j]).execute()               # in radians
    array([ 0.        ,  1.57079633,  0.78539816])
    >>> mt.angle(1+1j, deg=True).execute()                  # in degrees
    45.0

    """
    op = TensorAngle(deg=deg, **kwargs)
    return op(z) 
Example #30
Source File: comp_angle_d_axis.py    From pyleecan with Apache License 2.0 5 votes vote down vote up
def comp_angle_d_axis(self):
    """Compute the angle between the X axis and the first d+ axis
    By convention a "Tooth" is centered on the X axis

    Parameters
    ----------
    self : LamSlotWind
        A LamSlotWind object

    Returns
    -------
    d_angle : float
        angle between the X axis and the first d+ axis
    """

    MMF = self.comp_mmf_unit()
    p = self.get_pole_pair_number()

    # Get the unit mmf FFT and angle values
    results = MMF.get_along("angle")
    angle_rotor = results["angle"]
    results = MMF.get_along("wavenumber")
    wavenumber = results["wavenumber"]
    mmf_ft = results[MMF.symbol]

    # Find the angle where the FFT is max
    indr_fund = np_abs(wavenumber - p).argmin()
    phimax = np_angle(mmf_ft[indr_fund])
    magmax = np_abs(mmf_ft[indr_fund])
    mmf_waveform = magmax * cos(p * angle_rotor + phimax)
    ind_max = argmax(mmf_waveform)
    return angle_rotor[ind_max]