Beispiel #1
0
 def findTcrit(self):
     rho = np.array(np.linspace(0, self.rho0, 2000))
     self.checkmat(rho)
     Tmax = 100000
     Tstart = 1000
     Tint = 1000
     while Tint >= 1.:
         self.calculate_B_iso(rho, Tstart)
         zero_crossings = np.where(np.diff(np.signbit(self.B_iso)))[0]
         #print(Tstart,Tint,zero_crossings,len(zero_crossings));
         if len(zero_crossings) == 0:
             Tstart -= Tint
             Tint = Tint * 0.1
         else:
             Tstart += Tint
         if Tstart > Tmax:
             print("Could not find critical temperature Tmax: ", Tmax)
             return 0.0
     self.T_crit = Tstart
     self.calculate_B_iso(rho, Tstart - 1.0)
     self.calculate_P(rho, Tstart - 1.0)
     zero_crossings = np.where(np.diff(np.signbit(self.B_iso)))[0]
     print("Found crit T:", self.T_crit, " rho crit: ", rho[zero_crossings],
           " Pcrit ", self.P[zero_crossings] / 10**9)
     return Tstart
Beispiel #2
0
def test_pos_nan():
    """Check np.nan is a positive nan."""
    if sys.platform == "cli":
        # Not sure why, but Windows/.NET binary format for NaN has MSB set.
        assert np.signbit(np.nan) == 1
    else:
        assert np.signbit(np.nan) == 0
Beispiel #3
0
    def get_foot_pressure_sensors(self, floor):
        """
        Checks if 4 corners of the each feet are in contact with ground

        Indicies for looking from above on the feet plates:
          Left         Right
        4-------5    0-------1
        |   ^   |    |   ^   |      ^
        |   |   |    |   |   |      | : forward direction
        |       |    |       |
        6-------7    2-------3

        :param floor: PyBullet body id of the plane the robot is walking on.
        :return: boolean array of 8 contact points on both feet, True: that point is touching the ground False: otherwise
        """
        locations = [False] * 8
        right_pts = pb.getContactPoints(bodyA=self.body, bodyB=floor, linkIndexA=Links.RIGHT_LEG_6)
        left_pts = pb.getContactPoints(bodyA=self.body, bodyB=floor, linkIndexA=Links.LEFT_LEG_6)
        right_center = np.array(pb.getLinkState(self.body, linkIndex=Links.RIGHT_LEG_6)[4])
        left_center = np.array(pb.getLinkState(self.body, linkIndex=Links.LEFT_LEG_6)[4])
        right_tr = tr.get_rotation_matrix_from_transformation(
            tr(quaternion=pb.getLinkState(self.body, linkIndex=Links.RIGHT_LEG_6)[5]))
        left_tr = tr.get_rotation_matrix_from_transformation(
            tr(quaternion=pb.getLinkState(self.body, linkIndex=Links.LEFT_LEG_6)[5]))
        for point in right_pts:
            index = np.signbit(np.matmul(right_tr, point[5] - right_center))[0:2]
            locations[index[1] + index[0] * 2] = True
        for point in left_pts:
            index = np.signbit(np.matmul(left_tr, point[5] - left_center))[0:2]
            locations[index[1] + (index[0] * 2) + 4] = True
        return locations
    def _feet(self):
        """
        Checks if 4 corners of the each feet are in contact with ground
        Indicies for looking from above on the feet plates:
          Left         Right
        4-------5    0-------1
        |   ^   |    |   ^   |      ^
        |   |   |    |   |   |      | : forward direction
        |       |    |       |
        6-------7    2-------3
        :return: int array of 8 contact points on both feet, 1: that point is touching the ground -1: otherwise
        """
        locations = [-1.] * self._FEET_DIM
        right_pts = pb.getContactPoints(bodyA=self.soccerbotUid, bodyB=self.planeUid, linkIndexA=Links.RIGHT_LEG_6)
        left_pts = pb.getContactPoints(bodyA=self.soccerbotUid, bodyB=self.planeUid, linkIndexA=Links.LEFT_LEG_6)
        right_center = np.array(pb.getLinkState(bodyUniqueId=self.soccerbotUid, linkIndex=Links.RIGHT_LEG_6)[4])
        left_center = np.array(pb.getLinkState(bodyUniqueId=self.soccerbotUid, linkIndex=Links.LEFT_LEG_6)[4])
        right_tr = np.array(pb.getMatrixFromQuaternion(
            pb.getLinkState(bodyUniqueId=self.soccerbotUid, linkIndex=Links.RIGHT_LEG_6)[5])
            , dtype=self.DTYPE).reshape((3, 3))
        left_tr = np.array(pb.getMatrixFromQuaternion(
            pb.getLinkState(bodyUniqueId=self.soccerbotUid, linkIndex=Links.LEFT_LEG_6)[5])
            , dtype=self.DTYPE).reshape((3, 3))
        for point in right_pts:
            index = np.signbit(np.matmul(right_tr, point[5] - right_center))[0:2]
            locations[index[1] + index[0] * 2] = 1.
        for point in left_pts:
            index = np.signbit(np.matmul(left_tr, point[5] - left_center))[0:2]
            locations[index[1] + (index[0] * 2) + 4] = 1.

        for i in range(len(locations)):  # 5% chance of incorrect reading
            locations[i] *= np.sign(self.np_random.uniform(low=- self._FEET_FALSE_CHANCE,
                                                           high=1 - (self._FEET_FALSE_CHANCE)), dtype=self.DTYPE)
        return np.array(locations)
Beispiel #5
0
    def test_signbit(self):
        from numpy import signbit, add, copysign, nan

        assert signbit(add.identity) == False
        assert (signbit([0, 0.0, 1, 1.0, float("inf")]) == [False, False, False, False, False]).all()
        assert (signbit([-0, -0.0, -1, -1.0, float("-inf")]) == [False, True, True, True, True]).all()
        assert (signbit([copysign(nan, 1), copysign(nan, -1)]) == [False, True]).all()
Beispiel #6
0
    def test_nans_infs(self):
        oldsettings = np.seterr(all='ignore')
        try:
            # Check some of the ufuncs
            assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32))
            assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32))
            assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32))
            assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32))
            assert_equal(np.spacing(float16(65504)), np.inf)

            # Check comparisons of all values with NaN
            nan = float16(np.nan)

            assert_(not (self.all_f16 == nan).any())
            assert_(not (nan == self.all_f16).any())

            assert_((self.all_f16 != nan).all())
            assert_((nan != self.all_f16).all())

            assert_(not (self.all_f16 < nan).any())
            assert_(not (nan < self.all_f16).any())

            assert_(not (self.all_f16 <= nan).any())
            assert_(not (nan <= self.all_f16).any())

            assert_(not (self.all_f16 > nan).any())
            assert_(not (nan > self.all_f16).any())

            assert_(not (self.all_f16 >= nan).any())
            assert_(not (nan >= self.all_f16).any())
        finally:
            np.seterr(**oldsettings)
