Brownian motion on the Sphere

Introduction

En este notebook vamos a simular la evolución de una o varias; un ensamble, partículas realizando movimiento browniano sobre la superficie de la esfera.

Esencialmente calcularemos cuatro cosas para compararlas con una solución analítica para este caso sencillo

- El promedio de la coordenada polar,
- El promedio de la coordenada azimuthal,
- La varianza de la coordenada polar,
- La varianza de la coordenada azimuthal,
- El histograma como función del tiempo,
- Graficaremos la evolución temporal de la solución analítica.
- Tiempo promedio de escape de una región $\Omega$

Mínimo de librerías necesarias


In [2]:
from matplotlib import pyplot as plt
import numpy as np
%matplotlib inline

Código


In [1]:
# %load Brownian_Sphere_code_02.py

import numpy as np
from matplotlib import pyplot as plt

#Funcion que toma un vector y regresa otro ortogonal a este.
def orto(x):
    if np.dot(x,x) == 0:
        return 'Pendejo: 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 imput x.
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.
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.
def vector_q(x,s):
    q = (R)*np.tan(s/(R))
    return q*x

#Dados todos los datos anteriores, esta funcion actualiza la posición de la particula.
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 pocision inicial y un arco de desplazamiento
#Como output da un vector de posicion nuevo dada un tipo de desplazamiento.
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 cuando es llamada grafia la posicion de la particula browniana
#sobre la superficie de una esfera sobre la que se esta difundiendo.
def plot_particle(r,i):
    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")

    #draw a point
    ax.scatter([r[0]],[r[1]],[r[2]],color="b",s=100)
    
    
    
    

    #draw sphere
    u, v = np.mgrid[0:2*np.pi:50j, (np.pi/7):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.55, linewidth = 0.15)



    #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)
    


    ax.view_init(80, 30)
    #fig.savefig('BS_Rand_01.{}.png'.format(i))
    
    plt.show()
    

    
#Esta funcion Genera n posiciones aleatorias sobre la superficie de la esfera de radio R.
#El proposito de tener esta funcion es el de generar de manera automatizada
#Una condicion inicial con distribucion uniforme sobre la esfera para varaias particulas Brownianas.
def P_INS(n,R):
    l = []
    for i in range(n):
        a1 = 2*np.pi*np.random.rand()
        a2 = np.pi*np.random.rand()
        l.append(np.array([R*np.sin(a2)*np.cos(a1),R*np.sin(a2)*np.sin(a1),R*np.cos(a2)]))
    return l

#Esta funcion cuando es llamada grafia la posicion de las partoculas brownianas.
#sobre la superficie de una esfera sobre la que se esta difundiendo.
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")

    



    #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.55, 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 points
    for p in lista:
        ax.scatter([p[0]],[p[1]],[p[2]],color="b",s=150)
    
    fig.savefig('BS_Obs_01.{}.png'.format(nombre(numero)))
    #ax.view_init(80, 30)
    plt.show()
    
#Esta función actualiza la posicion de todos los elementos de una lista; partícula brownianas.
def act_n(lista,s):
    l = []
    for v in lista:
        l.append(actualiza(v,s))
    return l

#Esta funcion simula la evolucion de n particulas brownianas difundiendose sobre la superficie de una esfera.
#Grafica cada paso o instantanea del sistema completo.
def sim_n_pb(lista, m):
    plot_particles(lista)
    sigma = lista
    for i in range(m):
        eta = act_n(sigma)
        plot_particles(eta)
        sigma = eta
        
#Funcion que pone n particulas en el polo norte de una esfera
def polo_n(n, R):
    l = []
    for i in range(n):
        l.append(np.array([0,0,R]))
    return l


#Operador de Rotación


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)


#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.

def b_steps(ri,rf,n):
    l = [ri]
    r0 = ri
    theta = np.arccos((np.dot(ri,rf))/((np.linalg.norm(ri))*(np.linalg.norm(rf))))
    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)
        l.append(vi)
        r0 = vi
    return l



#Transformacion de coordenada de esfericas a cartesianas.


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.

def trans_c_s(x,y,z):
    r = np.sqrt(x**2 + y**2 + z**2)
    theta = np.arccos(z/r)
    phi = np.arctan(y/z)
    return r, theta, phi




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])
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])
def phi_uni(theta, phi):
    x = -np.sin(theta)
    y = np.cos(phi)
    z = 0
    return np.array([x,y,z])



def collision_update(lista_vect, r_omega, theta_omega):
    for v in lista_vect:
        #angulo = np.arccos(np.dot(v,r_omega)/(np.linalg.norm(v)*np.linalg.norm(r_omega)))
        #print angulo, theta_omega
        tamanho = (R**2)*np.cos(theta_omega)
        if np.dot(v,r_omega) >= tamanho:
            print 'Choco el mother fucker'
            rp = v
            np_prima = np.cross(np.cross(r_omega, rp), rp)
            nor_p = np_prima/np.linalg.norm(np_prima)
            up_prima = np.cross(np.cross(lista_vect[0], lista_vect[-1]), rp)
            up = up_prima/np.linalg.norm(up_prima)
            tp_prima = np.cross(rp, nor_p)
            tp = tp_prima/np.linalg.norm(tp_prima)
            x = (np.dot(up,tp))*tp - (np.dot(up, nor_p))*nor_p
            v_rot_prima = np.cross(rp, x)
            v_rot = v_rot_prima/np.linalg.norm(v_rot_prima)
            ang_dif = np.arccos(np.dot(v,lista_vect[-1])/(np.linalg.norm(v)*np.linalg.norm(lista_vect[-1])))
            posicion_final = rot_theta(rp, ang_dif, v_rot)
            return v, posicion_final
        else:
            continue
    print 'no choco el mother fucker'
    return lista_vect[0], lista_vect[-1]
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
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

def ese(D,delta_t):
    return abs(np.random.normal(loc = 0., scale = np.sqrt(var(D,delta_t)),size = None))




#Definimos las condiciones inciales

# R es el radio de la esfera

R=1
def exit_time(R):
    t0 = 0
    x0 = np.array([0,0,R])
    x = x0
    t = t0
    for i in range(550):
        t = t + 25e-6
        x = actualiza(x,ese())
        #plot_particle(x,i)
        theta_x = np.arccos(x[2]/R)
        if theta_R < theta_x:
            return  t
        else:
            continue
    return 'no salio de la region'

In [ ]:


In [ ]:

De manera rutinaria necesitaresmo crear carpetas donde guardar los snapshotsde nuestras simulaciones.


In [2]:
!pwd


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy

In [11]:
!mkdir Histograma_Thesis_theta_NO_02

In [12]:
%cd /Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/Histograma_Thesis_theta_NO_02/


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/Histograma_Thesis_theta_NO_02

In [46]:
!mkdir Histograma_Theta_NO_04

In [47]:
%cd Histograma_Theta_NO_04/


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/Histograma_Theta_NO_04

In [48]:
!pwd


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/Histograma_Theta_NO_04

In [13]:
%cd /Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy

In [ ]:


In [ ]:


In [ ]:

Cálculo Numérico de $D$


In [14]:
!pwd


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/Histograma_Thesis_theta_NO_02

A continuación definimos los valores de el parámetros $D$ y de el tamaño del paso para los incrementos del tiempo.


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

In [65]:
#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 [ ]:


In [ ]:


In [ ]:


In [66]:
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[66]:
<matplotlib.legend.Legend at 0x10b515790>

In [67]:
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[67]:
<matplotlib.legend.Legend at 0x10b05dd50>

In [58]:
np.sqrt(.46)


Out[58]:
0.67823299831252681

In [ ]:


In [28]:
np.mean(var_theta_en_t)


Out[28]:
0.30236539516102218

In [ ]:


In [276]:
(np.pi**2)/4 -2


Out[276]:
0.4674011002723395

In [ ]:


In [ ]:


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

In [30]:
tiempos


Out[30]:
[0,
 0.0002302585092994046,
 0.0004605170185988092,
 0.00069077552789821378,
 0.0009210340371976184,
 0.0011512925464970229,
 0.0013815510557964276,
 0.0016118095650958322,
 0.0018420680743952368,
 0.0020723265836946414,
 0.0023025850929940458,
 0.0025328436022934503,
 0.0027631021115928547,
 0.0029933606208922591,
 0.0032236191301916635,
 0.0034538776394910679,
 0.0036841361487904723,
 0.0039143946580898767,
 0.0041446531673892811,
 0.0043749116766886855,
 0.00460517018598809,
 0.0048354286952874944,
 0.0050656872045868988,
 0.0052959457138863032,
 0.0055262042231857076,
 0.005756462732485112,
 0.0059867212417845164,
 0.0062169797510839208,
 0.0064472382603833252,
 0.0066774967696827297,
 0.0069077552789821341,
 0.0071380137882815385,
 0.0073682722975809429,
 0.0075985308068803473,
 0.0078287893161797517,
 0.008059047825479157,
 0.0082893063347785623,
 0.0085195648440779675,
 0.0087498233533773728,
 0.0089800818626767781,
 0.0092103403719761834,
 0.0094405988812755887,
 0.0096708573905749939,
 0.0099011158998743992,
 0.010131374409173804,
 0.01036163291847321,
 0.010591891427772615,
 0.01082214993707202,
 0.011052408446371426,
 0.011282666955670831,
 0.011512925464970236,
 0.011743183974269641,
 0.011973442483569047,
 0.012203700992868452,
 0.012433959502167857,
 0.012664218011467263,
 0.012894476520766668,
 0.013124735030066073,
 0.013354993539365478,
 0.013585252048664884,
 0.013815510557964289,
 0.014045769067263694,
 0.0142760275765631,
 0.014506286085862505,
 0.01473654459516191,
 0.014966803104461315,
 0.015197061613760721,
 0.015427320123060126,
 0.015657578632359531,
 0.015887837141658936,
 0.016118095650958342,
 0.016348354160257747,
 0.016578612669557152,
 0.016808871178856558,
 0.017039129688155963,
 0.017269388197455368,
 0.017499646706754773,
 0.017729905216054179,
 0.017960163725353584,
 0.018190422234652989,
 0.018420680743952395,
 0.0186509392532518,
 0.018881197762551205,
 0.01911145627185061,
 0.019341714781150016,
 0.019571973290449421,
 0.019802231799748826,
 0.020032490309048231,
 0.020262748818347637,
 0.020493007327647042,
 0.020723265836946447,
 0.020953524346245853,
 0.021183782855545258,
 0.021414041364844663,
 0.021644299874144068,
 0.021874558383443474,
 0.022104816892742879,
 0.022335075402042284,
 0.02256533391134169,
 0.022795592420641095,
 0.0230258509299405,
 0.023256109439239905,
 0.023486367948539311,
 0.023716626457838716,
 0.023946884967138121,
 0.024177143476437526,
 0.024407401985736932,
 0.024637660495036337,
 0.024867919004335742,
 0.025098177513635148,
 0.025328436022934553,
 0.025558694532233958,
 0.025788953041533363,
 0.026019211550832769,
 0.026249470060132174,
 0.026479728569431579,
 0.026709987078730985,
 0.02694024558803039,
 0.027170504097329795,
 0.0274007626066292,
 0.027631021115928606,
 0.027861279625228011,
 0.028091538134527416,
 0.028321796643826821,
 0.028552055153126227,
 0.028782313662425632,
 0.029012572171725037,
 0.029242830681024443,
 0.029473089190323848,
 0.029703347699623253,
 0.029933606208922658,
 0.030163864718222064,
 0.030394123227521469,
 0.030624381736820874,
 0.03085464024612028,
 0.031084898755419685,
 0.03131515726471909,
 0.031545415774018495,
 0.031775674283317901,
 0.032005932792617306,
 0.032236191301916711,
 0.032466449811216117,
 0.032696708320515522,
 0.032926966829814927,
 0.033157225339114332,
 0.033387483848413738,
 0.033617742357713143,
 0.033848000867012548,
 0.034078259376311953,
 0.034308517885611359,
 0.034538776394910764,
 0.034769034904210169,
 0.034999293413509575,
 0.03522955192280898,
 0.035459810432108385,
 0.03569006894140779,
 0.035920327450707196,
 0.036150585960006601,
 0.036380844469306006,
 0.036611102978605412,
 0.036841361487904817,
 0.037071619997204222,
 0.037301878506503627,
 0.037532137015803033,
 0.037762395525102438,
 0.037992654034401843,
 0.038222912543701248,
 0.038453171053000654,
 0.038683429562300059,
 0.038913688071599464,
 0.03914394658089887,
 0.039374205090198275,
 0.03960446359949768,
 0.039834722108797085,
 0.040064980618096491,
 0.040295239127395896,
 0.040525497636695301,
 0.040755756145994707,
 0.040986014655294112,
 0.041216273164593517,
 0.041446531673892922,
 0.041676790183192328,
 0.041907048692491733,
 0.042137307201791138,
 0.042367565711090543,
 0.042597824220389949,
 0.042828082729689354,
 0.043058341238988759,
 0.043288599748288165,
 0.04351885825758757,
 0.043749116766886975,
 0.04397937527618638,
 0.044209633785485786,
 0.044439892294785191,
 0.044670150804084596,
 0.044900409313384002,
 0.045130667822683407,
 0.045360926331982812,
 0.045591184841282217,
 0.045821443350581623,
 0.046051701859881028,
 0.046281960369180433,
 0.046512218878479838,
 0.046742477387779244,
 0.046972735897078649,
 0.047202994406378054,
 0.04743325291567746,
 0.047663511424976865,
 0.04789376993427627,
 0.048124028443575675,
 0.048354286952875081,
 0.048584545462174486,
 0.048814803971473891,
 0.049045062480773297,
 0.049275320990072702,
 0.049505579499372107,
 0.049735838008671512,
 0.049966096517970918,
 0.050196355027270323,
 0.050426613536569728,
 0.050656872045869134,
 0.050887130555168539,
 0.051117389064467944,
 0.051347647573767349,
 0.051577906083066755,
 0.05180816459236616,
 0.052038423101665565,
 0.05226868161096497,
 0.052498940120264376,
 0.052729198629563781,
 0.052959457138863186,
 0.053189715648162592,
 0.053419974157461997,
 0.053650232666761402,
 0.053880491176060807,
 0.054110749685360213,
 0.054341008194659618,
 0.054571266703959023,
 0.054801525213258429,
 0.055031783722557834,
 0.055262042231857239,
 0.055492300741156644,
 0.05572255925045605,
 0.055952817759755455,
 0.05618307626905486,
 0.056413334778354265,
 0.056643593287653671,
 0.056873851796953076,
 0.057104110306252481,
 0.057334368815551887,
 0.057564627324851292,
 0.057794885834150697,
 0.058025144343450102,
 0.058255402852749508,
 0.058485661362048913,
 0.058715919871348318,
 0.058946178380647724,
 0.059176436889947129,
 0.059406695399246534,
 0.059636953908545939,
 0.059867212417845345,
 0.06009747092714475,
 0.060327729436444155,
 0.06055798794574356,
 0.060788246455042966,
 0.061018504964342371,
 0.061248763473641776,
 0.061479021982941182,
 0.061709280492240587,
 0.061939539001539992,
 0.062169797510839397,
 0.062400056020138803,
 0.062630314529438208,
 0.062860573038737613,
 0.063090831548037019,
 0.063321090057336424,
 0.063551348566635829,
 0.063781607075935234,
 0.06401186558523464,
 0.064242124094534045,
 0.06447238260383345,
 0.064702641113132855,
 0.064932899622432261,
 0.065163158131731666,
 0.065393416641031071,
 0.065623675150330477,
 0.065853933659629882,
 0.066084192168929287,
 0.066314450678228692,
 0.066544709187528098,
 0.066774967696827503,
 0.067005226206126908,
 0.067235484715426314,
 0.067465743224725719,
 0.067696001734025124,
 0.067926260243324529,
 0.068156518752623935,
 0.06838677726192334,
 0.068617035771222745,
 0.068847294280522151,
 0.069077552789821556,
 0.069307811299120961,
 0.069538069808420366,
 0.069768328317719772,
 0.069998586827019177,
 0.070228845336318582,
 0.070459103845617987,
 0.070689362354917393,
 0.070919620864216798,
 0.071149879373516203,
 0.071380137882815609,
 0.071610396392115014,
 0.071840654901414419,
 0.072070913410713824,
 0.07230117192001323,
 0.072531430429312635,
 0.07276168893861204,
 0.072991947447911446,
 0.073222205957210851,
 0.073452464466510256,
 0.073682722975809661,
 0.073912981485109067,
 0.074143239994408472,
 0.074373498503707877,
 0.074603757013007282,
 0.074834015522306688,
 0.075064274031606093,
 0.075294532540905498,
 0.075524791050204904,
 0.075755049559504309,
 0.075985308068803714,
 0.076215566578103119,
 0.076445825087402525,
 0.07667608359670193,
 0.076906342106001335,
 0.077136600615300741,
 0.077366859124600146,
 0.077597117633899551,
 0.077827376143198956,
 0.078057634652498362,
 0.078287893161797767,
 0.078518151671097172,
 0.078748410180396577,
 0.078978668689695983,
 0.079208927198995388,
 0.079439185708294793,
 0.079669444217594199,
 0.079899702726893604,
 0.080129961236193009,
 0.080360219745492414,
 0.08059047825479182,
 0.080820736764091225,
 0.08105099527339063,
 0.081281253782690036,
 0.081511512291989441,
 0.081741770801288846,
 0.081972029310588251,
 0.082202287819887657,
 0.082432546329187062,
 0.082662804838486467,
 0.082893063347785872,
 0.083123321857085278,
 0.083353580366384683,
 0.083583838875684088,
 0.083814097384983494,
 0.084044355894282899,
 0.084274614403582304,
 0.084504872912881709,
 0.084735131422181115,
 0.08496538993148052,
 0.085195648440779925,
 0.085425906950079331,
 0.085656165459378736,
 0.085886423968678141,
 0.086116682477977546,
 0.086346940987276952,
 0.086577199496576357,
 0.086807458005875762,
 0.087037716515175167,
 0.087267975024474573,
 0.087498233533773978,
 0.087728492043073383,
 0.087958750552372789,
 0.088189009061672194,
 0.088419267570971599,
 0.088649526080271004,
 0.08887978458957041,
 0.089110043098869815,
 0.08934030160816922,
 0.089570560117468626,
 0.089800818626768031,
 0.090031077136067436,
 0.090261335645366841,
 0.090491594154666247,
 0.090721852663965652,
 0.090952111173265057,
 0.091182369682564463,
 0.091412628191863868,
 0.091642886701163273,
 0.091873145210462678,
 0.092103403719762084,
 0.092333662229061489,
 0.092563920738360894,
 0.092794179247660299,
 0.093024437756959705,
 0.09325469626625911,
 0.093484954775558515,
 0.093715213284857921,
 0.093945471794157326,
 0.094175730303456731,
 0.094405988812756136,
 0.094636247322055542,
 0.094866505831354947,
 0.095096764340654352,
 0.095327022849953758,
 0.095557281359253163,
 0.095787539868552568,
 0.096017798377851973,
 0.096248056887151379,
 0.096478315396450784,
 0.096708573905750189,
 0.096938832415049594,
 0.097169090924349,
 0.097399349433648405,
 0.09762960794294781,
 0.097859866452247216,
 0.098090124961546621,
 0.098320383470846026,
 0.098550641980145431,
 0.098780900489444837,
 0.099011158998744242,
 0.099241417508043647,
 0.099471676017343053,
 0.099701934526642458,
 0.099932193035941863,
 0.10016245154524127,
 0.10039271005454067,
 0.10062296856384008,
 0.10085322707313948,
 0.10108348558243889,
 0.10131374409173829,
 0.1015440026010377,
 0.10177426111033711,
 0.10200451961963651,
 0.10223477812893592,
 0.10246503663823532,
 0.10269529514753473,
 0.10292555365683413,
 0.10315581216613354,
 0.10338607067543294,
 0.10361632918473235,
 0.10384658769403175,
 0.10407684620333116,
 0.10430710471263056,
 0.10453736322192997,
 0.10476762173122937,
 0.10499788024052878,
 0.10522813874982818,
 0.10545839725912759,
 0.105688655768427,
 0.1059189142777264,
 0.10614917278702581,
 0.10637943129632521,
 0.10660968980562462,
 0.10683994831492402,
 0.10707020682422343,
 0.10730046533352283,
 0.10753072384282224,
 0.10776098235212164,
 0.10799124086142105,
 0.10822149937072045,
 0.10845175788001986,
 0.10868201638931926,
 0.10891227489861867,
 0.10914253340791807,
 0.10937279191721748,
 0.10960305042651688,
 0.10983330893581629,
 0.1100635674451157,
 0.1102938259544151,
 0.11052408446371451,
 0.11075434297301391,
 0.11098460148231332,
 0.11121485999161272,
 0.11144511850091213,
 0.11167537701021153,
 0.11190563551951094,
 0.11213589402881034,
 0.11236615253810975,
 0.11259641104740915,
 0.11282666955670856,
 0.11305692806600796,
 0.11328718657530737,
 0.11351744508460677,
 0.11374770359390618,
 0.11397796210320559,
 0.11420822061250499,
 0.1144384791218044,
 0.1146687376311038,
 0.11489899614040321,
 0.11512925464970261,
 0.11535951315900202,
 0.11558977166830142,
 0.11582003017760083,
 0.11605028868690023,
 0.11628054719619964,
 0.11651080570549904,
 0.11674106421479845,
 0.11697132272409785,
 0.11720158123339726,
 0.11743183974269666,
 0.11766209825199607,
 0.11789235676129547,
 0.11812261527059488,
 0.11835287377989429,
 0.11858313228919369,
 0.1188133907984931,
 0.1190436493077925,
 0.11927390781709191,
 0.11950416632639131,
 0.11973442483569072,
 0.11996468334499012,
 0.12019494185428953,
 0.12042520036358893,
 0.12065545887288834,
 0.12088571738218774,
 0.12111597589148715,
 0.12134623440078655,
 0.12157649291008596,
 0.12180675141938536,
 0.12203700992868477,
 0.12226726843798418,
 0.12249752694728358,
 0.12272778545658299,
 0.12295804396588239,
 0.1231883024751818,
 0.1234185609844812,
 0.12364881949378061,
 0.12387907800308001,
 0.12410933651237942,
 0.12433959502167882,
 0.12456985353097823,
 0.12480011204027763,
 0.12503037054957702,
 0.12526062905887642,
 0.12549088756817581,
 0.1257211460774752,
 0.12595140458677459,
 0.12618166309607398,
 0.12641192160537337,
 0.12664218011467276,
 0.12687243862397216,
 0.12710269713327155,
 0.12733295564257094,
 0.12756321415187033,
 0.12779347266116972,
 0.12802373117046911,
 0.1282539896797685,
 0.1284842481890679,
 0.12871450669836729,
 0.12894476520766668,
 0.12917502371696607,
 0.12940528222626546,
 0.12963554073556485,
 0.12986579924486424,
 0.13009605775416364,
 0.13032631626346303,
 0.13055657477276242,
 0.13078683328206181,
 0.1310170917913612,
 0.13124735030066059,
 0.13147760880995998,
 0.13170786731925938,
 0.13193812582855877,
 0.13216838433785816,
 0.13239864284715755,
 0.13262890135645694,
 0.13285915986575633,
 0.13308941837505572,
 0.13331967688435511,
 0.13354993539365451,
 0.1337801939029539,
 0.13401045241225329,
 0.13424071092155268,
 0.13447096943085207,
 0.13470122794015146,
 0.13493148644945085,
 0.13516174495875025,
 0.13539200346804964,
 0.13562226197734903,
 0.13585252048664842,
 0.13608277899594781,
 0.1363130375052472,
 0.13654329601454659,
 0.13677355452384599,
 0.13700381303314538,
 0.13723407154244477,
 0.13746433005174416,
 0.13769458856104355,
 0.13792484707034294,
 0.13815510557964233,
 0.13838536408894173,
 0.13861562259824112,
 0.13884588110754051,
 0.1390761396168399,
 0.13930639812613929,
 0.13953665663543868,
 0.13976691514473807,
 0.13999717365403747,
 0.14022743216333686,
 0.14045769067263625,
 0.14068794918193564,
 0.14091820769123503,
 0.14114846620053442,
 0.14137872470983381,
 0.14160898321913321,
 0.1418392417284326,
 0.14206950023773199,
 0.14229975874703138,
 0.14253001725633077,
 0.14276027576563016,
 0.14299053427492955,
 0.14322079278422895,
 0.14345105129352834,
 0.14368130980282773,
 0.14391156831212712,
 0.14414182682142651,
 0.1443720853307259,
 0.14460234384002529,
 0.14483260234932469,
 0.14506286085862408,
 0.14529311936792347,
 0.14552337787722286,
 0.14575363638652225,
 0.14598389489582164,
 0.14621415340512103,
 0.14644441191442042,
 0.14667467042371982,
 0.14690492893301921,
 0.1471351874423186,
 0.14736544595161799,
 0.14759570446091738,
 0.14782596297021677,
 0.14805622147951616,
 0.14828647998881556,
 0.14851673849811495,
 0.14874699700741434,
 0.14897725551671373,
 0.14920751402601312,
 0.14943777253531251,
 0.1496680310446119,
 0.1498982895539113,
 0.15012854806321069,
 0.15035880657251008,
 0.15058906508180947,
 0.15081932359110886,
 0.15104958210040825,
 0.15127984060970764,
 0.15151009911900704,
 0.15174035762830643,
 0.15197061613760582,
 0.15220087464690521,
 0.1524311331562046,
 0.15266139166550399,
 0.15289165017480338,
 0.15312190868410278,
 0.15335216719340217,
 0.15358242570270156,
 0.15381268421200095,
 0.15404294272130034,
 0.15427320123059973,
 0.15450345973989912,
 0.15473371824919852,
 0.15496397675849791,
 0.1551942352677973,
 0.15542449377709669,
 0.15565475228639608,
 0.15588501079569547,
 0.15611526930499486,
 0.15634552781429426,
 0.15657578632359365,
 0.15680604483289304,
 0.15703630334219243,
 0.15726656185149182,
 0.15749682036079121,
 0.1577270788700906,
 0.15795733737938999,
 0.15818759588868939,
 0.15841785439798878,
 0.15864811290728817,
 0.15887837141658756,
 0.15910862992588695,
 0.15933888843518634,
 0.15956914694448573,
 0.15979940545378513,
 0.16002966396308452,
 0.16025992247238391,
 0.1604901809816833,
 0.16072043949098269,
 0.16095069800028208,
 0.16118095650958147,
 0.16141121501888087,
 0.16164147352818026,
 0.16187173203747965,
 0.16210199054677904,
 0.16233224905607843,
 0.16256250756537782,
 0.16279276607467721,
 0.16302302458397661,
 0.163253283093276,
 0.16348354160257539,
 0.16371380011187478,
 0.16394405862117417,
 0.16417431713047356,
 0.16440457563977295,
 0.16463483414907235,
 0.16486509265837174,
 0.16509535116767113,
 0.16532560967697052,
 0.16555586818626991,
 0.1657861266955693,
 0.16601638520486869,
 0.16624664371416809,
 0.16647690222346748,
 0.16670716073276687,
 0.16693741924206626,
 0.16716767775136565,
 0.16739793626066504,
 0.16762819476996443,
 0.16785845327926383,
 0.16808871178856322,
 0.16831897029786261,
 0.168549228807162,
 0.16877948731646139,
 0.16900974582576078,
 0.16924000433506017,
 0.16947026284435956,
 0.16970052135365896,
 0.16993077986295835,
 0.17016103837225774,
 0.17039129688155713,
 0.17062155539085652,
 0.17085181390015591,
 0.1710820724094553,
 0.1713123309187547,
 0.17154258942805409,
 0.17177284793735348,
 0.17200310644665287,
 0.17223336495595226,
 0.17246362346525165,
 0.17269388197455104,
 0.17292414048385044,
 0.17315439899314983,
 0.17338465750244922,
 0.17361491601174861,
 0.173845174521048,
 0.17407543303034739,
 0.17430569153964678,
 0.17453595004894618,
 0.17476620855824557,
 0.17499646706754496,
 0.17522672557684435,
 0.17545698408614374,
 0.17568724259544313,
 0.17591750110474252,
 0.17614775961404192,
 0.17637801812334131,
 0.1766082766326407,
 0.17683853514194009,
 0.17706879365123948,
 0.17729905216053887,
 0.17752931066983826,
 0.17775956917913766,
 0.17798982768843705,
 0.17822008619773644,
 0.17845034470703583,
 0.17868060321633522,
 0.17891086172563461,
 0.179141120234934,
 0.1793713787442334,
 0.17960163725353279,
 0.17983189576283218,
 0.18006215427213157,
 0.18029241278143096,
 0.18052267129073035,
 0.18075292980002974,
 0.18098318830932913,
 0.18121344681862853,
 0.18144370532792792,
 0.18167396383722731,
 0.1819042223465267,
 0.18213448085582609,
 0.18236473936512548,
 0.18259499787442487,
 0.18282525638372427,
 0.18305551489302366,
 0.18328577340232305,
 0.18351603191162244,
 0.18374629042092183,
 0.18397654893022122,
 0.18420680743952061,
 0.18443706594882001,
 0.1846673244581194,
 0.18489758296741879,
 0.18512784147671818,
 0.18535809998601757,
 0.18558835849531696,
 0.18581861700461635,
 0.18604887551391575,
 0.18627913402321514,
 0.18650939253251453,
 0.18673965104181392,
 0.18696990955111331,
 0.1872001680604127,
 0.18743042656971209,
 0.18766068507901149,
 0.18789094358831088,
 0.18812120209761027,
 0.18835146060690966,
 0.18858171911620905,
 0.18881197762550844,
 0.18904223613480783,
 0.18927249464410723,
 0.18950275315340662,
 0.18973301166270601,
 0.1899632701720054,
 0.19019352868130479,
 0.19042378719060418,
 0.19065404569990357,
 0.19088430420920297,
 0.19111456271850236,
 0.19134482122780175,
 0.19157507973710114,
 0.19180533824640053,
 0.19203559675569992,
 0.19226585526499931,
 0.1924961137742987,
 0.1927263722835981,
 0.19295663079289749,
 0.19318688930219688,
 0.19341714781149627,
 0.19364740632079566,
 0.19387766483009505,
 0.19410792333939444,
 0.19433818184869384,
 0.19456844035799323,
 0.19479869886729262,
 0.19502895737659201,
 0.1952592158858914,
 0.19548947439519079,
 0.19571973290449018,
 0.19594999141378958,
 0.19618024992308897,
 0.19641050843238836,
 0.19664076694168775,
 0.19687102545098714,
 0.19710128396028653,
 0.19733154246958592,
 0.19756180097888532,
 0.19779205948818471,
 0.1980223179974841,
 0.19825257650678349,
 0.19848283501608288,
 0.19871309352538227,
 0.19894335203468166,
 0.19917361054398106,
 0.19940386905328045,
 0.19963412756257984,
 0.19986438607187923,
 0.20009464458117862,
 0.20032490309047801,
 0.2005551615997774,
 0.2007854201090768,
 0.20101567861837619,
 0.20124593712767558,
 0.20147619563697497,
 0.20170645414627436,
 0.20193671265557375,
 0.20216697116487314,
 0.20239722967417254,
 0.20262748818347193,
 0.20285774669277132,
 0.20308800520207071,
 0.2033182637113701,
 0.20354852222066949,
 0.20377878072996888,
 0.20400903923926827,
 0.20423929774856767,
 0.20446955625786706,
 0.20469981476716645,
 0.20493007327646584,
 0.20516033178576523,
 0.20539059029506462,
 0.20562084880436401,
 0.20585110731366341,
 0.2060813658229628,
 0.20631162433226219,
 0.20654188284156158,
 0.20677214135086097,
 0.20700239986016036,
 0.20723265836945975,
 0.20746291687875915,
 0.20769317538805854,
 0.20792343389735793,
 0.20815369240665732,
 0.20838395091595671,
 0.2086142094252561,
 0.20884446793455549,
 0.20907472644385489,
 0.20930498495315428,
 0.20953524346245367,
 0.20976550197175306,
 0.20999576048105245,
 0.21022601899035184,
 0.21045627749965123,
 0.21068653600895063,
 0.21091679451825002,
 0.21114705302754941,
 0.2113773115368488,
 0.21160757004614819,
 0.21183782855544758,
 0.21206808706474697,
 0.21229834557404637,
 0.21252860408334576,
 0.21275886259264515,
 0.21298912110194454,
 0.21321937961124393,
 0.21344963812054332,
 0.21367989662984271,
 0.21391015513914211,
 0.2141404136484415,
 0.21437067215774089,
 0.21460093066704028,
 0.21483118917633967,
 0.21506144768563906,
 0.21529170619493845,
 0.21552196470423785,
 0.21575222321353724,
 0.21598248172283663,
 0.21621274023213602,
 0.21644299874143541,
 0.2166732572507348,
 0.21690351576003419,
 0.21713377426933358,
 0.21736403277863298,
 0.21759429128793237,
 0.21782454979723176,
 0.21805480830653115,
 0.21828506681583054,
 0.21851532532512993,
 0.21874558383442932,
 0.21897584234372872,
 0.21920610085302811,
 0.2194363593623275,
 0.21966661787162689,
 0.21989687638092628,
 0.22012713489022567,
 0.22035739339952506,
 0.22058765190882446,
 0.22081791041812385,
 0.22104816892742324,
 0.22127842743672263,
 0.22150868594602202,
 0.22173894445532141,
 0.2219692029646208,
 0.2221994614739202,
 0.22242971998321959,
 0.22265997849251898,
 0.22289023700181837,
 0.22312049551111776,
 0.22335075402041715,
 0.22358101252971654,
 0.22381127103901594,
 0.22404152954831533,
 0.22427178805761472,
 0.22450204656691411,
 0.2247323050762135,
 0.22496256358551289,
 0.22519282209481228,
 0.22542308060411168,
 0.22565333911341107,
 0.22588359762271046,
 0.22611385613200985,
 0.22634411464130924,
 0.22657437315060863,
 0.22680463165990802,
 0.22703489016920742,
 0.22726514867850681,
 0.2274954071878062,
 0.22772566569710559,
 0.22795592420640498,
 0.22818618271570437,
 0.22841644122500376,
 0.22864669973430315,
 0.22887695824360255,
 0.22910721675290194,
 0.22933747526220133,
 0.22956773377150072,
 0.22979799228080011,
 0.2300282507900995,
 ...]

In [ ]:


In [68]:
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[68]:
<matplotlib.text.Text at 0x10b266fd0>

In [69]:
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[69]:
<matplotlib.text.Text at 0x10a3b01d0>

In [ ]:


In [56]:
#cos_theta = np.cos(promedio_en_t)
log_cos_theta = np.log(cos_theta)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-56-6722b0140435> in <module>()
      1 #cos_theta = np.cos(promedio_en_t)
----> 2 log_cos_theta = np.log(cos_theta)

NameError: name 'cos_theta' is not defined

In [ ]:

Una simulación más en donde se ve la presición del algoritmo


In [70]:
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[70]:
<matplotlib.legend.Legend at 0x10b2fa9d0>

In [71]:
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[71]:
<matplotlib.legend.Legend at 0x10b6c5750>

In [72]:
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


-1.650188597 -0.19781314834

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 [ ]:

Para el ajuste de la recta


In [42]:
m


Out[42]:
-1.8750965595664355

In [228]:
m*np.array(tiempos)


Out[228]:
array([-0.        , -0.00471191, -0.00942383, ..., -4.7024889 ,
       -4.70720081, -4.71191272])

In [220]:
b*np.ones(len(tiempos))


Out[220]:
array([ 0.01902013,  0.01902013,  0.01902013, ...,  0.01902013,
        0.01902013,  0.01902013])

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [19]:
y = np.exp(m*np.array(tiempos) + c*np.ones(len(tiempos)))

plt.plot(tiempos, promedio_cos_theta, label = "Simulacion")
plt.plot(tiempos, y, label = "Ajuste: m = {}".format(m))
plt.yscale("log")
#plt.yscale("log")
#plt.plot(tiempos, np.exp(-4*tiempos))
#plt.plot(np.array(tiempos), np.exp(-2*np.array(tiempos)))
plt.ylabel(r'$\log{\langle \cos{\theta} \rangle}$', fontsize = 15)
plt.xlabel('tiempo', fontsize = 12)
plt.yscale("log")
plt.legend(loc=0);



In [ ]:


In [ ]:


In [ ]:


In [185]:
m = (log_cos_theta[600] - log_cos_theta[0])/(tiempos[600] - tiempos[0])

In [186]:
m


Out[186]:
-2.1813949100330605

In [66]:
m,b = np.polyfit(tiempos[:50],promedio_cos_theta[:50],1)

In [67]:
m


Out[67]:
-1.7694248358257085

In [214]:
b


Out[214]:
0.019020131276243829

In [215]:
y = m*np.array(tiempos) + b*np.ones(1001)

In [ ]:


In [ ]:


In [ ]:


In [190]:
!pwd


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/Simulaciones_01

In [191]:
%cd /Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy

In [ ]:


In [192]:
%%file Brownian_Sphere_code_02vf01.py
# %load Brownian_Sphere_code_02.py

import numpy as np
from matplotlib import pyplot as plt

#Funcion que toma un vector y regresa otro ortogonal a este.
def orto(x):
    if np.dot(x,x) == 0:
        return 'Pendejo: 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 imput x.
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.
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.
def vector_q(x,s):
    q = (R)*np.tan(s/(R))
    return q*x

#Dados todos los datos anteriores, esta funcion actualiza la posición de la particula.
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 pocision inicial y un arco de desplazamiento
#Como output da un vector de posicion nuevo dada un tipo de desplazamiento.
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 cuando es llamada grafia la posicion de la particula browniana
#sobre la superficie de una esfera sobre la que se esta difundiendo.
def plot_particle(r,i):
    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")

    #draw a point
    ax.scatter([r[0]],[r[1]],[r[2]],color="b",s=100)
    
    
    
    

    #draw sphere
    u, v = np.mgrid[0:2*np.pi:50j, (np.pi/7):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.55, linewidth = 0.15)



    #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)
    


    ax.view_init(80, 30)
    #fig.savefig('BS_Rand_01.{}.png'.format(i))
    
    plt.show()
    

    
#Esta funcion Genera n posiciones aleatorias sobre la superficie de la esfera de radio R.
#El proposito de tener esta funcion es el de generar de manera automatizada
#Una condicion inicial con distribucion uniforme sobre la esfera para varaias particulas Brownianas.
def P_INS(n,R):
    l = []
    for i in range(n):
        a1 = 2*np.pi*np.random.rand()
        a2 = np.pi*np.random.rand()
        l.append(np.array([R*np.sin(a2)*np.cos(a1),R*np.sin(a2)*np.sin(a1),R*np.cos(a2)]))
    return l

#Esta funcion cuando es llamada grafia la posicion de las partoculas brownianas.
#sobre la superficie de una esfera sobre la que se esta difundiendo.
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")

    



    #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.55, 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 points
    for p in lista:
        ax.scatter([p[0]],[p[1]],[p[2]],color="b",s=150)
    
    fig.savefig('BS_Obs_01.{}.png'.format(nombre(numero)))
    #ax.view_init(80, 30)
    plt.show()
    
#Esta función actualiza la posicion de todos los elementos de una lista; partícula brownianas.
def act_n(lista,s):
    l = []
    for v in lista:
        l.append(actualiza(v,s))
    return l

#Esta funcion simula la evolucion de n particulas brownianas difundiendose sobre la superficie de una esfera.
#Grafica cada paso o instantanea del sistema completo.
def sim_n_pb(lista, m):
    plot_particles(lista)
    sigma = lista
    for i in range(m):
        eta = act_n(sigma)
        plot_particles(eta)
        sigma = eta
        
#Funcion que pone n particulas en el polo norte de una esfera
def polo_n(n, R):
    l = []
    for i in range(n):
        l.append(np.array([0,0,R]))
    return l


#Operador de Rotación


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)


#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.

def b_steps(ri,rf,n):
    l = [ri]
    r0 = ri
    theta = np.arccos((np.dot(ri,rf))/((np.linalg.norm(ri))*(np.linalg.norm(rf))))
    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)
        l.append(vi)
        r0 = vi
    return l



#Transformacion de coordenada de esfericas a cartesianas.


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.

def trans_c_s(x,y,z):
    r = np.sqrt(x**2 + y**2 + z**2)
    theta = np.arccos(z/r)
    phi = np.arctan(y/x)
    return r, theta, phi




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])
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])
def phi_uni(theta, phi):
    x = -np.sin(theta)
    y = np.cos(phi)
    z = 0
    return np.array([x,y,z])



def collision_update(lista_vect, r_omega, theta_omega):
    for v in lista_vect:
        #angulo = np.arccos(np.dot(v,r_omega)/(np.linalg.norm(v)*np.linalg.norm(r_omega)))
        #print angulo, theta_omega
        tamanho = (R**2)*np.cos(theta_omega)
        if np.dot(v,r_omega) >= tamanho:
            print 'Choco el mother fucker'
            rp = v
            np_prima = np.cross(np.cross(r_omega, rp), rp)
            nor_p = np_prima/np.linalg.norm(np_prima)
            up_prima = np.cross(np.cross(lista_vect[0], lista_vect[-1]), rp)
            up = up_prima/np.linalg.norm(up_prima)
            tp_prima = np.cross(rp, nor_p)
            tp = tp_prima/np.linalg.norm(tp_prima)
            x = (np.dot(up,tp))*tp - (np.dot(up, nor_p))*nor_p
            v_rot_prima = np.cross(rp, x)
            v_rot = v_rot_prima/np.linalg.norm(v_rot_prima)
            ang_dif = np.arccos(np.dot(v,lista_vect[-1])/(np.linalg.norm(v)*np.linalg.norm(lista_vect[-1])))
            posicion_final = rot_theta(rp, ang_dif, v_rot)
            return v, posicion_final
        else:
            continue
    print 'no choco el mother fucker'
    return lista_vect[0], lista_vect[-1]
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
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

def ese(D,delta_t):
    return abs(np.random.normal(loc = 0., scale = np.sqrt(var(D,delta_t)),size = None))




#Definimos las condiciones inciales

# R es el radio de la esfera

R=1
def exit_time(R):
    t0 = 0
    x0 = np.array([0,0,R])
    x = x0
    t = t0
    for i in range(550):
        t = t + 25e-6
        x = actualiza(x,ese())
        #plot_particle(x,i)
        theta_x = np.arccos(x[2]/R)
        if theta_R < theta_x:
            return  t
        else:
            continue
    return 'no salio de la region'


#R = 1
#D = 1
#dt = (np.pi**2)/4
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 = 1000

for i in range(t_final):
    nuevos_vec = act_n(posicion_vec, ese(D,dt))
    thetas = []
    phis = []
    thetas_al_2 = []
    phis_al_2 = []
    for v in nuevos_vec:
        theta = np.arccos(v[2]/R)
        phi = np.arctan(v[1]/v[2])
        thetas.append(theta)
        phis.append(phi)
        thetas_al_2.append(theta**2)
        phis_al_2.append(phi**2)
    
    #Aqui vamos a salvar una instantanea de cada uno de los histogramas
    #de theta
    #plt.hist(thetas, 100, color = 'g', normed=True)
    #plt.xlabel(r"$\theta$", fontsize = 15)
    #plt.xlim(0,np.pi)
    #plt.ylabel("Frecuencia", fontsize = 15)
    #plt.ylim(0,1)
    #plt.title("Paso = {}".format(i), fontsize = 15)
    #plt.savefig('Histograma_theta_{}'.format(nombre(i)))
    #plt.close()
    mean_cos_theta = np.mean(np.cos(thetas))
    mean_theta = np.mean(thetas)
    mean_phi = np.mean(phis)
    mean_theta_cuad = np.mean(thetas_al_2)
    mean_phi_cuad = np.mean(phis_al_2)
    var_theta_en_t.append(mean_theta_cuad - mean_theta**2)
    var_phi_en_t.append(mean_phi_cuad - mean_phi**2)
    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)


Writing Brownian_Sphere_code_02vf01.py

In [ ]:


In [ ]:


In [19]:
!pwd


/Users/adriano/Documents/Tesis_Maestria/Notebooks_ipy/Histograma_Thesis_theta_NO_02

In [20]:
!mencoder "mf://*.png" -o BS_Histograma_Thesis_01.avi -ovc lavc -lavcopts vcodec=msmpeg4v2:autoaspect:vbitrate=2160000:mbd=2:keyint=132:vqblur=1.0:cmp=2:subcmp=2:dia=2:mv0:last_pred=3 -fps 4


MEncoder 1.1-4.2.1 (C) 2000-2012 MPlayer Team
192 audio & 400 video codecs
success: format: 16  data: 0x0 - 0x0
MF file format detected.
[mf] search expr: *.png
[mf] number of files: 2000 (16000)
[demux_mf] file type was not set! trying 'type=png'...
VIDEO:  [MPNG]  0x0  24bpp  25.000 fps    0.0 kbps ( 0.0 kbyte/s)
[V] filefmt:16  fourcc:0x474E504D  size:0x0  fps:25.000  ftime:=0.0400
Input fps will be interpreted as 4.000 instead.
libavcodec version 54.23.100 (internal)
Opening video filter: [expand osd=1]
Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1
==========================================================================
Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family
Selected video codec: [ffpng] vfm: ffmpeg (FFmpeg PNG)
==========================================================================
Could not find matching colorspace - retrying with -vf scale...
Opening video filter: [scale]
Movie-Aspect is undefined - no prescaling applied.
[swscaler @ 0x10cc84e90]BICUBIC scaler, from rgba to yuv420p using MMX2
videocodec: libavcodec (432x288 fourcc=3234504d [MP42])
[VE_LAVC] High quality encoding selected (non-realtime)!
Writing header...
ODML: vprp aspect is 16384:10922.
Writing header...
ODML: vprp aspect is 16384:10922.
Pos: 500.0s   2000f (100%) 49.28fps Trem:   0min  14mb  A-V:0.000 [249:0]

Skipping frame!
Pos: 500.0s   2001f (100%) 49.31fps Trem:   0min  14mb  A-V:0.000 [249:0]

Flushing video frames.
Writing index...
Writing header...
ODML: vprp aspect is 16384:10922.

Video stream:  249.559 kbit/s  (31194 B/s)  size: 15597420 bytes  500.000 secs  2001 frames

In [ ]:


In [ ]: