Ejemplo n.º 1
0
def get_stroke_angle(t, f, amp, u, v, k, phase=0.5 * PI):
    """
    Stroke position function w/ J. Wang's shape parameter. The control input 
    u adds a asymmetric velicty to the stroke positon fuction, while the control
    input v adds changes the mean stroke position.

    Arguments:
        t     = array of time points (s)
        f     = flapping frequency (Hz)
        amp   = stroke amplitude 
        u     = control input, scalar or array
        v     = control input, s
        k     = shape parameter near 0 => sine wave, near 1=> sawtooth
    """
    f1 = f / (2 * u)
    f2 = 1 / (2 / f - 1 / f1)
    phi_A = amp / scipy.arcsin(k) * scipy.arcsin(
        k * scipy.sin(2 * PI * f1 * scipy.fmod(t, 1 / f) + phase))
    phi_B = amp / scipy.arcsin(k) * scipy.arcsin(
        k * scipy.sin(2 * PI * f2 * (1 / (2 * f2) - 1 /
                                     (2 * f1) + scipy.fmod(t, 1 / f)) + phase))
    phi = phi_A * (scipy.fmod(t, 1 / f) < 1 /
                   (2 * f1)) + phi_B * (scipy.fmod(t, 1 / f) >= 1 /
                                        (2 * f1)) + v
    return phi
Ejemplo n.º 2
0
def get_likelihood_map(obj_name, pts, polygons, prior_cond, prior, mymap):
    free_pts = array(mymap.get_free_locations())

    print "w x h", mymap.get_map_width(), mymap.get_map_height()
    likelihood_map = zeros([mymap.get_map_width(),
                            mymap.get_map_height()]) * 1.0

    #if there are none
    if (len(free_pts) == 0):
        return

    #when we iterate through them
    for i in range(len(free_pts[0])):
        if (fmod(i, 100) == 0):
            print "i=", i, " of ", len(free_pts[0]), " grid cells"
        #print "free pts", free_pts
        #print "free pts:", free_pts[:,i]
        x, y = free_pts[:, i]
        vpts = get_visible_points([x, y], pts, mymap)
        vpolys = get_visible_polygons([x, y], polygons, mymap)
        vpolys.extend(vpts)

        i, j = mymap.to_index([x, y])
        #print "i, j-->", i, j

        #compute the posterior
        v, l1, l2 = compute_log_posterior(obj_name, prior_cond, prior, vpolys)
        likelihood_map[i, j] = v

        #for v in vpolys:
        #    print v.tag,
        #print ""
        #raw_input()
    return likelihood_map
Ejemplo n.º 3
0
def isPrime(n):
    """This function test with the numpy and scipy libs if n is a prime number.
    """
    maxTest = numpy.ceil(scipy.sqrt(n) + 1)
    d = 2
    while d <= maxTest:
        if 0 == scipy.fmod(n, d):
            return False
        d += 1
    return True
Ejemplo n.º 4
0
 def set_dorsal_delay_kine(self,
                           t,
                           f,
                           phase_delay,
                           amp_stroke,
                           amp_rotation,
                           k_stroke=DFLT_K_STROKE,
                           k_rotation=DFLT_K_ROTATION,
                           rotation_offset=DFLT_ROTATION_OFFSET):
     """
     Sets current kinematics to those with a different velocity on the upstroke
     and downstroke. The amount of offset is determined by the control input u.
     """
     phase0 = scipy.zeros(t.shape)
     T = scipy.fmod(t, 1 / f)
     phase = (phase0 + phase_delay *
              ((T >= .25 / f) * (T < .75 / f) - (1.0 - 10.0 * f *
                                                 (T - .25 / f)) *
               (T >= .25 / f) * (T < .35 / f) - 10.0 * f * (T - .65 / f) *
               (T >= .65 / f) * (T < .75 / f)))
     ro_0, ro_1 = -rotation_offset, rotation_offset
     num_motors = self.num_motors()
     kine = scipy.zeros((t.shape[0], num_motors))
     s0 = self.get_motor_num('stroke_0')
     s1 = self.get_motor_num('stroke_1')
     r0 = self.get_motor_num('rotation_0')
     r1 = self.get_motor_num('rotation_1')
     d0 = self.get_motor_num('deviation_0')
     d1 = self.get_motor_num('deviation_1')
     kine[:, s0] = get_stroke_angle(t, f, amp_stroke, 0.5, 0.0, k_stroke)
     kine[:, s1] = get_stroke_angle(t, f, amp_stroke, 0.5, 0.0, k_stroke)
     kine[:, r0] = get_rotation_angle(t,
                                      f,
                                      amp_rotation,
                                      ro_0,
                                      k_rotation,
                                      phase=phase)
     kine[:, r1] = get_rotation_angle(t,
                                      f,
                                      amp_rotation,
                                      ro_1,
                                      k_rotation,
                                      phase=phase)
     kine[:, d0] = get_deviation_angle(t, f, 0.0)
     kine[:, d1] = get_deviation_angle(t, f, 0.0)
     self.kine = kine
     self.t = t
Ejemplo n.º 5
0
def sin_seq(A = 1.0, f = 1.0, T = 1.0, delta = 0.1):
    t = 0.0
    events = []
    # Note use of round() to compensate for floating-point arithmetic errors
    # that lead to inexact results.
    while t <= T:
        v = delta * floor(round(A*sin(2*pi*f*t) / delta,10))
        events += [(t, v)]
        tm = fmod(abs(t), 0.5/f)
        if tm < 0.25/f:
            vq = delta * (floor(round(A*sin(2*pi*f*tm) / delta,10)) + 1.0)
            dt = arcsin(vq/A)/(2*pi*f) - tm
        else:
            vq = delta * (floor(round(A*sin(2*pi*f*tm) / delta,10)) - 1.0)
            dt = (pi - arcsin(vq/A))/(2*pi*f) - tm             
        t += dt
    return array(events)
Ejemplo n.º 6
0
def int2binary(x, width=32):
    """Convert integer to binary array
    
    Parameters
    -----------
    x : int
    width : int
        Width of binary representation.
    
    Returns
    ----------
    y : (width, ) ndarray
         Vector of boolean values for binary representation.
    
    """
    conv = sp.power(2, sp.arange(1 - width, 1))
    y = sp.fmod(sp.floor(x * conv), 2).astype(bool)
    return y
Ejemplo n.º 7
0
def diagnosticos():
    """Funcion que genera los graficos de las distintas
       cantidades fisicas en un paso de tiempo determinado
       por el usuario"""
    global rhoe, Ex, npuntos_malla, itiempo, longitud_malla, rho0, aP, v1, v2, F
    global EnergiaK, EnergiaP, EnergiaT, emax
    global iout, igrafica, ifase, ivdist, distribucion
    global Archivos_Densidades, Archivos_Campo, Archivos_Efase, Archivos_Fdistribucion

    # Se crea el eje para graficar las cantidades fisicas involucradas:
    xgrafica = dx * sp.arange(npuntos_malla + 1)

    if (itiempo == 0):
        plt.figure('Cantidades')
        plt.clf()

    if (igrafica > 0):
        # Se grafica cada paso dado por el contador igrafica:
        if (sp.fmod(itiempo, igrafica) == 0):
            # Densidad total
            plt.figure(1)
            if (itiempo > 0): plt.cla()
            plt.plot(xgrafica, -(rhoe + rho0), 'r', label='Densidad')
            plt.xlabel('x')
            plt.xlim(0, longitud_malla)
            plt.ylim(-1.5, 1.5)
            plt.legend(loc=1)
            # Se imprimen y se guardan las imagenes de acuerdo a iout:
            plt.pause(0.0001)
            plt.draw()
            filename = '%0*d_densidad' % (5, itiempo)
            Archivos_Densidades[itiempo] = filename
            if (iout > 0):
                if (sp.fmod(itiempo, iout) == 0):
                    plt.savefig(filename + '.png', dpi=720)

            # Campo electrico
            plt.figure(2)
            if (itiempo > 0): plt.cla()
            plt.plot(xgrafica, Ex, 'b', label='Ex')
            plt.xlabel('x', fontsize=18)
            plt.ylabel('Ex', fontsize=18)
            plt.xticks(np.linspace(0, 16, 4), fontsize=18)
            plt.yticks(np.linspace(-0.0010, 0.0010, 5), fontsize=18)
            plt.xlim(0, longitud_malla)
            plt.ylim(-0.0015, 0.0015)
            plt.legend(loc=1)
            # Se imprimen y se guardan las imagenes de acuerdo a iout:
            plt.pause(0.0001)
            plt.draw()
            filename = '%0*d_campoelectrico' % (5, itiempo)
            Archivos_Campo[itiempo] = filename
            if (iout > 0):
                if (sp.fmod(itiempo, iout) == 0):
                    plt.savefig(filename + '.png', dpi=720)

            if (ifase > 0):
                if (sp.fmod(itiempo, ifase) == 0):
                    # Se grafica el espacio de fase en el paso dado por el contador ifase:
                    plt.figure(3)
                    if (itiempo > 0): plt.cla()
                    v1 = sp.zeros(nparticulas)
                    v2 = sp.zeros(nparticulas)
                    x1 = sp.zeros(nparticulas)
                    x2 = sp.zeros(nparticulas)
                    for i in range(nparticulas):
                        if (v[i - 1] > v[i]):
                            v1[i] = v[i]
                            x1[i] = x[i]
                        elif (v[i - 1] < v[i]):
                            v2[i] = v[i]
                            x2[i] = x[i]
                    if (distribucion == 0):
                        plt.scatter(x, v, marker='.', s=0.1, color='black')
                    elif (distribucion == 1 or distribucion == 2):
                        plt.scatter(x1, v1, marker='.', s=0.1, color='red')
                        plt.scatter(x2, v2, marker='.', s=0.1, color='blue')
                        plt.xticks(np.linspace(0, 100, 6), fontsize=18)
                        plt.yticks(np.linspace(-8, 8, 5), fontsize=18)
                        plt.xlabel('x', fontsize=18)
                        plt.ylabel('v', fontsize=18)
                    plt.xlim(0, longitud_malla)
                    plt.ylim(-4, 8)

                    # Se imprimen y se guardan las imagenes de acuerdo a iout:
                    plt.pause(0.0001)
                    plt.draw()
                    filename = '%0*d_espaciofase' % (5, itiempo)
                    Archivos_Efase[itiempo] = filename
                    if (iout > 0):
                        if (sp.fmod(itiempo, iout) == 0):
                            plt.savefig(filename + '.png', dpi=240)

            if (ivdist > 0):
                if (sp.fmod(itiempo, ivdist) == 0):
                    plt.figure(4)
                    if (itiempo > 0): plt.cla()
                    plt.scatter(v, F, marker='.', s=0.1, color='green')
                    plt.xlim(-5 * vh, 5 * vh)
                    plt.ylim(0, 1.0)
                    plt.xlabel('v')
                    plt.ylabel('f(v)')
                    #fn_vdist = 'vdist_%0*d'%(5, itiempo)
                    # Se imprimen y se guardan las imagenes de acuerdo a iout:
                    plt.pause(0.0001)
                    plt.draw()
                    filename = '%0*d_fdistribucion' % (5, itiempo)
                    Archivos_Fdistribucion[itiempo] = filename
                    if (iout > 0):
                        if (sp.fmod(itiempo, iout) == 0):
                            plt.savefig(filename + '.png', dpi=720)
                        #Se escriben los datos de la distribucion en un archivo:
#                    sp.savetxt(fn_vdist, sp.column_stack((v,F)),fmt=('%1.4e','%1.4e'))

# Energia cinetica:
    v2 = v**2
    EnergiaK[itiempo] = 0.5 * masa * sum(v2)

    # Energia potencial:
    e2 = Ex**2
    EnergiaP[itiempo] = 0.5 * dx * sum(e2)
    emax = max(Ex)  # Campo maximo para analisis de inestabilidad

    # Energia total:
    EnergiaT[itiempo] = EnergiaP[itiempo] + EnergiaK[itiempo]

    return True