Beispiel #7
0
def pocketGrid(density, universe, atomSel="all"):
    """For an MDAnalysis density and the coresponding universe,
    return an isomorphous grid populated with pocket scores."""

    coords = universe.selectAtoms(atomSel).coordinates()
    nAtoms = coords.shape[0]
    directions = [[1,0,0],
                  [0,1,0],
                  [0,0,1],
                  [1,1,1],
                  [-1,1,1],
                  [1,-1,1],
                  [1,1,-1]]
    grid = np.zeros(density.grid.shape,dtype=np.int8).flatten()

    for i,point in enumerate(density.centers()):
        # Point too close to atoms (ie. is inside the protein)
        if np.linalg.norm(point-coords, axis=1).min()<3.1:
            continue
        for d in directions:
            # distance from each atom to the line from point along d:
            vecs = (point-coords)-(np.dot((point-coords),d)*np.array([d,]*nAtoms).T).T
            dists = np.linalg.norm(vecs, axis=1)
            # the projection from point along d for each bisected atom:
            proj = np.dot((point-coords),d)[np.where(dists<3.1)]
            if np.signbit(proj).all():
                # proj all positive, so not in pocket along d
                continue
            if np.signbit(proj).any():
                # in pocket along d, as proj has both +ve and -ve members
                grid[i] += 1
                continue
            # otherwise proj all -ve, so not in pocket

    return grid.reshape(density.grid.shape)
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1)))
Beispiel #9
0
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1)))
Beispiel #10
0
def test_pos_nan():
    """Check np.nan is a positive nan."""
    if sys.platform == 'cli':
        # Not sure why, but Windows/.NET binary format for NaN has MSB set.
        assert np.signbit(np.nan) == 1
    else:
        assert np.signbit(np.nan) == 0
Beispiel #11
0
    def test_nans_infs(self):
        with np.errstate(all='ignore'):
            # Check some of the ufuncs
            assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32))
            assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32))
            assert_equal(np.isfinite(self.all_f16), np.isfinite(self.all_f32))
            assert_equal(np.signbit(self.all_f16), np.signbit(self.all_f32))
            assert_equal(np.spacing(float16(65504)), np.inf)

            # Check comparisons of all values with NaN
            nan = float16(np.nan)

            assert_(not (self.all_f16 == nan).any())
            assert_(not (nan == self.all_f16).any())

            assert_((self.all_f16 != nan).all())
            assert_((nan != self.all_f16).all())

            assert_(not (self.all_f16 < nan).any())
            assert_(not (nan < self.all_f16).any())

            assert_(not (self.all_f16 <= nan).any())
            assert_(not (nan <= self.all_f16).any())

            assert_(not (self.all_f16 > nan).any())
            assert_(not (nan > self.all_f16).any())

            assert_(not (self.all_f16 >= nan).any())
            assert_(not (nan >= self.all_f16).any())
Beispiel #12
0
 def assertFloatsIdentical(self, a, b):
     # Assert that float instances are equal, and that if they're zero,
     # then the signs match. N.B. we don't care about NaNs.
     self.assertEqual(
         (a, np.signbit(a)),
         (b, np.signbit(b)),
     )
def norm1(x):
    if np.signbit(x.real):
        if np.signbit(x.imag):
            return -x.real - x.imag
        return -x.real + x.imag
    if np.signbit(x.imag):
        return x.real - x.imag
    return x.real + x.imag
 def test_signbit(self):
     from numpy import signbit, add, copysign, nan
     assert signbit(add.identity) == False
     assert (signbit([0, 0.0, 1, 1.0, float('inf')]) ==
             [False, False, False, False, False]).all()
     assert (signbit([-0, -0.0, -1, -1.0, float('-inf')]) ==
             [False,  True,  True,  True,  True]).all()
     assert (signbit([copysign(nan, 1), copysign(nan, -1)]) ==
             [False, True]).all()
Beispiel #15
0
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    old_err = np.seterr(divide="ignore")
    try:
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    finally:
        np.seterr(**old_err)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1)))
Beispiel #16
0
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    old_err = np.seterr(divide="ignore")
    try:
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    finally:
        np.seterr(**old_err)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1)))
Beispiel #17
0
def test_zeros():
    y = sc.sinpi(-0.0)
    assert y == 0.0
    assert np.signbit(y)

    y = sc.sinpi(0.0)
    assert y == 0.0
    assert not np.signbit(y)

    y = sc.cospi(0.5)
    assert y == 0.0
    assert not np.signbit(y)
Beispiel #18
0
def angle_between(v1, v2):
    u1 = v1 / norm(v1)
    u2 = v2 / norm(v2)
    y = u1 - u2
    x = u1 + u2
    a0 = 2 * arctan(norm(y) / norm(x))
    if (not signbit(a0)) or signbit(pi - a0):
        return a0
    elif signbit(a0):
        return 0
    else:
        return pi
Beispiel #19
0
def test_zero_sign():
    y = sinpi(-0.0)
    assert y == 0.0
    assert np.signbit(y)

    y = sinpi(0.0)
    assert y == 0.0
    assert not np.signbit(y)

    y = cospi(0.5)
    assert y == 0.0
    assert not np.signbit(y)
def test_zero_sign():
    y = sinpi(-0.0)
    assert y == 0.0
    assert np.signbit(y)

    y = sinpi(0.0)
    assert y == 0.0
    assert not np.signbit(y)

    y = cospi(0.5)
    assert y == 0.0
    assert not np.signbit(y)
Beispiel #21
0
def adjust_negative_zero(zero, expected):
    """
    Helper to adjust the expected result if we are dividing by -0.0
    as opposed to 0.0
    """
    if np.signbit(np.array(zero)).any():
        # All entries in the `zero` fixture should be either
        #  all-negative or no-negative.
        assert np.signbit(np.array(zero)).all()

        expected *= -1

    return expected
Beispiel #22
0
def test_math_float(dt):
    Amin = A.min()
    Amax = A.max()
    A2 = (2 * (A - Amin) / (Amax - Amin) - 1) * .999
    _A2 = (2 * (_A - Amin) / (Amax - Amin) - 1) * .999
    assert_eq(clip(_A, 0, 1), np.clip(A, 0, 1))
    assert_eq(abs(_O), np.abs(O))
    assert_eq(abs(_A), np.abs(A))
    assert_eq(square(_A), np.square(A))
    assert_eq(round(_A), np.round(A))
    assert_eq(floor(_A), np.floor(A))
    assert_eq(ceil(_A), np.ceil(A))
    assert_close(sin(_A), np.sin(A))
    assert_close(cos(_A), np.cos(A))
    assert_close(tan(_A), np.tan(A))
    assert_close(arcsin(_A2), np.arcsin(A2))
    assert_close(arccos(_A2), np.arccos(A2))
    assert_close(arctan(_A2), np.arctan(A2))
    assert_close(sinh(_A), np.sinh(A))
    assert_close(cosh(_A), np.cosh(A))
    assert_close(tanh(_A), np.tanh(A))
    assert_close(arcsinh(_A2), np.arcsinh(A2))
    assert_close(arccosh(1 + abs(_A2)), np.arccosh(1 + np.abs(A2)))
    assert_close(arctanh(_A2), np.arctanh(A2))
    assert_close(exp(_C), np.exp(C))
    assert_close(exp2(_C), np.exp2(C))
    assert_close(log(_C), np.log(C))
    assert_close(log2(_C), np.log2(C))
    assert_close(logistic(_A), 1 / (1 + np.exp(-A)))

    # Handle sign and sqrt separately...
    if dt == bool:
        assert_eq(sign(_O), np.sign(np.asarray(
            O, dtype=uint8)))  # numpy doesn't support sign on type bool
        assert_eq(sign(_A), np.sign(np.asarray(A, dtype=uint8)))
    else:
        assert_eq(sign(_O), np.sign(O))
        assert_eq(sign(_I), np.sign(I))
        if dt in (int8, int16, int32, int64, float32, float64):
            assert_eq(sign(-_I), np.sign(-I))
        assert_eq(sign(_A), np.sign(A))
        assert_eq(signbit(_O), np.signbit(O, out=np.empty(O.shape, dtype=dt)))
        assert_eq(signbit(_I), np.signbit(I, out=np.empty(I.shape, dtype=dt)))
        if dt in (int8, int16, int32, int64, float32, float64):
            assert_eq(signbit(-_I),
                      np.signbit(-I, out=np.empty(I.shape, dtype=dt)))
        assert_eq(signbit(_A), np.signbit(A, out=np.empty(A.shape, dtype=dt)))
    if dt in dtypes_float:
        assert_close(
            sqrt(abs(_A)), np.sqrt(np.abs(A))
        )  # numpy converts integer types to float16/float32/float64, and we don't want that.
Beispiel #23
0
def get_arg(x, y, x_center, y_center):
    """Calculates the argument for a point relative to a center point
    
    Parameters
    ----------
    x : ``1-D array``
        x coordinate of the point
    y : ``1-D array``
        y coordinate of the point
    x_center : ``1-D array``
        x coordinate of the ellipse's center
    y_center : ``1-D array``
        y coordinate of the ellipse's center
    
    Returns
    -------
    coords : ``1-D array``
        The argument in radians, between 0 and 2*pi
    """
    arg = np.arctan2(y - y_center, x - x_center)
    #Make sure the angle is between 0 and 2*pi
    if np.isscalar(arg):
        if arg < 0:
            arg += 2 * M.pi
    else:
        arg[np.signbit(arg)] += 2 * M.pi
    return arg
 def stopping_conditions(imf,t):
     mins = signal.argrelmin(imf)[0]
     mins_ = [float(data*60/8064) for data in mins]
     maxs = signal.argrelmax(imf)[0]
     maxs_ = [float(data*60/8064) for data in maxs]
     
     spl_min = interpolate.CubicSpline(mins_,imf[mins])#, bc_type = 'natural') #clamped
     spl_max = interpolate.CubicSpline(maxs_, imf[maxs])#, bc_type = 'natural')#clamped
     
     mean_amplitude = [np.abs(spl_max(i)+spl_min(i))/2 for i in range(0,len(t))]
     envelope_amplitude = [np.abs(spl_max(i)- spl_min(i))/2 for i in range(0,len(t))]
     bo = [(m/e > 0.05) for m,e in zip(mean_amplitude,envelope_amplitude)]
     
     #at each point, mean_amplitude < THRESHOLD2*envelope_amplitude
     condition = [not(m < 0.5*e) for m,e in zip(mean_amplitude,envelope_amplitude)]
     
     #mean of boolean array {(mean_amplitude)/(envelope_amplitude) > THRESHOLD} < TOLERANCE
     if((1 in condition) or (not(np.mean(bo)<0.05))):
         return False
     
     # |#zeros-#extrema|<=1
     zero_crossings = np.where(np.diff(np.signbit(imf)))[0]
     diff_zeroCr_extremas = np.abs(len(maxs)+len(mins)-len(zero_crossings))
     if(diff_zeroCr_extremas <= 1):# and mean <0.1):
         return True
     else:
         return False
Beispiel #25
0
def find_zero_crossings(y, height=None, delta=0.):
    """Finds zero crossing indices.

    Parameters
    ----------
    y: array-like
        Signal.
    height: float, optional
        Maximum deviation from zero.
    delta: float, optional
        Prominence value used in `scipy.signal.find_peaks` when `height` is
        specified.

    Returns
    -------
    ind_zer: ndarray
        Zero-crossing indices.
    """
    if height is None:
        ind_zer, = np.where(np.diff(np.signbit(y)))
    else:
        ind_zer, _ = signal.find_peaks(-np.abs(y),
                                       height=-height,
                                       prominence=delta)
    return ind_zer
Beispiel #26
0
def remove_outliers(lists, std_devs=2):
    means = numpy.mean(lists, axis=0)
    stds = numpy.multiply(numpy.array([std_devs] * len(lists[0])), numpy.std(lists, axis=0))
    # data - np.mean(data)) < m * np.std(data)
    # We only want the data if all of the parts are < N std_devs from the mean.
    # Which means abs(data - means) - (N * std_devs) < 0.
    return filter(lambda data: all(numpy.signbit(numpy.subtract(numpy.absolute(numpy.subtract(data, means)), stds))), lists)
Beispiel #27
0
    def general_work(self, input_items, output_items):
        in_stream = input_items[0]
        if (len(in_stream) < 1000):
            return 0
        ## cruzamentos por zero
        in_stream = in_stream[:1000]
        zero_crossings = np.where(np.diff(np.signbit(input_items)))
        size = len(zero_crossings[1])
        zeros_ = []
        zeros_ativo = []

        for x in range(0, size - 2):
            dif = zero_crossings[1][x + 1] - zero_crossings[1][x]
            #pegando apenas diferencas maiores que 5 amostras
            zeros_ativo.append(dif)
            if dif > self.threshold:
                zeros_.append(dif)

        ## pegando o menor valor
        if (len(zeros_)):
            minimo = min(zeros_)
            valor = 1 / (minimo / self.fs)
            self.sps = self.fs / valor
        else:
            self.sps = 0

        #i0 = len(in_stream)
        self.consume(0, 1000)
        #output_items[0][:1] = np.array(buffer_)
        return 0
Beispiel #28
0
def test_wrightomega_singular():
    pts = [complex(-1.0, np.pi),
           complex(-1.0, -np.pi)]
    for p in pts:
        res = sc.wrightomega(p)
        assert_equal(res, -1.0)
        assert_(np.signbit(res.imag) == False)
Beispiel #29
0
    def test_half_ufuncs(self):
        """Test the various ufuncs"""

        a = np.array([0, 1, 2, 4, 2], dtype=float16)
        b = np.array([-2, 5, 1, 4, 3], dtype=float16)
        c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)

        assert_equal(np.add(a, b), [-2, 6, 3, 8, 5])
        assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1])
        assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6])
        assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625])

        assert_equal(np.equal(a, b), [False, False, False, True, False])
        assert_equal(np.not_equal(a, b), [True, True, True, False, True])
        assert_equal(np.less(a, b), [False, True, False, False, True])
        assert_equal(np.less_equal(a, b), [False, True, False, True, True])
        assert_equal(np.greater(a, b), [True, False, True, False, False])
        assert_equal(np.greater_equal(a, b), [True, False, True, True, False])
        assert_equal(np.logical_and(a, b), [False, True, True, True, True])
        assert_equal(np.logical_or(a, b), [True, True, True, True, True])
        assert_equal(np.logical_xor(a, b), [True, False, False, False, False])
        assert_equal(np.logical_not(a), [True, False, False, False, False])

        assert_equal(np.isnan(c), [False, False, False, True, False])
        assert_equal(np.isinf(c), [False, False, True, False, False])
        assert_equal(np.isfinite(c), [True, True, False, False, True])
        assert_equal(np.signbit(b), [True, False, False, False, False])

        assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3])

        assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3])
        x = np.maximum(b, c)
        assert_(np.isnan(x[3]))
        x[3] = 0
        assert_equal(x, [0, 5, 1, 0, 6])
        assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2])
        x = np.minimum(b, c)
        assert_(np.isnan(x[3]))
        x[3] = 0
        assert_equal(x, [-2, -1, -np.inf, 0, 3])
        assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3])
        assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6])
        assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2])
        assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3])

        assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0])
        assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2])
        assert_equal(np.square(b), [4, 25, 1, 16, 9])
        assert_equal(np.reciprocal(b),
                     [-0.5, 0.199951171875, 1, 0.25, 0.333251953125])
        assert_equal(np.ones_like(b), [1, 1, 1, 1, 1])
        assert_equal(np.conjugate(b), b)
        assert_equal(np.absolute(b), [2, 5, 1, 4, 3])
        assert_equal(np.negative(b), [2, -5, -1, -4, -3])
        assert_equal(np.positive(b), b)
        assert_equal(np.sign(b), [-1, 1, 1, 1, 1])
        assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b))
        assert_equal(np.frexp(b),
                     ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2]))
        assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
Beispiel #30
0
def calculate_pitch_CEP(wav_file, frame_dur):
    print("Current wav file: {} ".format(wav_file))
    rate, data = read(wav_file)
    duration = int(len(data) / rate) + 1
    data = (np.sin(2 * np.pi * np.arange(rate * duration) * 110 /
                   rate)).astype(np.float32)
    print(data)
    frame_num = int(len(data) / frame_dur) + 1
    frames = np.zeros((frame_num, frame_dur))
    pitch = np.zeros((frame_num))
    for i in range(frame_num):
        if i == frame_num - 1:
            last_frame_len = (len(data) - frame_dur * i)
            frames[i, :last_frame_len] = data[frame_dur * i:len(data)]
        else:
            frames[i, :] = data[frame_dur * i:frame_dur * (i + 1)]
    #silence detector <1/15 of maximum peak absolute signal value within the utterance, then it's called silence
    signal_peak = np.amax(np.abs(data))
    for i in range(frame_num):
        curr_peak = np.amax(np.abs(frames[i, :]))
        if curr_peak < signal_peak / 12: continue
        zero_crossings_num = len(
            np.where(np.diff(np.signbit(frames[i, :])))[0])
        if zero_crossings_num >= zero_crossing_threshold: continue
        #compute cepstrum
        windowed = np.hamming(frame_dur) * frames[i]
        cep = np.fft.ifft(np.log(np.abs(np.fft.fft(windowed, n=frame_dur))))
        min_interval, max_interval = rate // max_pitch, rate // min_pitch
        pitch_interval = np.argmax(np.square(
            cep[min_interval:max_interval])) + min_interval
        pitch[i] = rate / pitch_interval
        print(i, pitch[i], pitch_interval, min_interval, max_interval)
        plt.plot(np.abs(cep[1:]))
        plt.show()
Beispiel #31
0
def insert_zeros(trace, tt=None):
    '''
    Insert zero locations in data trace and tt vector based on linear fit
    '''

    if tt is None:
        tt = np.arange(len(trace))

    # Find zeros
    zc_idx = np.where(np.diff(np.signbit(trace)))[0]
    x1 = tt[zc_idx]
    x2 = tt[zc_idx + 1]
    y1 = trace[zc_idx]
    y2 = trace[zc_idx + 1]
    a = (y2 - y1) / (x2 - x1)
    tt_zero = x1 - y1 / a

    # split tt and trace
    tt_split = np.split(tt, zc_idx + 1)
    trace_split = np.split(trace, zc_idx + 1)
    tt_zi = tt_split[0]
    trace_zi = trace_split[0]

    # insert zeros in tt and trace
    for i in range(len(tt_zero)):
        tt_zi = np.hstack((tt_zi, np.array([tt_zero[i]]), tt_split[i + 1]))
        trace_zi = np.hstack((trace_zi, np.zeros(1), trace_split[i + 1]))

    return trace_zi, tt_zi
def find_zero_xings(waveform: numpy.ndarray) -> numpy.ndarray:
    """
    Function which returns a boolean array indicating the positions of zero crossings in the the waveform
    :param waveform:
    :return: a boolean array indicating the positions of zero crossings in the the waveform
    """
    return numpy.diff(numpy.signbit(waveform))
Beispiel #33
0
def _single_arm_features(gyr, acc, time):
    crossings_idx = np.where(np.diff(np.signbit(gyr)))[0] + 1
    cols = [
        'start_idx', 'end_idx', 'duration', 'degrees', 'max_velocity', 'jerk'
    ]
    df = pd.DataFrame(index=range(len(crossings_idx) - 1), columns=cols)
    for i in range(len(crossings_idx) - 1):
        st = crossings_idx[i]
        en = crossings_idx[i + 1]
        df.iloc[i]['start_idx'] = st
        df.iloc[i]['end_idx'] = en
        df.iloc[i]['duration'] = (time.iloc[en]['value'] -
                                  time.iloc[st]['value']).total_seconds()
        df.iloc[i]['max_velocity'] = np.max(gyr[st:en])

    # degrees and jerk
    for i in range(len(crossings_idx) - 1):
        st = df.iloc[i]['start_idx']
        en = df.iloc[i]['end_idx']
        t = (time.iloc[st:en]['value']) - time.iloc[st]['value']
        df.iloc[i]['degrees'] = trapz(gyr[st:en], t)

        dt = []
        for j in range(df.iloc[i]['start_idx'], df.iloc[i]['end_idx']):
            dt.append((time.iloc[j + 1]['value'] -
                       time.iloc[j]['value']).total_seconds())
        dx = np.abs(np.diff(acc[st:en + 1]))
        df.iloc[i]['jerk'] = np.mean(
            dx / dt)  # This assumes evenly spaced time series
    return df
Beispiel #34
0
def test_wrightomega_singular():
    pts = [complex(-1.0, np.pi),
           complex(-1.0, -np.pi)]
    for p in pts:
        res = sc.wrightomega(p)
        assert_equal(res, -1.0)
        assert_(np.signbit(res.imag) == False)
Beispiel #35
0
def wiggle(frame, scale=1.0):
        fig = pylab.figure()
        ax = fig.add_subplot(111)        
        ns = frame['ns'][0]
        nt = frame.size
        scalar = scale*frame.size/(frame.size*0.2) #scales the trace amplitudes relative to the number of traces
        frame['trace'][:,-1] = np.nan #set the very last value to nan. this is a lazy way to prevent wrapping
        vals = frame['trace'].ravel() #flat view of the 2d array.
        vect = np.arange(vals.size).astype(np.float) #flat index array, for correctly locating zero crossings in the flat view
        crossing = np.where(np.diff(np.signbit(vals)))[0] #index before zero crossing
        #use linear interpolation to find the zero crossing, i.e. y = mx + c. 
        x1=  vals[crossing]
        x2 =  vals[crossing+1]
        y1 = vect[crossing]
        y2 = vect[crossing+1]
        m = (y2 - y1)/(x2-x1)
        c = y1 - m*x1       
        #tack these values onto the end of the existing data
        x = np.hstack([vals, np.zeros_like(c)])
        y = np.hstack([vect, c])
        #resort the data
        order = np.argsort(y) 
        #shift from amplitudes to plotting coordinates
        x_shift, y = y[order].__divmod__(ns)
        ax.plot(x[order] *scalar + x_shift + 1, y, 'k')
        x[x<0] = np.nan
        x = x[order] *scalar + x_shift + 1
        ax.fill(x,y, 'k', aa=True) 
        ax.set_xlim([0,nt])
        ax.set_ylim([ns,0])
        pylab.tight_layout()
        pylab.show()
    def WriteDataBlock(self,data,codingParams):
        """Writes a block of signed-fraction data to a PCMFile object that has already executed OpenForWriting"""
        # get information about the block to write
        nChannels = len(data)
        if nChannels != codingParams.nChannels: raise Exception("Data block to PCMFile did not have expected number of channels")
        nSamples= min([len(data[iCh]) for iCh in range(nChannels)])  # use shortest length of channel data for nSamples
        bytesToWrite = nChannels*nSamples*(codingParams.bitsPerSample/BYTESIZE)
        # convert data to an array of 2s-complement uniformly quantized codes
        codes = []  # PCM quantized codes will go here
        for iCh in range(nChannels):
            temp = data[iCh]
            signs = np.signbit(temp)  # extract signs
            temp[signs] *= -1.  # now temp is positive
            temp = vQuantizeUniform(temp,16)   # returns 16 bit quantized codes (stored as unsigned ints)
            temp = temp.astype(np.int16)  # now it can take a 2s complement sign (it was unsigned before)
            temp[signs] *= -1  # now quantization code has 2s complement sign attached
            codes.append(temp)  # codes[iCh]
        # interleave the codes to be written out (because that's the WAV format)
        dataBlock = [codes[iCh][iSample] for iSample in xrange(nSamples) for iCh in range(nChannels) ]
        dataBlock = np.asarray(dataBlock, dtype = np.int16)  # notice that this is SIGNED 16-bit int
        # pack the interleaved codes into a block of bytes
        if codingParams.bitsPerSample == 16:
            # Uses '<h' format code in struct to convert short integers into little-endian pairs of bytes
 #           dataString = ""
 #           for i in range(len(dataBlock)):  dataString += pack('<h',dataBlock[i])
            dataString=dataBlock.tostring()  # converts (local Endian) data of dataBlock into a string to write  -- use byteswap() method if wrong Endian
        else: raise Exception("Asked to write to a PCM file with other than 16-bits per sample in PCMFile.WriteDataBlock!")
        # write those bytes to the file and return
        self.fp.write(dataString)
        return
Beispiel #37
0
def pitch_detect_zero_crossing(signal):
    diff_threshold = 50
    zero_crossings = np.where(np.diff(np.signbit(signal)))[0]
    diffs = np.ediff1d(zero_crossings)
    diffs = [d for d in diffs if d > diff_threshold]
    avg = np.mean(diffs)
    return float(RATE)/avg/2.0
def pitch_detect_zero_crossing(signal):
    diff_threshold = 50
    zero_crossings = np.where(np.diff(np.signbit(signal)))[0]
    diffs = np.ediff1d(zero_crossings)
    diffs = [d for d in diffs if d > diff_threshold]
    avg = np.mean(diffs)
    return float(RATE) / avg / 2.0
Beispiel #39
0
def zero_crossings(input_signal):
    """
    Return the indices where the input signal crosses zero.

    Input:
    input_signal (list or numpy array): The signal to be analyzed

    Output:
    crossings_idx (numpy array): Numpy array of the indices where a signal crosses zero.
    area (numpy array): Numpy array of the area defined y=0 and every two consecutive zero crossings.
    """

    # Find zero crossings
    crossings_idx = np.where(np.diff(np.signbit(input_signal)))[0] + 1
    if len(crossings_idx) == 0:
        return None, None

    # Remove crossing at point zero if it exists. Also, no crossing should exist at the last point if it is zero.
    if crossings_idx[0] == 1:
        crossings_idx = np.delete(crossings_idx, 0)

    idx = np.unique(np.append(0, crossings_idx, len(input_signal)))
    area = []
    for i in range(len(idx) - 1):
        st = idx[i]
        en = idx[i + 1]
        area.append(np.sum(input_signal[st:en]))
    return crossings_idx, np.asarray(area)
Beispiel #40
0
def mask_zero_div_zero(x, y, result: np.ndarray) -> np.ndarray:
    """
    Set results of  0 // 0 to np.nan, regardless of the dtypes
    of the numerator or the denominator.

    Parameters
    ----------
    x : ndarray
    y : ndarray
    result : ndarray

    Returns
    -------
    ndarray
        The filled result.

    Examples
    --------
    >>> x = np.array([1, 0, -1], dtype=np.int64)
    >>> x
    array([ 1,  0, -1])
    >>> y = 0       # int 0; numpy behavior is different with float
    >>> result = x // y
    >>> result      # raw numpy result does not fill division by zero
    array([0, 0, 0])
    >>> mask_zero_div_zero(x, y, result)
    array([ inf,  nan, -inf])
    """

    if not hasattr(y, "dtype"):
        # e.g. scalar, tuple
        y = np.array(y)
    if not hasattr(x, "dtype"):
        # e.g scalar, tuple
        x = np.array(x)

    zmask = y == 0

    if zmask.any():

        # Flip sign if necessary for -0.0
        zneg_mask = zmask & np.signbit(y)
        zpos_mask = zmask & ~zneg_mask

        x_lt0 = x < 0
        x_gt0 = x > 0
        nan_mask = zmask & (x == 0)
        with np.errstate(invalid="ignore"):
            neginf_mask = (zpos_mask & x_lt0) | (zneg_mask & x_gt0)
            posinf_mask = (zpos_mask & x_gt0) | (zneg_mask & x_lt0)

        if nan_mask.any() or neginf_mask.any() or posinf_mask.any():
            # Fill negative/0 with -inf, positive/0 with +inf, 0/0 with NaN
            result = result.astype("float64", copy=False)

            result[nan_mask] = np.nan
            result[posinf_mask] = np.inf
            result[neginf_mask] = -np.inf

    return result
Beispiel #41
0
def test_wrightomega_inf_branch():
    pts = [complex(-np.inf, np.pi/4),
           complex(-np.inf, -np.pi/4),
           complex(-np.inf, 3*np.pi/4),
           complex(-np.inf, -3*np.pi/4)]
    for p in pts:
        res = sc.wrightomega(p)
        assert_equal(res, 0)
        if abs(p.imag) <= np.pi/2:
            assert_(np.signbit(res.real) == False)
        else:
            assert_(np.signbit(res.real) == True)
        if p.imag >= 0:
            assert_(np.signbit(res.imag) == False)
        else:
            assert_(np.signbit(res.imag) == True)
Beispiel #42
0
def DecomposeArterialSignal(Ao, Return='all'):
    #Starting work on the arterial signal

    #Start with a moving average of the signal for like a 10 seconds.
    AveAo = Ao.rolling(250 * 10).mean()
    ZeroedAo = Ao - AveAo

    #Count the cumulative number of transitions per time as the heart rate.
    #Convert to numpy for this, the solutions just don't seem as elegant in pandas.
    ZeroedAoArray = ZeroedAo.to_numpy()

    BeatTrace = np.where(np.diff(np.signbit(ZeroedAoArray)))[0] + Ao.index[
        0]  #sync with the experimental time.

    # plt.plot(Ao)
    plt.plot(ZeroedAo)
    plt.vlines(BeatTrace, ymin=-20, ymax=20)
    #detecting the dichrotic notch, need to eliminate points that are too close to other points.
    #High quality Ao signal is needed.

    plt.show()

    # print(BeatTrace)
    # print(len(BeatTrace))
    # print(len(BeatTrace))

    pass
    def ReadDataBlock(self,codingParams):
        """Reads a block of data from a PCMFile object that has already executed OpenForReading and returns those samples as signed-fraction data"""
        # read a block of nSamplesPerBlock*nChannels*bytesPerSample bytes from the file (where nSamples is set by coding file before reading)
        bytesToRead = codingParams.nSamplesPerBlock*codingParams.nChannels*(codingParams.bitsPerSample/BYTESIZE)
        if codingParams.nChannels*codingParams.numSamples*(codingParams.bitsPerSample/BYTESIZE) - codingParams.bytesReadSoFar <= 0:
            dataBlock = None
        elif codingParams.nChannels*codingParams.numSamples*(codingParams.bitsPerSample/BYTESIZE) - codingParams.bytesReadSoFar < bytesToRead:
            dataBlock = self.fp.read(codingParams.nChannels*codingParams.numSamples*(codingParams.bitsPerSample/BYTESIZE) - codingParams.bytesReadSoFar)
        else:
            dataBlock = self.fp.read(bytesToRead)
        codingParams.bytesReadSoFar += bytesToRead
        if dataBlock and len(dataBlock)<bytesToRead:  # got data but not as much as expected
            # this was a partial block, zero pad
            dataBlock += (bytesToRead-len(dataBlock))*"\0"
        elif not dataBlock: return  # stop if nothing read
        # convert block of bytes into block of uniformly quantized codes, dequantize them, and parse into channels
        if codingParams.bitsPerSample == 16:
            # Uses '<h' format code in struct to convert little-endian pairs of bits into short integers
            dataBlock=unpack("<"+str(codingParams.nSamplesPerBlock*codingParams.nChannels)+"h",dataBlock)  # asumes nSamples*nChannels SIGNED short ints
#            dataBlock=np.fromstring(dataBlock,dtype=np.int16)  # uses Local Endian conversion -- use byteswap() method if wrong Endian
        else: raise Exception("PCMFile was not 16-bit PCM in PCMFile.ReadDataBlock!")
        # parse samples into channels and dequantize into signed-fraction floating point numbers
        data = [] # this is where the signed-fraction samples will reside for each channel
        for iCh in range(codingParams.nChannels):
            # slice out this channel's interleaved 16-bit PCM codes (and make sure it is a numpy array)
            codes = np.asarray(dataBlock[iCh::codingParams.nChannels])
            # extract signs
            signs = np.signbit(codes)
            codes[signs] *= -1  # now codes are positive
            # dequantize, return signs, and put result as data[iCh]
            temp = vDequantizeUniform(codes,16)
            temp[signs] *= -1.  # returns signs
            data.append(temp)  # data[iCh]
        # return data
        return data
Beispiel #44
0
def test_math_float(dt):
    Amin = A.min()
    Amax = A.max()
    A2  = (2*( A-Amin)/(Amax-Amin)-1)*.999
    _A2 = (2*(_A-Amin)/(Amax-Amin)-1)*.999
    assert_eq(clip(_A,0,1),np.clip(A,0,1))
    assert_eq(abs(_O),     np.abs(O))
    assert_eq(abs(_A),     np.abs(A))
    assert_eq(square(_A),  np.square(A))
    assert_eq(round(_A),   np.round(A))
    assert_eq(floor(_A),   np.floor(A))
    assert_eq(ceil(_A),    np.ceil(A))
    assert_close(sin(_A),  np.sin(A))
    assert_close(cos(_A),  np.cos(A))
    assert_close(tan(_A),  np.tan(A))
    assert_close(arcsin(_A2), np.arcsin(A2))
    assert_close(arccos(_A2), np.arccos(A2))
    assert_close(arctan(_A2), np.arctan(A2))
    assert_close(sinh(_A),  np.sinh(A))
    assert_close(cosh(_A),  np.cosh(A))
    assert_close(tanh(_A),  np.tanh(A))
    assert_close(arcsinh(_A2), np.arcsinh(A2))
    assert_close(arccosh(1+abs(_A2)), np.arccosh(1+np.abs(A2)))
    assert_close(arctanh(_A2), np.arctanh(A2))
    assert_close(exp(_C),  np.exp(C))
    assert_close(exp2(_C), np.exp2(C))
    assert_close(log(_C),  np.log(C))
    assert_close(log2(_C), np.log2(C))
    assert_close(logistic(_A), 1 / (1 + np.exp(-A)))

    # Handle sign and sqrt separately...
    if dt == bool:
        assert_eq(sign(_O), np.sign(np.asarray(O,dtype=uint8)))  # numpy doesn't support sign on type bool
        assert_eq(sign(_A), np.sign(np.asarray(A,dtype=uint8))) 
    else:
        assert_eq(sign(_O), np.sign(O))
        assert_eq(sign(_I), np.sign(I))
        if dt in (int8,int16,int32,int64,float32,float64):
            assert_eq(sign(-_I), np.sign(-I))
        assert_eq(sign(_A), np.sign(A))
        assert_eq(signbit(_O), np.signbit(O,out=np.empty(O.shape,dtype=dt)))
        assert_eq(signbit(_I), np.signbit(I,out=np.empty(I.shape,dtype=dt)))
        if dt in (int8,int16,int32,int64,float32,float64):
            assert_eq(signbit(-_I), np.signbit(-I,out=np.empty(I.shape,dtype=dt)))
        assert_eq(signbit(_A), np.signbit(A,out=np.empty(A.shape,dtype=dt)))
    if dt in dtypes_float:
        assert_close(sqrt(abs(_A)),np.sqrt(np.abs(A)))  # numpy converts integer types to float16/float32/float64, and we don't want that.
    def test_half_ufuncs(self):
        """Test the various ufuncs"""

        a = np.array([0, 1, 2, 4, 2], dtype=float16)
        b = np.array([-2, 5, 1, 4, 3], dtype=float16)
        c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)

        assert_equal(np.add(a, b), [-2, 6, 3, 8, 5])
        assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1])
        assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6])
        assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625])

        assert_equal(np.equal(a, b), [False, False, False, True, False])
        assert_equal(np.not_equal(a, b), [True, True, True, False, True])
        assert_equal(np.less(a, b), [False, True, False, False, True])
        assert_equal(np.less_equal(a, b), [False, True, False, True, True])
        assert_equal(np.greater(a, b), [True, False, True, False, False])
        assert_equal(np.greater_equal(a, b), [True, False, True, True, False])
        assert_equal(np.logical_and(a, b), [False, True, True, True, True])
        assert_equal(np.logical_or(a, b), [True, True, True, True, True])
        assert_equal(np.logical_xor(a, b), [True, False, False, False, False])
        assert_equal(np.logical_not(a), [True, False, False, False, False])

        assert_equal(np.isnan(c), [False, False, False, True, False])
        assert_equal(np.isinf(c), [False, False, True, False, False])
        assert_equal(np.isfinite(c), [True, True, False, False, True])
        assert_equal(np.signbit(b), [True, False, False, False, False])

        assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3])

        assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3])
        x = np.maximum(b, c)
        assert_(np.isnan(x[3]))
        x[3] = 0
        assert_equal(x, [0, 5, 1, 0, 6])
        assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2])
        x = np.minimum(b, c)
        assert_(np.isnan(x[3]))
        x[3] = 0
        assert_equal(x, [-2, -1, -np.inf, 0, 3])
        assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3])
        assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6])
        assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2])
        assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3])

        assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0])
        assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2])
        assert_equal(np.divmod(a, b), ([0, 0, 2, 1, 0], [0, 1, 0, 0, 2]))
        assert_equal(np.square(b), [4, 25, 1, 16, 9])
        assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125])
        assert_equal(np.ones_like(b), [1, 1, 1, 1, 1])
        assert_equal(np.conjugate(b), b)
        assert_equal(np.absolute(b), [2, 5, 1, 4, 3])
        assert_equal(np.negative(b), [2, -5, -1, -4, -3])
        assert_equal(np.positive(b), b)
        assert_equal(np.sign(b), [-1, 1, 1, 1, 1])
        assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b))
        assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2]))
        assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])
Beispiel #46
0
def yCrossingSegPoints(data, yThresh=0, xBetweenSegs=1, yBetweenSegs=1):
	prev = data[0]
	segPoints = []
	canSegment = True
	candidate = None
	for i,d in enumerate(data):
		if len(segPoints) > 0 and abs(d-data[segPoints[-1]]) >= yBetweenSegs/2.0:
			canSegment = True
			if candidate and abs(candidate[0]-segPoints[-1]) >= xBetweenSegs:
				pass;#segPoints += candidate
		if np.signbit(prev-yThresh) != np.signbit(d-yThresh):
			candidate = [i]
			if canSegment and (len(segPoints) == 0 or abs(candidate[0]-segPoints[-1]) >= xBetweenSegs):
				segPoints += candidate
				canSegment = False
		prev = d
	return segPoints
def calc_global_tc(event_generator, calib, pixel, gain, cell_width_guess):
    f_calib = 30e6 # in Hz
    unit_of_ti = 1e-9 # in seconds
    nominal_period = 1 / (f_calib * unit_of_ti)

    cell_width = np.copy(cell_width_guess) 
    T = cell_width.sum()
    stop_cells = np.zeros(1024, dtype=int)

    number_of_zxings_per_cell = np.zeros(1024, dtype=int)

    for event in tqdm(event_generator):
        event = calib(event)
        calibrated = event.data[pixel][gain]
        stop_cell = event.header.stop_cells[pixel][gain]
        stop_cells[stop_cell % 1024] += 1
        zero_crossings = np.where(np.diff(np.signbit(calibrated)))[0]
        number_of_zxings_per_cell[(zero_crossings+stop_cell)%1024] += 1

        for zxing_type in [zero_crossings[0::2], zero_crossings[1::2]]:
            for start, end in zip(zxing_type[:-1], zxing_type[1:]):

                N = end - start + 1
                weights = np.zeros(1024)
                weights[(stop_cell + start + np.arange(N))%1024] = 1.
                weights[(stop_cell + start)%1024] = 1 - weight_on_edge(calibrated, start)
                weights[(stop_cell + end)%1024] = weight_on_edge(calibrated, end)

                measured_period = (weights * cell_width).sum()
                if measured_period < nominal_period*0.7 or measured_period > nominal_period*1.3:
                    continue

                n0 = nominal_period / measured_period
                n1 = (T - nominal_period) / (T - measured_period)

                correction = n0 * weights + n1 * (1-weights)
                cell_width *= correction

                # The next line is fishy:
                #   * it should not be possibl to have a width < 0, but Ritt has shown it is.
                #   * cells more than double their nominal size, seem impossible, but one cell with 200% width
                #       can easily be accomplished with 10 cells having only 90% their nominal width.
                #  Never the less, without this line, the result can become increadibly shitty!
                cell_width = np.clip(cell_width, 0, 2)  
                cell_width /= cell_width.mean()


    # Regarding the uncertainty of the cell width, we assume that the correction should become
    # smaller and smaller, the more interations we perform.
    # so the last corrections should be very close to 1. 

    tc = pd.DataFrame({
        "cell_width_mean": np.roll(cell_width, 1),
        "cell_width_std": np.zeros(1024),  # np.full((len(cell_width), np.nan)
        "number_of_crossings": number_of_zxings_per_cell,
        "stop_cell": stop_cells,
        })
    return tc
Beispiel #48
0
def count_runs(v):
	pos = np.signbit(v)
	runs = 0
	prev = pos[0]
	for x in np.nditer(pos):
		if prev != x:
			prev = not prev # =x
			runs += 1
	return runs
    def __get_zero_crossings__(self, signals):

        # get # zero crossings for each file
        crossings = []
        for data in signals:
            crossings.append(len(numpy.where(numpy.diff(numpy.signbit(data)))[0]))

        med_crossings = numpy.median(crossings)
        return med_crossings
Beispiel #50
0
    def _repr_latex_(self):
        # get the scaled argument string to the basis functions
        off, scale = self.mapparms()
        if off == 0 and scale == 1:
            term = 'x'
            needs_parens = False
        elif scale == 1:
            term = '{} + x'.format(
                self._repr_latex_scalar(off)
            )
            needs_parens = True
        elif off == 0:
            term = '{}x'.format(
                self._repr_latex_scalar(scale)
            )
            needs_parens = True
        else:
            term = '{} + {}x'.format(
                self._repr_latex_scalar(off),
                self._repr_latex_scalar(scale)
            )
            needs_parens = True

        mute = r"\color{{LightGray}}{{{}}}".format

        parts = []
        for i, c in enumerate(self.coef):
            # prevent duplication of + and - signs
            if i == 0:
                coef_str = '{}'.format(self._repr_latex_scalar(c))
            elif not isinstance(c, numbers.Real):
                coef_str = ' + ({})'.format(self._repr_latex_scalar(c))
            elif not np.signbit(c):
                coef_str = ' + {}'.format(self._repr_latex_scalar(c))
            else:
                coef_str = ' - {}'.format(self._repr_latex_scalar(-c))

            # produce the string for the term
            term_str = self._repr_latex_term(i, term, needs_parens)
            if term_str == '1':
                part = coef_str
            else:
                part = r'{}\,{}'.format(coef_str, term_str)

            if c == 0:
                part = mute(part)

            parts.append(part)

        if parts:
            body = ''.join(parts)
        else:
            # in case somehow there are no coefficients at all
            body = '0'

        return r'$x \mapsto {}$'.format(body)
Beispiel #51
0
 def findZeroCrossings(selfs,image,axis=0):
     (x,y) = image.shape
     image = image.reshape(x * y)
     crossings = np.where(np.diff(np.signbit(image)))[axis]
     print crossings
     out = np.zeros(x * y)
     for c in crossings:
         out[c] = abs(image[c]) + abs(image[c + 1])
     out = out.reshape(x, y)
     return out
def signbitToStr(b):
    '''
    Take numerical expression and return whether it evaluates to
    being Negative or not in a string
    :param b:
    '''
    if(np.signbit(b)):
        return "Negative"
    else:
        return "Non-negative"
Beispiel #53
0
def intersectIn(X1, X2, P):
    """
    Check whether point, P=(x,y), is on line within X1 and X2.

    INPUT:
      X1, X2 ... points X1=(x1,y1) and X2=(x2,y2) defining a line
      P ........ point P=(x,y) 

    RETURN:
      isOnLine ... True if P is between X1 and X2
    """
    acc = 0.002

    Xl2 = X2 - X1
    Pl = P - X1
    #print "Xl2, Pl ", Xl2, Pl

    if(numpy.signbit(Pl[0]) != numpy.signbit(Xl2[0])):
        #print '1'
        return(False)
    # end   if(...

    if(numpy.signbit(Pl[1]) != numpy.signbit(Xl2[1])):
        #print '2'
        return(False)
    # end   if(...

    if(not numpy.signbit(Pl[0]) and (Pl[0] > Xl2[0])
       and (abs(Pl[0] - Xl2[0]) > acc)):
        #print '3'
        return(False)
    # end   if(...

    if(not numpy.signbit(Pl[1]) and (Pl[1] > Xl2[1])
       and (abs(Pl[1] - Xl2[1]) > acc)):
        #print '4'
        return(False)
    # end   if(...

    if(numpy.signbit(Pl[0]) and (Pl[0] < Xl2[0])
       and (abs(Pl[0] - Xl2[0]) > acc)):
        #print '5'
        return(False)
    # end   if(...

    if(numpy.signbit(Pl[1]) and (Pl[1] < Xl2[1])
       and (abs(Pl[1] - Xl2[1]) > acc)):
        #print '6'
        return(False)
    # end   if(...

    return(True)
Beispiel #54
0
def slope_sign_changes(x, threshold=0, axis=-1, keepdims=False):
    """Computes the number of slope sign changes (SSC) of each signal.

    A slope sign change occurs when the middle value of a group of three
    adjacent values in the signal is either greater than or less than both of
    the other two.

    Parameters
    ----------
    x : ndarray
        Input data. Use the ``axis`` argument to specify the "time axis".
    threshold : float, optional
        A threshold for discriminating true slope sign changes from those
        caused by low-level noise fluctuating about a specific value. By
        default, no threshold is used, so every slope sign change in the signal
        is counted.
    axis : int, optional
        The axis to compute the feature along. By default, it is computed along
        rows, so the input is assumed to be shape (n_channels, n_samples).
    keepdims : bool, optional
        Whether or not to keep the dimensionality of the input. That is, if the
        input is 2D, the output will be 2D even if a dimension collapses to
        size 1.

    Returns
    -------
    y : ndarray, shape (n_channels,)
        SSC of each channel.

    References
    ----------
    .. [1] B. Hudgins, P. Parker, and R. N. Scott, "A New Strategy for
       Multifunction Myoelectric Control," IEEE Transactions on Biomedical
       Engineering, vol. 40, no. 1, pp. 82-94, 1993.
    """
    diffs = np.diff(x, axis=axis)
    # transpose the diffs so rolling window works
    adj_diffs = rolling_window(np.swapaxes(np.absolute(diffs), -1, axis), 2)

    # sum to count boolean values which indicate slope sign changes
    return np.sum(
        # two conditions need to be met
        np.logical_and(
            # 1. sign of the diff changes from one pair of samples to the next
            np.diff(np.signbit(diffs), axis=axis),
            # 2. the max of two adjacent diffs is bigger than threshold
            # the transpose here is to un-transpose adj_diffs
            np.swapaxes(np.max(adj_diffs, axis=-1), -1, axis) > threshold),
        axis=axis, keepdims=keepdims)
def calc_local_tc(event_generator, calib, pixel, gain):
    all_slopes = [[] for i in range(1024)]
    stop_cells = np.zeros(1024, dtype=int)

    for event in tqdm(event_generator):
        event = calib(event)
        calibrated = event.data[pixel][gain]
        
        zero_crossings = np.where(np.diff(np.signbit(calibrated)))[0]
        slopes = calibrated[zero_crossings + 1] - calibrated[zero_crossings]
        absolute_slopes = np.abs(slopes)

        sc = event.header.stop_cells[pixel][gain]
        stop_cells[sc%1024] += 1
        zero_crossing_cells = dr.sample2cell(zero_crossings+1, 
            stop_cell=sc,
            total_cells=1024)
        
        for abs_slope, cell_id in zip(absolute_slopes, zero_crossing_cells):
            all_slopes[cell_id].append(abs_slope)

    tc = pd.DataFrame({
            "cell_width_mean": np.zeros(len(all_slopes), dtype=np.float32),
            "cell_width_std": np.zeros(len(all_slopes), dtype=np.float32),
            "number_of_crossings": np.zeros(len(all_slopes), dtype=np.int32),
            "stop_cell": stop_cells,
            "slope_mean": np.zeros(len(all_slopes), dtype=np.float32),
        })
    for cell_id, slopes in enumerate(all_slopes):
        slopes = np.array(slopes)
        tc.loc[cell_id, "number_of_crossings"] = len(slopes)
        tc.loc[cell_id, "cell_width_mean"] = np.mean(slopes) # np.median(slopes)
        tc.loc[cell_id, "slope_mean"] = slopes.mean()
        if False:
            plt.hist(slopes, bins=50, histtype="step")
            plt.title(str(len(slopes)))
            ax = plt.gca()
            ax.ticklabel_format(useOffset=False)
            plt.savefig("slopes/{0:04d}.png".format(cell_id))
            plt.close("all")
        
        tc.loc[cell_id, "cell_width_std"] = slopes.std() / np.sqrt(len(slopes))


    average_of_all_slopes = tc.cell_width_mean.dropna().mean()
    tc["cell_width_mean"] /= average_of_all_slopes
    tc["cell_width_std"]  /= average_of_all_slopes

    return tc
Beispiel #56
0
def generate_events(sample_stream):
	"""Make events for 0-crossings.

	sample_stream must be a generator of CHANNELS-tuples of values that
		represent the current microphone level.
	Yields channel ID, time tuples.
	"""
	last_samples_sign = None
	for timestep, samples in enumerate(sample_stream):
		samples_sign = signbit(samples)
		if last_samples_sign is not None:
			sign_changes = logical_xor(last_samples_sign, samples_sign)
			for channel, sign_change in enumerate(sign_changes):
				if sign_change:
					yield channel, float(timestep) / float(SAMPLE_RATE_HERTZ)
		last_samples_sign = samples_sign
Beispiel #57
0
def load_vorobonds(fname):
    """load the bond network from a custom output of Voro++ '%i %v %s %n'"""
    #load all bonds
    bonds = np.vstack([np.column_stack((
	int(line.split()[0])*np.ones(int(line.split()[2]), int),
	map(int, line.split()[3:])
	)) for line in open(fname)])
    walls = np.signbit(bonds.min(axis=-1))
    outside = np.unique1d(bonds[walls].max(axis=-1))
    #remove the walls and the duplicates
    bonds = bonds[np.bitwise_and(
	np.diff(bonds, axis=-1)[:,0]>0,
	np.bitwise_not(walls)
	)]
    #sort by second then first column
    return bonds[np.lexsort(bonds.T[::-1].tolist())], outside
def compute_zcr(file, windowLength=512, windowHop= 256):
    """
    Compute the Zero Crossing Rate of an audio signal.

    file: an instance of the AudioFile class.
    windowLength: size of the sliding window (samples)
    windowHop: size of the lag window (samples)

    return: a list of values (number of zero crossing for each window)
    """


    sig = file.sig_int # Signal on integer values

    times = range(0, len(sig)- windowLength +1, windowHop)
    frames = [sig[i:i+windowLength] for i in times]
    return [len(np.where(np.diff(np.signbit(x)))[0])/float(windowLength) for x in frames]
Beispiel #59
0
    def __call__(self, location, step):
        """takes a step just past the edge of the next voxel along step

        given a location and a step, finds the smallest step needed to move
        into the next voxel

        Parameters
        ----------
        location : ndarray, (3,)
            location to integrate from
        step : ndarray, (3,)
            direction in 3 space to integrate along
        """
        step_sizes = self.voxel_size * (~np.signbit(step))
        step_sizes -= location % self.voxel_size
        step_sizes /= step
        smallest_step = min(step_sizes) + self.overstep
        return location + smallest_step * step
Beispiel #60
0
def zero_crossings(x, threshold=0, axis=-1, keepdims=False):
    """Computes the number of zero crossings (ZC) of each signal.

    A zero crossing occurs when two adjacent values (in time) of the signal
    have opposite sign. A threshold is used to mitigate the effect of noise
    around zero. It is used as a measure of frequency information.

    Parameters
    ----------
    x : ndarray
        Input data. Use the ``axis`` argument to specify the "time axis".
    threshold : float, optional
        A threshold for discriminating true zero crossings from those caused
        by low-level noise situated about zero. By default, no threshold is
        used, so every sign change in the signal is counted.
    axis : int, optional
        The axis to compute the feature along. By default, it is computed along
        rows, so the input is assumed to be shape (n_channels, n_samples).
    keepdims : bool, optional
        Whether or not to keep the dimensionality of the input. That is, if the
        input is 2D, the output will be 2D even if a dimension collapses to
        size 1.

    Returns
    -------
    y : ndarray, shape (n_channels,)
        ZC of each channel.

    References
    ----------
    .. [1] B. Hudgins, P. Parker, and R. N. Scott, "A New Strategy for
       Multifunction Myoelectric Control," IEEE Transactions on Biomedical
       Engineering, vol. 40, no. 1, pp. 82-94, 1993.
    """
    # sum to count boolean values which indicate slope sign changes
    return np.sum(
        # two conditions:
        np.logical_and(
            # 1. sign changes from one sample to the next
            np.diff(np.signbit(x), axis=axis),
            # 2. difference between adjacent samples bigger than threshold
            np.absolute(np.diff(x, axis=axis)) > threshold),
        axis=axis,
        keepdims=keepdims)