In [1]:
import numpy as np

In [2]:
from matplotlib import pyplot as plt

In [3]:
%matplotlib inline

In [4]:
# %load Multiple_Coll_01.py
import numpy as np
from matplotlib import pyplot as plt
def orto(x):
    if np.dot(x,x) == 0:
        return 'No se puede: ese es el vector cero!'
    else:
        if 0 not in x:
            v1 = 1
            v2 = -(x[0]/x[1])
            v3 = 0
            #return np.array([v1,v2,v3])
        else:
            if x[0] == 0:
                if x[1] == 0:
                    v1 = 1
                    v2 = 0
                    v3 = 0
                else:
                    v1 = 0
                    v2 = 0
                    v3 = 1
            elif x[1] == 0:
                v1 = 0
                v2 = 1
                v3 = 0
            else:
                v1 = 0
                v2 = 0
                v3 = 1
        return np.array([v1,v2,v3])
    
#Funcion que regresa dos vectores; numpy arrays de 3D, ortogonales al vector de input x.
#Esto es, devuelven la base al espacio ortogonal definido por el vector x de entrada.
#@jit
def base_ort_nor(x):
    y = orto(x)
    v1 = y/np.linalg.norm(y)
    z = np.cross(x,v1)
    v2 = z/np.linalg.norm(z)
    return v1, v2


#Esta funcion genera un vector con distrubucion uniforme en las direcciones sobre un plano tangente a la esfera de radio R.
#@jit
def vector_des(v1,v2):
    na = 2*np.pi*np.random.rand()
    vn = v1*np.cos(na) + v2*np.sin(na)
    return vn/np.linalg.norm(vn)

R = 1

#Normalizamos al vector de desplazamiento para que intersecte al vector de la nueva posicion de acuerdo con que el
#desplazamiento (s) sobre la esfera, sobre este arco de circulo maximo, sea el determinado por el movimiento browniano particular.
#@jit
def vector_q(x,s):
    q = (R)*np.tan(s/(R))
    return q*x

#Dados todos los datos anteriores, esta funcion actualiza la posicion de la particula.
#Lo que hace es que la mueve sobre el plano tangente a la esfera en la direccion predeterminada de tal suerte que el desplazamiento efectivo
#s sobre una geodesica de la esfera, se el deseado, y posteriormente la proyecta sobre la superficie de la esfera.
#@jit
def nuevo_r(r, vector_q):
    y = r + vector_q
    y = y/np.linalg.norm(y)
    return (R)*y

#Esta funcion ensambla todo lo anterior: como imput necesita una posicion inicial y un arco de desplazamiento
#Como output da un vector de posicion nuevo dada un tipo de desplazamiento.
#@jit
def actualiza(r,s):
    v1, v2 = base_ort_nor(r)
    pre_q = vector_des(v1,v2)
    q = vector_q(pre_q, s)
    return nuevo_r(r, q)


#Esta funcion actualiza la posicion de todos los elementos de una lista; particula brownianas.
#@jit
def act_n(lista,s):
    l = []
    for v in lista:
        l.append(actualiza(v,s))
    return l

#Huella de la trayectoria
#La siguiente funcion hace una particion de la trayectoria sobre s en n pedazos y regresa
#una lista de los vectores de esas posiciones sobre la esfera.
#Usa al operador de rotacion.

#@jit
def b_steps_(ri,rf,n):
    l = [ri]
    r0 = ri
    lamb = (np.dot(ri,rf))/((np.linalg.norm(ri))*(np.linalg.norm(rf)))
    
    if abs(lamb) > 1:
        #print 'Is fucked up: there was a rounding '
        if lamb < 0:
            lamb = -1
        else:
            lamb = 1
    
    
    
    theta = np.arccos(lamb)
    #if theta < 1e17:
        #return l
    if theta == 0:
        return [ri,rf]
    
    else:

        normal = np.cross(ri, rf)/ np.linalg.norm(np.cross(ri,rf))
        for i in range(1,n + 1):
            #vi = rot_theta(r0, theta/n, normal)
            vi = rot_finita(r0, -normal, theta/n)
            l.append(vi)
            r0 = vi
        return l


#Operador de Rotacion
#Depende de los parametros r, el vector o punto que queremos rotar; theta el angulo de rotacion; n el vector que define el eje de rotacion y el signo de rotacion.


#@jit
def rot_theta(r, theta, u):
    x = np.array([np.cos(theta) + (u[0]*u[0])*(1 - np.cos(theta)), u[0]*u[1]*(1 - np.cos(theta)) - u[2]*np.sin(theta), u[0]*u[2]*(1 - np.cos(theta)) + u[1]*np.sin(theta)])
    y = np.array([u[1]*u[0]*(1 - np.cos(theta)) + u[2]*np.sin(theta), np.cos(theta) + u[1]*u[1]*(1 - np.cos(theta)), u[1]*u[2]*(1 - np.cos(theta)) - u[0]*np.sin(theta)])
    z = np.array([u[2]*u[0]*(1 - np.cos(theta)) - u[1]*np.sin(theta), u[2]*u[1]*(1 - np.cos(theta)) + u[0]*np.sin(theta), np.cos(theta) + u[2]*u[2]*(1 - np.cos(theta))])
    R = np.array([x,y,z])
    return np.dot(R, r)



#Transformacion de coordenada de esfericas a cartesianas.

#@jit
def trans_s_c(r,theta, phi):
    x = r*np.sin(theta)*np.cos(phi)
    y = r*np.sin(theta)* np.sin(phi)
    z = r*np.cos(theta)
    return x, y, z


#Transformacion de coordenadas de cartesianas a esfericas.
#@jit
def trans_c_s(x,y,z):
    r = np.sqrt(x**2 + y**2 + z**2)
    #print r
    cociente = z/r
    if abs(cociente) > 1:
        if cociente < 0:
            theta = np.arccos(-1)
        else:
            theta = np.arccos(1)
    else:
        
        theta = np.arccos(z/r)
        
    phi = np.arctan(y/x)
    return r, theta, phi



#@jit
def r_uni(theta, phi):
    x = np.sin(theta)*np.cos(phi)
    y = np.cos(theta)*np.cos(phi)
    z = np.cos(theta)
    return np.array([x,y,z])
#@jit
def theta_uni(theta, phi):
    x = np.cos(theta)*np.cos(phi)
    y = np.cos(theta)*np.sin(phi)
    z = -np.sin(theta)
    return np.array([x,y,z])
#@jit
def phi_uni(theta, phi):
    x = -np.sin(phi)
    y = np.cos(phi)
    z = 0
    return np.array([x,y,z])

#@jit
def nombre(s):
    diferencia = 4 - len(str(s))
    ceros = '' 
    for i in range(diferencia):
        ceros = ceros + '0'
    variable = ceros + str(s)
    return variable

#Varianza para una distribucion bigaussiana; difusion en 2D
#@jit
def var(D, delta_t):
    return 4*D*delta_t


#Arco de circulo maximo con distribucion normal alrededor de cero y una varianza dada por
#@jit
def ese(D,delta_t):
    return abs(np.random.normal(loc = 0., scale = np.sqrt(var(D,delta_t)),size = None))

#Funcion de rotacion finita
#@jit
def rot_finita(r_ini, N, Phi):
    n = N/np.linalg.norm(N)
    r_fin = np.cos(Phi)*r_ini + (np.dot(n,r_ini))*(1 - np.cos(Phi))*n + (np.sin(Phi))*(np.cross(r_ini,n))
    return r_fin


#Funcion que regresa una lista de n numpy arrays que son l
def Trayectoria(ri,rf,n):
    l = [ri]
    r0 = ri
    theta = np.arccos((np.dot(ri,rf))/((np.linalg.norm(ri))*(np.linalg.norm(rf))))
    N = np.cross(ri, rf)
    
    for i in range(1,n + 1):
        vi = rot_finita(r0, N, theta/n)
        l.append(vi)
        r0 = vi
    return l

#Collision_check es una función que, dada una trayectoria: una lista de vectores que
#pasan por puntos sucesivos de la trayectoria, verifica si alguna de estas posiciones
#interesecto a alguno de los obstáculos. En caso de que así sea, actualiza conforme una
#colision elastica. En caso de no intersectar a ningun obstaculo regresa una lista
#con dos vectores: posicion inicial y posicion final en ese orden.
#@jit
def penetrate_obs(lista_vect, lista_obs, size):
    metiches = []
    for obs in lista_obs:
        theta_omega = size
        r_omega = obs
        frontera = .2
        #metiches = []
        for v in lista_vect:
            tamanho = np.cos(theta_omega - frontera)
            if np.dot(v,r_omega) > tamanho:
                print 'Penetro el mother fucker obstacle'
                metiches.append(v)
                
            else:
                continue
    #print 'no choco el mother fucker'
    #valor = False
    return metiches


#Esta funcion cuando es llamada grafia la posicion de las partoculas brownianas.
#sobre la superficie de una esfera sobre la que se esta difundiendo.
#@jit
def plot_particles(lista, vpolar, vazim, numero):
    from mpl_toolkits.mplot3d import axes3d
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm

    #import matplotlib.pyplot as plt
    #import numpy as np
    from itertools import product, combinations
    fig = plt.figure(figsize=(20,10))
    ax = fig.gca(projection='3d')
    ax.set_aspect("equal")
    ax._axis3don = False

    



    #draw sphere
    R = 1
    u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
    x=R*np.cos(u)*np.sin(v)
    y=R*np.sin(u)*np.sin(v)
    z=R*np.cos(v)
    #ax.plot_surface(x, y, z, color="r", alpha = 0.15)

    ax.plot_surface(x, y, z, cmap=cm.YlGnBu_r,rstride=1, cstride=1, alpha = 0.10, linewidth = 0.15)
    ax.view_init(vpolar, vazim)
    
    
    #draw an arrow or a set of arrow
    ax.quiver(0,0,1.5,0,0,1, length=0.5, arrow_length_ratio = .5)
    #draw patch
    #u, v = np.mgrid[0:2*np.pi:50j, 0:(np.pi/7):50j]
    #x=R*np.cos(u)*np.sin(v)
    #y=R*np.sin(u)*np.sin(v)
    #z=R*np.cos(v)
    #ax.plot_surface(x, y, z, color="r", alpha = 0.25)    
    
    #draw points
    for p in lista:
        ax.scatter([p[0]],[p[1]],[p[2]],color="b",s=50, alpha = 0.6)
    
    #fig.savefig('Obs_Dist_Images{}.png'.format(nombre(numero)))
    #ax.view_init(80, 30)
    plt.show()
    #plt.close()

    
    
#@jit
def polo_n(n, R):
    l = []
    for i in range(n):
        l.append(np.array([0,0,R]))
    return l

#@jit
def particion_esfera(ccero, Nphi):
    Ntheta = int(4*np.pi/(ccero*Nphi))
    print 'Ntheta', Ntheta, 'Nphi', Nphi, 'Ntheta*Nphi', Ntheta*Nphi
    sigmaPhi = 2*np.pi/Nphi
    deltaphi = 2*np.pi/Nphi
    thetas = []
    phis = [0]
    cociente = ccero/sigmaPhi
    for i in range(Ntheta + 1):
        theta = np.arccos(1 - (i)*cociente)
        thetas.append(theta)
    for j in range(Nphi):
        phis.append(phis[j] + deltaphi)
    return thetas, phis

#@jit
def secuencia_part(tamini, Nfi, numero):
    l1, l2 = particion_esfera(4*np.pi/tamini, Nfi)
    particion = []
    for i in range(len(l2)):
        for j in range(len(l1)):
            x, y, z = trans_s_c(1, l1[j], l2[i])
            particion.append(np.array([x, y, z]))
            
    return plot_particles(particion, 45, 45, numero)

#Funcion que regresa las coordenadas del centro de dos arreglos para 
#las coordenadas theta y phi
#@jit
def coordenadas_centro(l1,l2):
    thetas_centro = []
    phis_centro = []
    for i in range(len(l1) - 1):
        theta_media = l1[i] + (l1[i + 1] - l1[i])/2.
        thetas_centro.append(theta_media)
    for j in range(len(l2) - 1):
        phi_media = l2[j] + (l2[j + 1] - l2[j])/2.
        phis_centro.append(phi_media)
    return thetas_centro, phis_centro

#@jit(nopython=True)
def secuencia_obs(N, Nfi, numero):
    l1_prima, l2_prima = particion_esfera(4*np.pi/N, Nfi)
    l1, l2 = coordenadas_centro(l1_prima, l2_prima)
    particion = []
    for i in range(len(l2)):
        for j in range(len(l1)):
            x, y, z = trans_s_c(1, l1[j], l2[i])
            particion.append(np.array([x, y, z]))
            
    print len(particion)
    
    #return plot_particles(particion, 0, 0, numero)
    return particion


def plot_particle_traj_obs(lista_obstaculos, trayectoria,  vpolar, vazim, numero):
    from mpl_toolkits.mplot3d import axes3d
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm

    #import matplotlib.pyplot as plt
    #import numpy as np
    from itertools import product, combinations
    fig = plt.figure(figsize=(20,10))
    ax = fig.gca(projection='3d')
    ax.set_aspect("equal")
    ax._axis3don = False
    

    



    #draw sphere
    R = 1
    u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
    x=R*np.cos(u)*np.sin(v)
    y=R*np.sin(u)*np.sin(v)
    z=R*np.cos(v)
    #ax.plot_surface(x, y, z, color="r", alpha = 0.15)

    ax.plot_surface(x, y, z, cmap=cm.YlGnBu_r,rstride=1, cstride=1, alpha = 0.10, linewidth = 0.15)
    ax.view_init(vpolar, vazim)
    #draw patch
    #u, v = np.mgrid[0:2*np.pi:50j, 0:(np.pi/7):50j]
    #x=R*np.cos(u)*np.sin(v)
    #y=R*np.sin(u)*np.sin(v)
    #z=R*np.cos(v)
    #ax.plot_surface(x, y, z, color="r", alpha = 0.25)
    
    
    
    #draw obstacles
    
    for p in lista_obstaculos:
        ax.scatter([p[0]],[p[1]],[p[2]], color="b", s=10, alpha = 0.2)
    
    #draw trajectory
    for p in trayectoria:
        ax.scatter([p[0]],[p[1]],[p[2]], color="k",s=20, alpha = 0.7)
    
    #Plot the x positive direction
    
    ax.quiver(1.5,0,0,1,0,0, length=0.5, arrow_length_ratio = .5)
    ax.quiver(0,1.5,0,0,1,0, length=0.5, arrow_length_ratio = .5)
    ax.quiver(0,0,1.5,0,0,1, length=0.5, arrow_length_ratio = .5)
    
    #fig.savefig('BS_24_Obs_test_01{}.png'.format(nombre(numero + 1)))
    #ax.view_init(80, 30)
    #plt.close()
    plt.show()

def obs_uniforme(N, R, size):
    
    list_obs = []
    omega = np.cos(size)
    while len(list_obs) < N:
        x, y, z = np.random.uniform(-1,1), np.random.uniform(-1,1), np.random.uniform(-1,1)
        v = np.array([x, y, z])
        norma = np.linalg.norm(v)
        if norma <= R:
            n = v/norma
            if not np.dot(n, np.array([0.,0.,1.]))/R > omega:
                list_obs.append(R*n)
    
    return list_obs    


def puntos_obs_j(r_omega, theta_omega, n):
    r , theta, phi = trans_c_s(r_omega[0],r_omega[1],r_omega[2])
    rp = rot_finita(r_omega, phi_uni(theta, phi), theta_omega)
    puntos_obs_j = [rp]
    for i in range(1,n):
        x = rot_finita(rp, r_omega, 2*np.pi/n)
        puntos_obs_j.append(x)
        rp = x
    return puntos_obs_j



def puntos_obs(lista_obstaculos, size):
    mis_obs = []
    for i in range(len(lista_obstaculos)):
        a = lista_obstaculos[i]
        b = size
        mis_obs = mis_obs + puntos_obs_j(a,b,100)
    return mis_obs
#Collision_check es una función que, dada una trayectoria: una lista de vectores que
#pasan por puntos sucesivos de la trayectoria, verifica si alguna de estas posiciones
#interesecto a alguno de los obstáculos. En caso de que así sea, actualiza conforme una
#colision elastica. En caso de no intersectar a ningun obstaculo regresa una lista
#con dos vectores: posicion inicial y posicion final en ese orden.

def penetrate_obs(lista_vect, lista_obs, size):
    metiches = []
    for obs in lista_obs:
        r_omega, theta_omega = obs, size
        #frontera = .2
        #metiches = []
        for v in lista_vect:
            tamanho = np.cos(theta_omega)
            if np.dot(v,r_omega) >= tamanho:
                #print 'Penetro el mother fucker obstacle'
                metiches.append(v)
                
            else:
                continue
    #print 'no choco el mother fucker'
    #valor = False
    return metiches
    

def check_collision(lista_vect, lista_obs, size):
    for obs in lista_obs:
        r_omega, theta_omega = obs, size 
        for v in lista_vect:
            tamanho = np.cos(theta_omega)
            if np.dot(v,r_omega) > tamanho:
                return  True
            else:
                continue
    return False

In [5]:
def tangent_space(x1,x2,xo):
    np_prima = np.cross(np.cross(xo, x1), x1)
    nor_p = np_prima/np.linalg.norm(np_prima)
    up_prima = np.cross(np.cross(x1, x2), x1)
    up = up_prima/np.linalg.norm(up_prima)
    tp_prima = np.cross(x1, nor_p)
    tp = tp_prima/np.linalg.norm(tp_prima)
    y = (np.dot(up,tp))*tp - (np.dot(up, nor_p))*nor_p
    v_rot_prima = np.cross(x1, y)
    v_rot = v_rot_prima/np.linalg.norm(v_rot_prima)
    return v_rot

In [6]:
def collision_check(Lv, Lo, size):
    if len(Lv) == 1:
        return Lv[0], Lv[0], 0
    
    elif len(Lv) == 2:
        sproduct = np.dot(Lv[0], Lv[1])
        if abs(sproduct) > 1:
            if sproduct < 0:
                sproduct = -1.
            else:
                sproduct = 1.
                
        alpha = np.arccos(sproduct)
        for obs in Lo:
            r_o = obs
            if np.dot(Lv[1],r_o) > np.cos(size):
                v_rot = tangent_space(Lv[0], Lv[1], r_o)
                x_final = rot_finita(Lv[1], -v_rot, alpha)
                return Lv[1], x_final, 0
    else:
        for k in range(1,len(Lv)):
            for obs in Lo:
                r_o = obs
                if np.dot(Lv[k],r_o) > np.cos(size):
                    v_rot = tangent_space(Lv[0], Lv[k], r_o)
                    
                    if k == len(Lv) - 1:
                        sproduct = np.dot(Lv[k-1], Lv[k])
                        if abs(sproduct) > 1:
                            if sproduct < 0:
                                sproduct = -1.
                        else:
                            sproduct = 1.
                        
                        
                    
                    else:
                        sproduct = np.dot(Lv[k], Lv[-1])
                        if abs(sproduct) > 1:
                            if sproduct < 0:
                                sproduct = -1.
                            else:
                                sproduct = 1.
                    alpha = np.arccos(sproduct)
                    
                    x_final = rot_finita(Lv[k], -v_rot, alpha)
                    return Lv[k], x_final, k
        return Lv[0], Lv[-1], 0

In [ ]:


In [ ]:

Posiciones iniciales


In [7]:
def uniform_inside_omega(N, R, size):
    
    list_obs = []
    omega = np.cos(size)
    while len(list_obs) < N:
        x, y, z = np.random.uniform(-1,1), np.random.uniform(-1,1), np.random.uniform(-1,1)
        v = np.array([x, y, z])
        norma = np.linalg.norm(v)
        if norma <= R:
            n = v/norma
            if not np.dot(n, np.array([0.,0.,1.]))/R < omega:
                list_obs.append(R*n)
    
    return list_obs

In [ ]:


In [49]:
D = 1e-2
dt = (2.3**2/4.)*1e-5
theta1 = 0.4
theta2 = 0.1

In [ ]:


In [50]:
pos_ini = uniform_inside_omega(100,1, theta1)

In [51]:
plot_particles(pos_ini,90,0,1)



In [9]:


In [21]:



Out[21]:
2.3025850929940459

In [ ]:


In [ ]:


In [ ]:


In [60]:
#Simulacion del Primer tiempo de salida para una region de tamaño.
pos_ini = uniform_inside_omega(10000,1, theta1-0.05)
tiempo = 0
tiempos_salida = []
tamanho = np.cos(theta1)
r_omega = np.array([0,0,1])
#plot_particles(pos_ini,90,0,1)
frozen = []
#plot_particle_Region_frozen(estructura_obs, pos_ini, frozen, 90, 0, 1)
for i in range(10000):
    tiempo = tiempo + dt
    nuevas_pos = act_n(pos_ini, ese(D,dt))
    #plot_particles(nuevas_pos, 90,0,1)
    #plot_particle_Region_frozen(estructura_obs, nuevas_pos, frozen, 90, 0, 1)
    survey = []
    for v in nuevas_pos:
        if np.dot(r_omega, v) <= tamanho:
            tiempos_salida.append(tiempo)
            frozen.append(v)
        else:
            survey.append(v)
    if len(survey) == 0:
        break
    else:
        pos_ini = survey


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-60-774bf7df55ed> in <module>()
     12     nuevas_pos = act_n(pos_ini, ese(D,dt))
     13     #plot_particles(nuevas_pos, 90,0,1)
---> 14     plot_particle_Region_frozen(estructura_obs, nuevas_pos, frozen, 90, 0, 1)
     15     survey = []
     16     for v in nuevas_pos:

<ipython-input-59-648099f2fea7> in plot_particle_Region_frozen(lista_region, trayectoria, lista_frozen, vpolar, vazim, numero)
     46 
     47     for p in lista_frozen:
---> 48         ax.scatter([p[0]],[p[1]],[p[2]], color="r", s=17, alpha = 1.0)
     49 
     50     #draw trajectory

/Users/adriano/anaconda/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.pyc in scatter(self, xs, ys, zs, zdir, s, c, depthshade, *args, **kwargs)
   2241         xs, ys, zs, s, c = cbook.delete_masked_points(xs, ys, zs, s, c)
   2242 
-> 2243         patches = Axes.scatter(self, xs, ys, s=s, c=c, *args, **kwargs)
   2244         if not cbook.iterable(zs):
   2245             is_2d = True

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, **kwargs)
   3672             self.set_ymargin(0.05)
   3673 
-> 3674         self.add_collection(collection)
   3675         self.autoscale_view()
   3676 

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/axes/_base.pyc in add_collection(self, collection, autolim)
   1472 
   1473         if collection.get_clip_path() is None:
-> 1474             collection.set_clip_path(self.patch)
   1475 
   1476         if autolim:

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/artist.pyc in set_clip_path(self, path, transform)
    585             if isinstance(path, Rectangle):
    586                 self.clipbox = TransformedBbox(Bbox.unit(),
--> 587                                               path.get_transform())
    588                 self._clippath = None
    589                 success = True

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/patches.pyc in get_transform(self)
    188         to the :class:`Patch`.
    189         """
--> 190         return self.get_patch_transform() + artist.Artist.get_transform(self)
    191 
    192     def get_data_transform(self):

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/patches.pyc in get_patch_transform(self)
    624 
    625     def get_patch_transform(self):
--> 626         self._update_patch_transform()
    627         return self._rect_transform
    628 

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/patches.pyc in _update_patch_transform(self)
    620         rot_trans = transforms.Affine2D()
    621         rot_trans.rotate_deg_around(x, y, self._angle)
--> 622         self._rect_transform = transforms.BboxTransformTo(bbox)
    623         self._rect_transform += rot_trans
    624 

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/transforms.pyc in __init__(self, boxout, **kwargs)
   2475         Affine2DBase.__init__(self, **kwargs)
   2476         self._boxout = boxout
-> 2477         self.set_children(boxout)
   2478         self._mtx = None
   2479         self._inverted = None

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/transforms.pyc in set_children(self, *children)
    167         """
    168         for child in children:
--> 169             child._parents[id(self)] = self
    170 
    171     if DEBUG:

/Users/adriano/anaconda/lib/python2.7/weakref.pyc in __setitem__(self, key, value)
     99         if self._pending_removals:
    100             self._commit_removals()
--> 101         self.data[key] = KeyedRef(value, self._remove, key)
    102 
    103     def clear(self):

/Users/adriano/anaconda/lib/python2.7/weakref.pyc in __new__(type, ob, callback, key)
    261 
    262     def __new__(type, ob, callback, key):
--> 263         self = ref.__new__(type, ob, callback)
    264         self.key = key
    265         return self

KeyboardInterrupt: 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/Users/adriano/anaconda/lib/python2.7/site-packages/IPython/core/formatters.pyc in __call__(self, obj)
    328                 pass
    329             else:
--> 330                 return printer(obj)
    331             # Finally look for special method names
    332             method = _safe_get_formatter_method(obj, self.print_method)

/Users/adriano/anaconda/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in <lambda>(fig)
    205 
    206     if 'png' in formats:
--> 207         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    208     if 'retina' in formats or 'png2x' in formats:
    209         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

/Users/adriano/anaconda/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in print_figure(fig, fmt, bbox_inches, **kwargs)
    115 
    116     bytes_io = BytesIO()
--> 117     fig.canvas.print_figure(bytes_io, **kw)
    118     data = bytes_io.getvalue()
    119     if fmt == 'svg':

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/backend_bases.pyc in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2156                     orientation=orientation,
   2157                     dryrun=True,
-> 2158                     **kwargs)
   2159                 renderer = self.figure._cachedRenderer
   2160                 bbox_inches = self.figure.get_tightbbox(renderer)

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in print_png(self, filename_or_obj, *args, **kwargs)
    519 
    520     def print_png(self, filename_or_obj, *args, **kwargs):
--> 521         FigureCanvasAgg.draw(self)
    522         renderer = self.get_renderer()
    523         original_dpi = renderer.dpi

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.pyc in draw(self)
    467 
    468         try:
--> 469             self.figure.draw(self.renderer)
    470         finally:
    471             RendererAgg.lock.release()

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/artist.pyc in draw_wrapper(artist, renderer, *args, **kwargs)
     57     def draw_wrapper(artist, renderer, *args, **kwargs):
     58         before(artist, renderer)
---> 59         draw(artist, renderer, *args, **kwargs)
     60         after(artist, renderer)
     61 

/Users/adriano/anaconda/lib/python2.7/site-packages/matplotlib/figure.pyc in draw(self, renderer)
   1083         dsu.sort(key=itemgetter(0))
   1084         for zorder, a, func, args in dsu:
-> 1085             func(*args)
   1086 
   1087         renderer.close_group('figure')

/Users/adriano/anaconda/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.pyc in draw(self, renderer)
    252         # Calculate projection of collections and zorder them
    253         zlist = [(col.do_3d_projection(renderer), col) \
--> 254                  for col in self.collections]
    255         zlist.sort(key=itemgetter(0), reverse=True)
    256         for i, (z, col) in enumerate(zlist):

AttributeError: 'PathCollection' object has no attribute 'do_3d_projection'
<matplotlib.figure.Figure at 0x19cadd4d0>

In [61]:
len(tiempos_salida)


Out[61]:
268

In [ ]:


In [ ]:


In [50]:
sample1 = tiempos_salida

In [52]:
plt.hist(sample1,80,color = 'g')


Out[52]:
(array([  65.,  119.,  117.,   64.,   51.,   61.,   91.,   41.,   43.,
          27.,   28.,   15.,   31.,   19.,   11.,   28.,   21.,    8.,
          20.,   10.,    4.,    3.,   11.,    7.,    8.,    5.,    7.,
           6.,    5.,    2.,    4.,    4.,    4.,    2.,    3.,    5.,
           4.,    3.,    4.,    0.,    2.,    4.,    1.,    0.,    3.,
           1.,    6.,    0.,    3.,    0.,    2.,    0.,    1.,    3.,
           0.,    1.,    1.,    0.,    1.,    0.,    0.,    0.,    0.,
           1.,    0.,    1.,    1.,    1.,    2.,    1.,    0.,    0.,
           0.,    0.,    0.,    1.,    0.,    0.,    0.,    2.]),
 array([ 0.00115129,  0.00349993,  0.00584857,  0.0081972 ,  0.01054584,
         0.01289448,  0.01524311,  0.01759175,  0.01994039,  0.02228902,
         0.02463766,  0.0269863 ,  0.02933493,  0.03168357,  0.03403221,
         0.03638084,  0.03872948,  0.04107812,  0.04342675,  0.04577539,
         0.04812403,  0.05047267,  0.0528213 ,  0.05516994,  0.05751858,
         0.05986721,  0.06221585,  0.06456449,  0.06691312,  0.06926176,
         0.0716104 ,  0.07395903,  0.07630767,  0.07865631,  0.08100494,
         0.08335358,  0.08570222,  0.08805085,  0.09039949,  0.09274813,
         0.09509676,  0.0974454 ,  0.09979404,  0.10214267,  0.10449131,
         0.10683995,  0.10918859,  0.11153722,  0.11388586,  0.1162345 ,
         0.11858313,  0.12093177,  0.12328041,  0.12562904,  0.12797768,
         0.13032632,  0.13267495,  0.13502359,  0.13737223,  0.13972086,
         0.1420695 ,  0.14441814,  0.14676677,  0.14911541,  0.15146405,
         0.15381268,  0.15616132,  0.15850996,  0.16085859,  0.16320723,
         0.16555587,  0.1679045 ,  0.17025314,  0.17260178,  0.17495042,
         0.17729905,  0.17964769,  0.18199633,  0.18434496,  0.1866936 ,
         0.18904224]),
 <a list of 80 Patch objects>)

In [53]:
np.mean(sample1)


Out[53]:
0.025177616699343416

In [54]:
np.var(sample1)


Out[54]:
0.00079619727794905755

In [55]:
np.sqrt(2)


Out[55]:
1.4142135623730951

In [ ]:


In [8]:
def plot_particle_Region_frozen(lista_region, trayectoria, lista_frozen, vpolar, vazim, numero):
    from mpl_toolkits.mplot3d import axes3d
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm

    #import matplotlib.pyplot as plt
    #import numpy as np
    from itertools import product, combinations
    fig = plt.figure(figsize=(20,10))
    ax = fig.gca(projection='3d')
    ax.set_aspect("equal")
    ax._axis3don = False
    

    



    #draw sphere
    R = 1
    u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
    x=R*np.cos(u)*np.sin(v)
    y=R*np.sin(u)*np.sin(v)
    z=R*np.cos(v)
    #ax.plot_surface(x, y, z, color="r", alpha = 0.15)

    ax.plot_surface(x, y, z, cmap=cm.YlGnBu_r,rstride=1, cstride=1, alpha = 0.10, linewidth = 0.15)
    ax.view_init(vpolar, vazim)
    #draw patch
    #u, v = np.mgrid[0:2*np.pi:50j, 0:(np.pi/7):50j]
    #x=R*np.cos(u)*np.sin(v)
    #y=R*np.sin(u)*np.sin(v)
    #z=R*np.cos(v)
    #ax.plot_surface(x, y, z, color="r", alpha = 0.25)
    
    
    
    #draw Region
    
    for p in lista_region:
        ax.scatter([p[0]],[p[1]],[p[2]], color="k", s=10, alpha = 0.2)
        
        
    #draw the frozen ones on the boundary
    
    for p in lista_frozen:
        ax.scatter([p[0]],[p[1]],[p[2]], color="r", s=17, alpha = 1.0)
    
    #draw trajectory
    for p in trayectoria:
        ax.scatter([p[0]],[p[1]],[p[2]], color="b",s=20, alpha = 0.7)
    
    #Plot the x positive direction
    
    ax.quiver(1.5,0,0,1,0,0, length=0.5, arrow_length_ratio = .5)
    ax.quiver(0,1.5,0,0,1,0, length=0.5, arrow_length_ratio = .5)
    ax.quiver(0,0,1.5,0,0,1, length=0.5, arrow_length_ratio = .5)
    
    #fig.savefig('BS_24_Obs_test_01{}.png'.format(nombre(numero + 1)))
    #ax.view_init(80, 30)
    #plt.close()
    plt.show()

In [47]:
estructura_obs = puntos_obs([r_omega], theta1)


/Users/adriano/anaconda/lib/python2.7/site-packages/IPython/kernel/__main__.py:163: RuntimeWarning: divide by zero encountered in long_scalars

Divide by Zero!!!

Probably this might have something to do with the overall screw up...


In [ ]:


In [48]:
plot_particles(estructura_obs, 90,0,0)



In [19]:
suma = 0
for i in range(100):
    suma = suma + .01

In [20]:
suma


Out[20]:
1.0000000000000007

In [13]:
#Simulacion del Primer tiempo de salida para una region de tamaño.
pos_ini = uniform_inside_omega(10000,1, theta1-0.05)
tiempo = 0
tiempos_salida = []
tamanho = np.cos(theta1)
r_omega = np.array([0,0,1])
#plot_particles(pos_ini,90,0,1)
frozen = []
#plot_particle_Region_frozen(estructura_obs, pos_ini, frozen, 90, 0, 1)
for i in range(10000):
    tiempo = tiempo + dt
    nuevas_pos = act_n(pos_ini, ese(D,dt))
    #plot_particles(nuevas_pos, 90,0,1)
    #plot_particle_Region_frozen(estructura_obs, nuevas_pos, frozen, 90, 0, 1)
    survey = []
    for v in nuevas_pos:
        if np.dot(r_omega, v) <= tamanho:
            tiempos_salida.append(tiempo)
            frozen.append(v)
        else:
            survey.append(v)
    if len(survey) == 0:
        break
    else:
        pos_ini = survey

In [15]:
len(tiempos_salida)


Out[15]:
10000

In [18]:
plt.hist(tiempos_salida, 70)


Out[18]:
(array([  1.99500000e+03,   1.25000000e+03,   5.98000000e+02,
          4.82000000e+02,   7.50000000e+02,   5.88000000e+02,
          4.18000000e+02,   3.58000000e+02,   3.34000000e+02,
          5.35000000e+02,   3.72000000e+02,   2.98000000e+02,
          3.01000000e+02,   1.35000000e+02,   2.63000000e+02,
          1.26000000e+02,   1.11000000e+02,   1.63000000e+02,
          4.70000000e+01,   8.40000000e+01,   5.40000000e+01,
          1.28000000e+02,   4.10000000e+01,   6.20000000e+01,
          4.50000000e+01,   5.00000000e+01,   1.80000000e+01,
          4.30000000e+01,   3.70000000e+01,   1.60000000e+01,
          2.20000000e+01,   1.80000000e+01,   1.90000000e+01,
          2.80000000e+01,   2.90000000e+01,   3.60000000e+01,
          7.00000000e+00,   6.00000000e+00,   1.00000000e+01,
          1.40000000e+01,   1.20000000e+01,   1.00000000e+01,
          5.00000000e+00,   1.20000000e+01,   7.00000000e+00,
          7.00000000e+00,   3.00000000e+00,   7.00000000e+00,
          8.00000000e+00,   8.00000000e+00,   4.00000000e+00,
          3.00000000e+00,   1.00000000e+00,   3.00000000e+00,
          2.00000000e+00,   2.00000000e+00,   0.00000000e+00,
          2.00000000e+00,   2.00000000e+00,   2.00000000e+00,
          1.00000000e+00,   2.00000000e+00,   2.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   1.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   1.00000000e+00,
          2.00000000e+00]),
 array([ 0.00069078,  0.00383545,  0.00698012,  0.0101248 ,  0.01326947,
         0.01641414,  0.01955882,  0.02270349,  0.02584816,  0.02899284,
         0.03213751,  0.03528218,  0.03842686,  0.04157153,  0.0447162 ,
         0.04786088,  0.05100555,  0.05415022,  0.0572949 ,  0.06043957,
         0.06358424,  0.06672892,  0.06987359,  0.07301826,  0.07616294,
         0.07930761,  0.08245228,  0.08559696,  0.08874163,  0.0918863 ,
         0.09503098,  0.09817565,  0.10132032,  0.104465  ,  0.10760967,
         0.11075434,  0.11389902,  0.11704369,  0.12018836,  0.12333304,
         0.12647771,  0.12962238,  0.13276706,  0.13591173,  0.1390564 ,
         0.14220108,  0.14534575,  0.14849042,  0.1516351 ,  0.15477977,
         0.15792444,  0.16106912,  0.16421379,  0.16735846,  0.17050314,
         0.17364781,  0.17679248,  0.17993716,  0.18308183,  0.1862265 ,
         0.18937118,  0.19251585,  0.19566052,  0.1988052 ,  0.20194987,
         0.20509454,  0.20823922,  0.21138389,  0.21452856,  0.21767324,
         0.22081791]),
 <a list of 70 Patch objects>)

In [ ]:


In [ ]:


In [19]:
#Simulacion del Primer tiempo de salida para una region de tamaño.
pos_ini = uniform_inside_omega(100000,1, theta1-0.05)
tiempo = 0
tiempos_salida = []
tamanho = np.cos(theta1)
r_omega = np.array([0,0,1])
#plot_particles(pos_ini,90,0,1)
frozen = []
#plot_particle_Region_frozen(estructura_obs, pos_ini, frozen, 90, 0, 1)
for i in range(10000):
    tiempo = tiempo + dt
    nuevas_pos = act_n(pos_ini, ese(D,dt))
    #plot_particles(nuevas_pos, 90,0,1)
    #plot_particle_Region_frozen(estructura_obs, nuevas_pos, frozen, 90, 0, 1)
    survey = []
    for v in nuevas_pos:
        if np.dot(r_omega, v) <= tamanho:
            tiempos_salida.append(tiempo)
            frozen.append(v)
        else:
            survey.append(v)
    if len(survey) == 0:
        break
    else:
        pos_ini = survey

In [20]:
sample2 = tiempos_salida

In [27]:
plt.hist(sample2,75)


Out[27]:
(array([  2.10260000e+04,   1.25300000e+04,   1.49480000e+04,
          6.60600000e+03,   8.27200000e+03,   7.12700000e+03,
          2.87300000e+03,   3.86600000e+03,   3.20100000e+03,
          4.77800000e+03,   1.61000000e+03,   1.91400000e+03,
          1.19000000e+03,   2.57100000e+03,   8.13000000e+02,
          8.66000000e+02,   1.37000000e+03,   8.85000000e+02,
          4.45000000e+02,   4.54000000e+02,   2.44000000e+02,
          4.32000000e+02,   2.99000000e+02,   4.05000000e+02,
          2.04000000e+02,   1.87000000e+02,   6.90000000e+01,
          1.33000000e+02,   1.13000000e+02,   4.90000000e+01,
          6.30000000e+01,   8.30000000e+01,   6.60000000e+01,
          6.20000000e+01,   3.80000000e+01,   2.00000000e+01,
          2.50000000e+01,   1.20000000e+01,   3.60000000e+01,
          2.60000000e+01,   1.20000000e+01,   1.50000000e+01,
          1.00000000e+01,   6.00000000e+00,   1.00000000e+01,
          3.00000000e+00,   7.00000000e+00,   1.00000000e+00,
          6.00000000e+00,   2.00000000e+00,   1.00000000e+00,
          2.00000000e+00,   1.00000000e+00,   1.00000000e+00,
          0.00000000e+00,   2.00000000e+00,   3.00000000e+00,
          1.00000000e+00,   1.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   2.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   1.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   1.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   1.00000000e+00]),
 array([ 0.00115129,  0.00637049,  0.01158968,  0.01680887,  0.02202806,
         0.02724726,  0.03246645,  0.03768564,  0.04290484,  0.04812403,
         0.05334322,  0.05856241,  0.06378161,  0.0690008 ,  0.07421999,
         0.07943919,  0.08465838,  0.08987757,  0.09509676,  0.10031596,
         0.10553515,  0.11075434,  0.11597354,  0.12119273,  0.12641192,
         0.13163111,  0.13685031,  0.1420695 ,  0.14728869,  0.15250789,
         0.15772708,  0.16294627,  0.16816546,  0.17338466,  0.17860385,
         0.18382304,  0.18904224,  0.19426143,  0.19948062,  0.20469981,
         0.20991901,  0.2151382 ,  0.22035739,  0.22557659,  0.23079578,
         0.23601497,  0.24123416,  0.24645336,  0.25167255,  0.25689174,
         0.26211094,  0.26733013,  0.27254932,  0.27776852,  0.28298771,
         0.2882069 ,  0.29342609,  0.29864529,  0.30386448,  0.30908367,
         0.31430287,  0.31952206,  0.32474125,  0.32996044,  0.33517964,
         0.34039883,  0.34561802,  0.35083722,  0.35605641,  0.3612756 ,
         0.36649479,  0.37171399,  0.37693318,  0.38215237,  0.38737157,
         0.39259076]),
 <a list of 75 Patch objects>)

In [22]:
len(sample2)


Out[22]:
100000

In [23]:
np.mean(sample2)


Out[23]:
0.028518094325589636

In [24]:
np.var(sample2)


Out[24]:
0.00087143036392317585

In [ ]:


In [ ]:


In [28]:
#Simulacion del Primer tiempo de salida para una region de tamaño.
pos_ini = uniform_inside_omega(1000000,1, theta1-0.05)
tiempo = 0
tiempos_salida_A = []
tamanho = np.cos(theta1)
r_omega = np.array([0,0,1])
#plot_particles(pos_ini,90,0,1)
frozen = []
#plot_particle_Region_frozen(estructura_obs, pos_ini, frozen, 90, 0, 1)
for i in range(10000):
    tiempo = tiempo + dt
    nuevas_pos = act_n(pos_ini, ese(D,dt))
    #plot_particles(nuevas_pos, 90,0,1)
    #plot_particle_Region_frozen(estructura_obs, nuevas_pos, frozen, 90, 0, 1)
    survey = []
    for v in nuevas_pos:
        if np.dot(r_omega, v) <= tamanho:
            tiempos_salida_A.append(tiempo)
            frozen.append(v)
        else:
            survey.append(v)
    if len(survey) == 0:
        break
    else:
        pos_ini = survey

In [29]:
sample3 = tiempos_salida_A

In [44]:
plt.hist(sample3,80, normed = True)
#plt.xlim(0,.3)


Out[44]:
(array([  4.79605052e+01,   1.89469822e+01,   1.28710263e+01,
          1.60347659e+01,   1.30395166e+01,   6.56324458e+00,
          6.14580671e+00,   7.30448090e+00,   4.61075659e+00,
          2.91873165e+00,   3.85436826e+00,   2.12188746e+00,
          1.68596413e+00,   1.26988994e+00,   1.46322959e+00,
          1.01533618e+00,   5.14865294e-01,   7.06386699e-01,
          4.28498838e-01,   3.87739932e-01,   3.76375924e-01,
          1.71823792e-01,   1.92430525e-01,   1.94703326e-01,
          1.45307774e-01,   9.56091821e-02,   1.02730627e-01,
          1.01518466e-01,   4.06073864e-02,   5.27289942e-02,
          2.56068966e-02,   2.69705775e-02,   1.86369721e-02,
          2.43947358e-02,   2.45462559e-02,   1.92430525e-02,
          1.37883290e-02,   8.63664561e-03,   9.39424610e-03,
          5.45472354e-03,   8.63664561e-03,   2.72736177e-03,
          3.03040197e-03,   3.48496226e-03,   1.36368089e-03,
          1.21216079e-03,   7.57600492e-04,   1.21216079e-03,
          3.03040197e-04,   7.57600492e-04,   1.06064069e-03,
          1.51520098e-04,   0.00000000e+00,   3.03040197e-04,
          0.00000000e+00,   1.51520098e-04,   1.51520098e-04,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          1.51520098e-04,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   0.00000000e+00,   0.00000000e+00,
          0.00000000e+00,   1.51520098e-04]),
 array([  4.60517019e-04,   7.06030154e-03,   1.36600861e-02,
          2.02598706e-02,   2.68596551e-02,   3.34594396e-02,
          4.00592242e-02,   4.66590087e-02,   5.32587932e-02,
          5.98585777e-02,   6.64583622e-02,   7.30581468e-02,
          7.96579313e-02,   8.62577158e-02,   9.28575003e-02,
          9.94572849e-02,   1.06057069e-01,   1.12656854e-01,
          1.19256638e-01,   1.25856423e-01,   1.32456207e-01,
          1.39055992e-01,   1.45655777e-01,   1.52255561e-01,
          1.58855346e-01,   1.65455130e-01,   1.72054915e-01,
          1.78654699e-01,   1.85254484e-01,   1.91854268e-01,
          1.98454053e-01,   2.05053837e-01,   2.11653622e-01,
          2.18253406e-01,   2.24853191e-01,   2.31452975e-01,
          2.38052760e-01,   2.44652544e-01,   2.51252329e-01,
          2.57852113e-01,   2.64451898e-01,   2.71051682e-01,
          2.77651467e-01,   2.84251251e-01,   2.90851036e-01,
          2.97450821e-01,   3.04050605e-01,   3.10650390e-01,
          3.17250174e-01,   3.23849959e-01,   3.30449743e-01,
          3.37049528e-01,   3.43649312e-01,   3.50249097e-01,
          3.56848881e-01,   3.63448666e-01,   3.70048450e-01,
          3.76648235e-01,   3.83248019e-01,   3.89847804e-01,
          3.96447588e-01,   4.03047373e-01,   4.09647157e-01,
          4.16246942e-01,   4.22846726e-01,   4.29446511e-01,
          4.36046296e-01,   4.42646080e-01,   4.49245865e-01,
          4.55845649e-01,   4.62445434e-01,   4.69045218e-01,
          4.75645003e-01,   4.82244787e-01,   4.88844572e-01,
          4.95444356e-01,   5.02044141e-01,   5.08643925e-01,
          5.15243710e-01,   5.21843494e-01,   5.28443279e-01]),
 <a list of 80 Patch objects>)

In [31]:
np.mean(sample3)


Out[31]:
0.027192567467690849

In [32]:
np.var(sample3)


Out[32]:
0.00086924570460325198

In [42]:
plt.hist2d?

In [ ]:


In [ ]:


In [ ]:


In [45]:
#Simulacion del Primer tiempo de salida para una region de tamaño.

D = 1e-2
dt = (2.3**2/4.)*1e-5
theta1 = 2.3*1e-2
theta2 = 0.1


pos_ini = uniform_inside_omega(10000,1, theta1-0.005)
tiempo = 0
tiempos_salida_A = []
tamanho = np.cos(theta1)
r_omega = np.array([0,0,1])
#plot_particles(pos_ini,90,0,1)
frozen = []
#plot_particle_Region_frozen(estructura_obs, pos_ini, frozen, 90, 0, 1)
for i in range(10000):
    tiempo = tiempo + dt
    nuevas_pos = act_n(pos_ini, ese(D,dt))
    #plot_particles(nuevas_pos, 90,0,1)
    #plot_particle_Region_frozen(estructura_obs, nuevas_pos, frozen, 90, 0, 1)
    survey = []
    for v in nuevas_pos:
        if np.dot(r_omega, v) <= tamanho:
            tiempos_salida_A.append(tiempo)
            frozen.append(v)
        else:
            survey.append(v)
    if len(survey) == 0:
        break
    else:
        pos_ini = survey

In [46]:
sample4 = tiempos_salida_A

In [47]:
plt.hist(sample4, 100, color = 'g')
plt.xlabel('segundos')


Out[47]:
<matplotlib.text.Text at 0x11d085990>

In [48]:
np.mean(sample4)


Out[48]:
0.0091556357599999489

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [52]:
R = 1.
D = 1.
dt = 1e-3

In [53]:
R = 1
D = 1
#dt = 1e-3*np.log(10)
origen = polo_n(10000,R)
promedio_theta_en_t = [0]
promedio_phi_en_t = [0]
promedio_cos_theta = [np.cos(0)]
var_theta_en_t = [0]
var_phi_en_t = [0]
posicion_vec = origen
t_final = 2500

for i in range(t_final):
    nuevos_vec = act_n(posicion_vec, ese(D,dt))
    thetas = []

    phis = []

    for v in nuevos_vec:
        theta = np.arccos(v[2]/R)
        phi = np.arctan(v[1]/v[0])
        thetas.append(theta)

        phis.append(phi)

    
    #Aqui vamos a salvar una instantanea de cada uno de los histogramas
    #de theta
    #plt.hist(thetas, 50, color = 'g', alpha = 0.6, normed = "true")
    #plt.xlabel(r"$\theta$", fontsize = 15)
    #plt.xlim(0,np.pi)
    #plt.ylabel(r"$n(\theta)/10000$", fontsize = 15)
    #plt.ylim(0,1)
    #plt.title("Paso = {}".format(i), fontsize = 15)
    #plt.savefig('Histograma_theta_{}'.format(nombre(i)), dpi = 600, bbox_inches = 'tight')
    #plt.close()
    mean_cos_theta = np.mean(np.cos(thetas))
    mean_theta = np.mean(thetas)
    mean_phi = np.mean(phis)

    var_theta_en_t.append(np.var(thetas))
    var_phi_en_t.append(np.var(phis))
    promedio_theta_en_t.append(mean_theta)
    promedio_phi_en_t.append(mean_phi)
    posicion_vec = nuevos_vec
    promedio_cos_theta.append(mean_cos_theta)

In [54]:
npasos = t_final
suma = 0
tiempos = [0]
impulso = dt
for i in range(npasos):
    suma += impulso
    tiempos.append(suma)
    
    
plt.rc('text', usetex=True)
plt.plot(tiempos,promedio_theta_en_t)
plt.plot(tiempos, np.pi/2*np.ones(len(tiempos)), 'r', label ="$y = \pi/2$")
plt.ylabel(r'$\langle \theta(t)\rangle$', fontsize = 15)
plt.xlabel('tiempo', fontsize = 12)
plt.legend(loc=4); # Down right corner


Out[54]:
<matplotlib.legend.Legend at 0x108684810>

In [55]:
plt.rc('text', usetex=True)
plt.plot(tiempos,var_theta_en_t, alpha = .8, color = 'g')
plt.plot(tiempos, 0.46358922651739204*np.ones(len(tiempos)), 'r', label ="$y = 0.4636$")
plt.ylabel(r'$\mbox{Var}[\theta(t)]$', fontsize = 15)
plt.xlabel('tiempo', fontsize = 12)
plt.legend(loc=4); # down right corner


Out[55]:
<matplotlib.legend.Legend at 0x103a40a90>

In [58]:
npasos = 2500
suma = 0
tiempos = [0]
impulso = dt
for i in range(npasos):
    suma += impulso
    tiempos.append(suma)

In [59]:
plt.rc('text', usetex=True)  
plt.plot(tiempos, promedio_phi_en_t)
plt.ylabel(r'$\langle \phi(t)\rangle$ $\mbox{rad}$', fontsize = 15)
plt.xlabel('tiempo', fontsize = 15)


Out[59]:
<matplotlib.text.Text at 0x113e29c10>

In [60]:
plt.rc('text', usetex=True)
plt.plot(tiempos, var_phi_en_t, alpha = .8, color = 'g')
plt.ylabel(r'$\mbox{Var}[\phi(t)]$ $\mbox{rad}^2$', fontsize = 15)
plt.xlabel('tiempo', fontsize = 12)


Out[60]:
<matplotlib.text.Text at 0x10bfb3390>

In [ ]:


In [ ]:


In [ ]:


In [61]:
plt.plot(tiempos[:], promedio_cos_theta[:], label=r"$\langle \cos{\theta} \rangle$")
#plt.yscale("log")
#plt.plot(tiempos, np.exp(-4*tiempos))
plt.plot(np.array(tiempos[:]), np.exp(-2*np.array(tiempos[:])), label=r"$\exp{[-2Dt/R^2]}$")
plt.ylabel(r'$\langle \cos{\theta} \rangle$', fontsize = 18)
plt.xlabel('tiempo', fontsize = 12)
plt.legend(loc=0); # upper right


Out[61]:
<matplotlib.legend.Legend at 0x11ae2df50>

In [ ]:


In [62]:
plt.plot(tiempos[:], promedio_cos_theta[:], label=r"$\langle \cos{\theta} \rangle$")
#plt.yscale("log")
#plt.plot(tiempos, np.exp(-4*tiempos))
plt.plot(np.array(tiempos[:]), np.exp(-2*np.array(tiempos[:])), label=r"$\exp{[-2Dt/R^2]}$")
plt.ylabel(r'$\langle \cos{\theta} \rangle$', fontsize = 18)
plt.yscale("log")
plt.xlabel('tiempo', fontsize = 12)
plt.legend(loc=0); # upper right


Out[62]:
<matplotlib.legend.Legend at 0x103a07c90>

In [63]:
A = np.vstack((tiempos, np.ones(len(tiempos)))).T
m, c = np.linalg.lstsq(A, np.log(np.array(promedio_cos_theta)))[0]
print m, c


-2.16549608729 0.0797059581453

In [ ]:


In [64]:
plt.plot(tiempos, np.log(np.array(promedio_cos_theta)), 'o', label='Original data', markersize=5)
plt.plot(tiempos, m*np.array(tiempos) + c, 'r', label='Fitted line')
plt.legend()
plt.show()



In [ ]:


In [ ]:


In [65]:
R = 1
D = 1
t_final = 2000
n = 10000
#dt = 1e-3*np.log(10)
dt = 1e-3

In [9]:
def sim_NO_(R,D,dt, t_final, n):


    origen = polo_n(n,R)
    promedio_theta_en_t = [0]
    promedio_phi_en_t = [0]
    promedio_cos_theta = [np.cos(0)]
    var_theta_en_t = [0]
    var_phi_en_t = [0]
    posicion_vec = origen


    for i in range(t_final):
        nuevos_vec = act_n(posicion_vec, ese(D,dt))
        thetas = []

        phis = []

        for v in nuevos_vec:
            theta = np.arccos(v[2]/R)
            phi = np.arctan(v[1]/v[0])
            thetas.append(theta)

            phis.append(phi)


        #Aqui vamos a salvar una instantanea de cada uno de los histogramas
        #de theta
        #plt.hist(thetas, 50, color = 'g', alpha = 0.6, normed = "true")
        #plt.xlabel(r"$\theta$", fontsize = 15)
        #plt.xlim(0,np.pi)
        #plt.ylabel(r"$n(\theta)/10000$", fontsize = 15)
        #plt.ylim(0,1)
        #plt.title("Paso = {}".format(i), fontsize = 15)
        #plt.savefig('Histograma_theta_{}'.format(nombre(i)), dpi = 600, bbox_inches = 'tight')
        #plt.close()
        mean_cos_theta = np.mean(np.cos(thetas))
        mean_theta = np.mean(thetas)
        mean_phi = np.mean(phis)

        var_theta_en_t.append(np.var(thetas))
        var_phi_en_t.append(np.var(phis))
        promedio_theta_en_t.append(mean_theta)
        promedio_phi_en_t.append(mean_phi)
        posicion_vec = nuevos_vec
        promedio_cos_theta.append(mean_cos_theta)
        
    return promedio_theta_en_t, promedio_phi_en_t, promedio_cos_theta, var_theta_en_t, var_phi_en_t

In [68]:
a, b, c, d, e = sim_NO_(1,2,1e-5, 2000, 1000)

In [69]:
plt.hist(a,100)


Out[69]:
(array([  1.,   0.,   1.,   4.,   0.,   2.,   1.,   5.,   1.,   3.,   9.,
         10.,   6.,  10.,   5.,  17.,   7.,   5.,  21.,  12.,   2.,  13.,
          8.,  14.,  19.,  14.,   0.,  15.,   7.,  10.,  14.,   8.,   2.,
         13.,  15.,  15.,  14.,  14.,  13.,   9.,  12.,  17.,  19.,  13.,
         16.,  17.,  12.,  13.,  24.,  21.,  29.,  20.,  35.,  29.,  10.,
         28.,   8.,  36.,  15.,  18.,  36.,  15.,  22.,  25.,  22.,  35.,
         46.,  53.,  13.,  14.,  24.,  12.,  41.,  25.,  23.,  16.,  40.,
         17.,   8.,  23.,  11.,  57.,  35.,  38.,  56.,  33.,  39.,  27.,
         18.,  23.,  38.,  59.,  37.,  34.,  47.,  63.,  17.,  39.,  47.,
         42.]),
 array([ 0.        ,  0.00355142,  0.00710283,  0.01065425,  0.01420566,
         0.01775708,  0.0213085 ,  0.02485991,  0.02841133,  0.03196274,
         0.03551416,  0.03906558,  0.04261699,  0.04616841,  0.04971982,
         0.05327124,  0.05682266,  0.06037407,  0.06392549,  0.0674769 ,
         0.07102832,  0.07457974,  0.07813115,  0.08168257,  0.08523399,
         0.0887854 ,  0.09233682,  0.09588823,  0.09943965,  0.10299107,
         0.10654248,  0.1100939 ,  0.11364531,  0.11719673,  0.12074815,
         0.12429956,  0.12785098,  0.13140239,  0.13495381,  0.13850523,
         0.14205664,  0.14560806,  0.14915947,  0.15271089,  0.15626231,
         0.15981372,  0.16336514,  0.16691655,  0.17046797,  0.17401939,
         0.1775708 ,  0.18112222,  0.18467363,  0.18822505,  0.19177647,
         0.19532788,  0.1988793 ,  0.20243071,  0.20598213,  0.20953355,
         0.21308496,  0.21663638,  0.22018779,  0.22373921,  0.22729063,
         0.23084204,  0.23439346,  0.23794488,  0.24149629,  0.24504771,
         0.24859912,  0.25215054,  0.25570196,  0.25925337,  0.26280479,
         0.2663562 ,  0.26990762,  0.27345904,  0.27701045,  0.28056187,
         0.28411328,  0.2876647 ,  0.29121612,  0.29476753,  0.29831895,
         0.30187036,  0.30542178,  0.3089732 ,  0.31252461,  0.31607603,
         0.31962744,  0.32317886,  0.32673028,  0.33028169,  0.33383311,
         0.33738452,  0.34093594,  0.34448736,  0.34803877,  0.35159019,
         0.3551416 ]),
 <a list of 100 Patch objects>)

In [106]:
ensambles_theta_t = []
ensambles_phi_t = []
ensambles_cos_theta_t = []
ensambles_var_theta_t = []
ensambles_var_phi_t = []
for i in range(1,11):
    a, b, c, d, e = sim_NO_(1 , i, np.log(10)*1e-4, 2500, 4000)
    ensambles_theta_t.append(a)
    ensambles_phi_t.append(b)
    ensambles_cos_theta_t.append(c)
    ensambles_var_theta_t.append(d)
    ensambles_var_phi_t.append(e)

In [107]:
plt.plot(ensambles_cos_theta_t[0])


Out[107]:
[<matplotlib.lines.Line2D at 0x1185f1cd0>]

In [90]:
plt.plot(ensambles_cos_theta_t[1])


Out[90]:
[<matplotlib.lines.Line2D at 0x116be58d0>]

In [91]:
plt.plot(ensambles_cos_theta_t[2])


Out[91]:
[<matplotlib.lines.Line2D at 0x117c777d0>]

In [ ]:


In [ ]:


In [92]:
npasos = 2500

In [11]:
def f_tiempo(npasos, dt):

    suma = 0
    tiempos = [0]
    impulso = dt
    for i in range(npasos):
        suma += impulso
        tiempos.append(suma)
    return tiempos

In [102]:
t1 = f_tiempo(npasos, dt)

In [ ]:


In [86]:
len(ensambles_cos_theta_t[3])


Out[86]:
2001

In [98]:
plt.plot(t1, ensambles_cos_theta_t[2])


Out[98]:
[<matplotlib.lines.Line2D at 0x119e77e10>]

In [114]:
for i in range(1,10):
    A = np.vstack((t1, np.ones(len(t1[:])))).T
    m, c = np.linalg.lstsq(A, np.log(np.array(ensambles_cos_theta_t[i][:])))[0]
    print i, m, c


1 -0.983329036129 0.0334720035686
2 -1.38712022029 -0.0521067993034
3 -2.00149283495 0.0690505740265
4 nan nan
5 nan nan
6 nan nan
7 nan nan
8 nan nan
9 nan nan
/Users/draflorencia/anaconda/lib/python2.7/site-packages/IPython/kernel/__main__.py:3: RuntimeWarning: invalid value encountered in log
  app.launch_new_instance()

In [ ]:
plt.plot(tiempo,)

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [115]:
ensambles_02_theta_t = []
ensambles_02_phi_t = []
ensambles_02_cos_theta_t = []
ensambles_02_var_theta_t = []
ensambles_02_var_phi_t = []
for i in range(1,11):
    a, b, c, d, e = sim_NO_(1 , i, np.log(10)*1e-3, 2500, 1000)
    ensambles_02_theta_t.append(a)
    ensambles_02_phi_t.append(b)
    ensambles_02_cos_theta_t.append(c)
    ensambles_02_var_theta_t.append(d)
    ensambles_02_var_phi_t.append(e)

In [116]:
t2 = f_tiempo(2500, np.log(10)*1e-3)

In [118]:
for i in range(10):
    fig = plt.figure()
    plt.plot(t2, ensambles_02_cos_theta_t[i])



In [121]:
for i in range(10):
    fig = plt.figure()
    plt.plot(t2[:100], np.log(ensambles_02_cos_theta_t[i][:100]))



In [125]:
for i in range(10):
    a = ensambles_02_cos_theta_t[i][80] - ensambles_02_cos_theta_t[i][0]
    b = t2[80] - t2[0]
    m = a/b
    print 'm', m


m -1.76500064285
m -2.94758369122
m -3.69476378019
m -3.77481773991
m -4.82136508196
m -4.63872627917
m -4.76724757456
m -5.07843905518
m -5.31999372276
m -5.31078959868

In [ ]:


In [ ]:


In [128]:
t3 = f_tiempo(2000,np.log(10)*1e-3)

In [ ]:


In [127]:
ensambles_03_theta_t = []
ensambles_03_phi_t = []
ensambles_03_cos_theta_t = []
ensambles_03_var_theta_t = []
ensambles_03_var_phi_t = []
for i in range(1,11):
    a, b, c, d, e = sim_NO_(1 , (i), np.log(10)*1e-3, 2000, 4000)
    ensambles_03_theta_t.append(a)
    ensambles_03_phi_t.append(b)
    ensambles_03_cos_theta_t.append(c)
    ensambles_03_var_theta_t.append(d)
    ensambles_03_var_phi_t.append(e)

In [129]:
for i in range(10):
    fig = plt.figure()
    plt.plot(t3, ensambles_03_cos_theta_t[i])



In [ ]:


In [ ]:


In [151]:
A = np.vstack((t3[:100], np.ones(len(t3[:100])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(ensambles_03_cos_theta_t[3][:100])))[0]
print m, c


-9.45871299106 0.0718818933935

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [152]:
ax, bx, cx, dx, ex = sim_NO_(1 , 5, np.log(10)*1e-6, 1000, 100000)

In [153]:
tx = f_tiempo(1000,np.log(10)*1e-6)

In [156]:
plt.plot(tx,cx)


Out[156]:
[<matplotlib.lines.Line2D at 0x110b67510>]

In [157]:
A = np.vstack((tx[:], np.ones(len(tx[:])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(cx[:])))[0]
print m, c


-10.7844629345 0.000230725127598

In [158]:
ax2, bx2, cx2, dx2, ex2 = sim_NO_(1 , 5, np.log(10)*1e-6, 1000, 400000)
tx = f_tiempo(1000,np.log(10)*1e-6)
plt.plot(tx,cx2)
A = np.vstack((tx[:], np.ones(len(tx[:])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(cx2[:])))[0]
print 'm', m, 'c', c


m -10.4507936667 c -0.000267604467391

In [ ]:


In [ ]:


In [160]:
ax3, bx3, cx3, dx3, ex3 = sim_NO_(1 , 1, np.log(10)*1e-6, 1000, 10000)
tx = f_tiempo(1000,np.log(10)*1e-6)
plt.plot(tx,cx3)
A = np.vstack((tx[:], np.ones(len(tx[:])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(cx3[:])))[0]
print 'm', m, 'c', c


m -1.9106618026 c -3.48087501022e-05

In [ ]:


In [161]:
ax4, bx4, cx4, dx4, ex4 = sim_NO_(1 , 2., np.log(10)*1e-6, 1000, 10000)
tx = f_tiempo(1000,np.log(10)*1e-6)
plt.plot(tx,cx4)
A = np.vstack((tx[:], np.ones(len(tx[:])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(cx4[:])))[0]
print 'm', m, 'c', c


m -4.20546183846 c -8.03872503989e-05

In [ ]:


In [162]:
ax5, bx5, cx5, dx5, ex5 = sim_NO_(1 , 2., np.log(10)*1e-6, 1000, 10000)
tx = f_tiempo(1000,np.log(10)*1e-6)
plt.plot(tx,cx5)
A = np.vstack((tx[:], np.ones(len(tx[:])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(cx5[:])))[0]
print 'm', m, 'c', c


m -4.29726372672 c 0.000140853368671

In [ ]:


In [ ]:


In [163]:
ax6, bx6, cx6, dx6, ex6 = sim_NO_(1 , 3., np.log(10)*1e-6, 1000, 10000)
tx = f_tiempo(1000,np.log(10)*1e-6)
plt.plot(tx,cx6)
A = np.vstack((tx[:], np.ones(len(tx[:])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(cx6[:])))[0]
print 'm', m, 'c', c


m -5.91179220663 c 0.000140327779894

In [ ]:


In [164]:
ax7, bx7, cx7, dx7, ex7 = sim_NO_(1 , 4., np.log(10)*1e-6, 1000, 10000)
tx = f_tiempo(1000,np.log(10)*1e-6)
plt.plot(tx,cx7)
A = np.vstack((tx[:], np.ones(len(tx[:])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(cx7[:])))[0]
print 'm', m, 'c', c


m -7.46486409744 c 0.000197352889507

In [ ]:


In [12]:
#ax8, bx8, cx8, dx8, ex8 = sim_NO_(1 , 5., np.log(10)*1e-6, 1000, 10000)
tx = f_tiempo(1000,np.log(10)*1e-6)
plt.plot(tx,cx8)
A = np.vstack((tx[:], np.ones(len(tx[:])))).T
m, c = np.linalg.lstsq(A, np.log(np.array(cx8[:])))[0]
print 'm', m, 'c', c


m -9.87688769062 c 6.30797523952e-05

In [ ]: