Пример #1
0
    def _calcnewpos(self, deltat):
        if abs(self.angular_velocity) > self.angular_friction * deltat:
            self.angular_velocity = sign(self.angular_velocity) * (
                abs(self.angular_velocity) - self.angular_friction * deltat)
        else:
            self.angular_velocity = 0

        self.last_angle = self.angle
        self.angle += self.angular_velocity * deltat

        self.velocity = np.length(self.velocity) * np.array(
            (math.sin(-self.angle), math.cos(-self.angle)))
        # friction:
        if np.length(
                self.velocity) - self.min_velocity > self.friction * deltat:
            self.velocity *= (np.length(self.velocity) - self.friction *
                              deltat) / np.length(self.velocity)
        #else:
        #    self.velocity = np.array([0., 0.])

        self.velocity[1] = self.velocity[1] + self.gravity * deltat

        # staying in area / wraparound
        if not self.area.colliderect(self.rect):
            self.rect.x %= self.area.w
            self.rect.y %= self.area.h

        deltax = [deltat * V for V in self.velocity]

        return self.rect.move(deltax)
Пример #2
0
    def _calcnewpos(self,deltat):
        if abs(self.angular_velocity) > self.angular_friction * deltat:
            self.angular_velocity = sign(self.angular_velocity) * (abs(self.angular_velocity) - self.angular_friction * deltat)
        else:
            self.angular_velocity = 0

        self.last_angle = self.angle
        self.angle += self.angular_velocity * deltat

        self.velocity = np.length(self.velocity) * np.array((math.sin(-self.angle), math.cos(-self.angle)))
        # friction:
        if np.length(self.velocity) - self.min_velocity > self.friction * deltat:
            self.velocity *= (np.length(self.velocity) - self.friction * deltat) / np.length(self.velocity)
        #else:
        #    self.velocity = np.array([0., 0.])

        self.velocity[1] = self.velocity[1] + self.gravity * deltat

        # staying in area / wraparound
        if not self.area.colliderect(self.rect):
            self.rect.x %= self.area.w
            self.rect.y %= self.area.h

        deltax = [deltat*V for V in self.velocity]

        return self.rect.move(deltax)
Пример #3
0
    def remove_points_based_on_timestamps(self, indexes=[]):
        """Remove data points based on timestamp.

        """
        if indexes == []:
            indexes = self.tids

        for id in indexes:
            begin_chunk = 0
            end_chunk = begin_chunk + 2000
            for i in range(np.length(self.data[id])//2000):
                # Read a 2000 long chunk of data
                begin_chunk = 0*i
                end_chunk = max(begin_chunk+2000, np.length(self.data[id]))
                chunck_times = self.time[id][begin_chunk:end_chunk]
Пример #4
0
def makeState(configuration):
    """
    The function makeState takes argument configuration which specifies the state we want to initialise.

    :param configuration: np.array of length N with 1 meaning up and 0 meaning down, e.g. [1,0,0,1] means up-down-down-up
    :return: np.array of length 2**N, the state vector in full state space
    """
    # Initialising the state vector, which will be represented in the full state space of the chain
    state = 1

    # Defining the states from which our specific state will be constructed from
    up = [1, 0]
    down = [0, 1]

    # The loop below constructs a vector of size 2^N through the Kronecker product
    i = 0
    while i < np.length(configuration):
        if configuration[i] == 0:
            state = scipy.kron(state, down)
            i += 1
        elif configuration[i] == 1:
            state = scipy.kron(state, up)
            i += 1
        else:
            return (
                "The configuration has not been specified correctly, please read the"
                " docstring")

    return state
Пример #5
0
def karatsuba(x, y, a, b, c, d):
    x = str(x)
    y = str(y)
    i = len(x)/2
    i =int(i)
    a = x[0:i]
    b = x[i:]
    j = len(y)/2
    j =int(j)
    c = y[0:j]
    d = y[j:]
    p = a + b
    q = c + d
    ac = np.multiply(a, c)
    bd = np.multiply(b ,d)
    pq = np.multiply(p, q)
    adbc = pq - ac - bd
    
    n = np.length(x + y)    
    if n <= 2:
        result = np.product(x, y)
    else:
        result = np.product(10^(n/2) , ac) + adbc + bd
        
    return result
            
        
    
Пример #6
0
 def calcvelocity(self):
     smax = self.max_velocity
     smin = self.min_velocity
     vmax = self.dp.max_order
     vmin = 4
     v = self.dp.order
     s = (v - vmin) / (vmax - vmin) * (smax - smin) + smin
     self.velocity = self.velocity * s / np.length(self.velocity)
Пример #7
0
 def calcvelocity(self):
     smax = self.max_velocity
     smin = self.min_velocity
     vmax = self.dp.max_order
     vmin = 4
     v = self.dp.order
     s = (v - vmin) / (vmax - vmin) * (smax - smin) + smin
     self.velocity = self.velocity * s / np.length(self.velocity)
Пример #8
0
 def Gradientdescent(x, y,theta,alpha,iters):
     m = np.length(y)
     J_history = np.zeros(iters,1)
     for i in range(iters):
         error =(x*theta)-y
         theta = theta-((alpha/m)*np.transpose(x)*error)
         a = []
         a.append(theta)
     return J_history,theta
Пример #9
0
def temporal_smooth(signal,
                    blocks,
                    snap,
                    inter,
                    delay,
                    multi=[1, 1],
                    aoa=[np.pi / 2, 3 * np.pi / 2]):
    # If you call this fn we assume that the prerequisites are met, i.e. signal is long enough.
    # Assume the signal is already noisy
    rx = np.zeros(blocks, 6, snap)
    for b in range(blocks):
        for k in range(np.length(multi)):
            for p in range(multi(k)):
                if p != 1:
                    h = np.sqrt(0.5) * (np.random.randn + 1j * np.random.randn)
                else:
                    h = 1
                [_1, _1, A] = manifold(aoa, [
                    np.pi / 2 * np.random.rand,
                    2 * np.pi * np.random.rand - np.pi
                ])
                sig = signal[k, 1 + (b - 1) * inter + (p - 1) * delay:snap +
                             (b - 1) * inter + (p - 1) * delay]
                rx[b, :, :] = h * A * sig + np.squeeze(rx[b, :, :])

    R = 1 / snap * np.squeeze(rx[1, :, :]) * np.matrix.H(
        np.squeeze(rx[1, :, :]))  #Normal covariance

    smooth = np.zeros((6, 6))
    r = np.zeros((blocks, 6, 6))

    for b in range(blocks):
        r[b, :, :] = 1 / snap * np.squeeze(rx[b, :, :]) * np.matrix.H(
            np.squeeze(rx[b, :, :]))
        smooth[:, :] = 1 / blocks * np.squeeze(
            r[b, :, :]) + smooth[:, :]  # Temporally smoothed covariance

    return smooth, R
Пример #10
0
 def _calcnewpos(self):
     self.newpos = Active._calcnewpos(self)
     self.pos_delta = np.length(
         np.array(self.newpos) - np.array(self.droppos))
     return self.newpos
Пример #11
0
    def peak2(self, npeaks=2, sc=1, interp=False):
        """
        Find peaks in a matrix

        :param npeaks: number of peaks to return (default all)
        :type npeaks: scalar
        :param sc: scale of peaks to consider
        :type sc: float
        :param interp:  interpolation done on peaks
        :type interp: boolean
        :return: peaks, xy locations, ap? TODO
        :rtype: collections.namedtuple

        - ``IM.peak2()`` are the peak values in the 2-dimensional signal
          ``IM``. Also returns the indices of the maxima in the matrix ``IM``.
          Use SUB2IND to convert these to row and column.

        - ``IM.peak2(npeaks)`` as above with the number of peaks to return
          specifieid (default all).

        - ``IM.peak2(sc)`` as above with scale ``sc`` specified. Only consider
          as peaks the largest value in the horizontal and vertical range +/- S
          units.

        - ``IM.peak2(interp)`` as above with interp specified. Interpolate peak
          (default no peak interpolation).

        Example:

        .. runblock:: pycon

        .. note::

            - A maxima is defined as an element that larger than its eight
              neighbours. Edges elements will never be returned as maxima.
            - To find minima, use PEAK2(-V).
            - The interp options fits points in the neighbourhood about the
              peak with a paraboloid and its peak position is returned.  In
              this case IJ will be non-integer.

        """

        # TODO check valid input

        # create a neighbourhood mask for non-local maxima suppression
        h = sc
        w = 2 * h
        M = np.ones((w, w))
        M[h, h] = 0

        out = []
        for z in self:
            # compute the neighbourhood maximum
            znh = self.window(self.float(z), M, 'max', 'wrap')

            # find all pixels greater than their neighbourhood
            k = np.where(z > znh)

            # sort these local maxima into descending order
            ks = [np.argsort(z, axis=0)][:, :, -1]  # TODO check this
            k = k[ks]

            npks = np.min(np.length(k), npeaks)
            k = k[0:npks]

            y, x = np.unravel_index(k, z.shape)
            xy = np.stack((y, x), axis=2)

            # interpolate peaks if required
            if interp:
                # TODO see peak2.m, line 87-131
                raise ValueError(interp, 'interp not yet supported')
            else:
                xyp = xy
                zp = z(k)
                ap = []

            # TODO should xyp, etc be Images?
            o = namedtuple('peaks', 'xy' 'z' 'a')(xyp, zp, ap)
            out.append(o)

        return out
Пример #12
0
# % Channel parameters
Fade = 1  # = 1 if channel effect is considered, 0 otherwise
v = 1  # Number of paths for Rayleigh channel

# % BER parameters
EbNo_L = 0
EbNo_U = 25
EbNo_dB = np.linspace(EbNo_L, EbNo_U, 10)
EbNo_lin = 10. ** (EbNo_dB / 10)
ber = np.zeros(np.size(EbNo_lin))
SNR_BER_db = EbNo_dB + 10 * np.log10(m / (N + CP))
SNR_BER = 10. ** (SNR_BER_db / np.eldiv / 10)

# % Possible Codeword
Codewords = PossibleCodewords(M, n, k)
C = np.length(Codewords)
# % Generation of binary data
Binary = np.mcat([0, 1])  # Binary data that take 0 or 1
randn(np.mstring('state'), 12345)  # seeding the Matlab random number generator

for j in range[len(EbNo_dB)]:
    j()
    # % Generation of codewords (symbols) from random bits
    InputBinaryS = Binary(np.randsrc(1, Frames * m, np.mslice[1:2]))
    symbols = BitsIntoCodewords(InputBinaryS, m, m1, N, M, n, k, g, Frames)
    # % Channel
    impulse_response = np.zeros(NFFT, Frames)
    if Fade == 1:
        impulse_response(np.mslice[1:v], np.mslice[:]).lvalue = (1 / sqrt(2 * v)) * complex(randn(v, Frames), randn(v,
                                                                                                                    Frames))  # Rayleigh variance = 1
        fading_coeffs = np.fft(impulse_response)
Пример #13
0
ax[0].set_ylabel("订单价格")
ax[0].set_title("酒店订单价格")

sns.barplot(x='o_pay_type',
            y='o_total_price',
            hue='revenue',
            data=hotel_orders_data3,
            ax=ax[1],
            ci=None,
            estimator=np.size,
            order=hotel_orders_data3.groupby("o_pay_type")
            ['o_total_price'].count().sort_values(ascending=False).index,
            hue_order=hotel_orders_data3.groupby("revenue")
            ['o_total_price'].count().sort_values(ascending=False).index)
ax[1].set_xlabel("")
ax[1].set_ylabel("订单数量")
ax[1].set_title("酒店订单数量")

# In[]:
print(set(hotel_orders_data3['o_rt_hotel_room_name']))

unique_label, counts_label, unique_dict = ft.category_quantity_statistics_all(
    hotel_orders_data3['o_rt_hotel_room_name'])

# In[]:
print(np.size(hotel_orders_data3['o_rt_hotel_room_name']))

print(hotel_orders_data3['o_rt_hotel_room_name'].count())

np.length(hotel_orders_data3['o_rt_hotel_room_name'])
Пример #14
0
 def _calcnewpos(self):
     self.newpos = Active._calcnewpos(self)
     self.pos_delta = np.length(np.array(self.newpos) - np.array(self.droppos))
     return self.newpos