In [1]:
#ONDA SINUSIDAL ANIMADA
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01) # x-array
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10.0)) # update the data
return line,
#Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=25, blit=True)
plt.show()
In [1]:
#2 GRAFICAS INTERACTIVAS AL TIEMPO
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_line(num, data, line):
line.set_data(data[...,:num])
return line,
fig1 = plt.figure()
data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
#line_ani.save('lines.mp4')
fig2 = plt.figure()
x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
ims = []
for add in np.arange(15):
ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))
im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
blit=True)
#im_ani.save('im.mp4', metadata={'artist':'Guido'})
plt.show()
In [3]:
#CORPUSCULOS ANIME IMAGE
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im = plt.imshow(f(x, y), cmap=plt.get_cmap('jet'))
def updatefig(*args):
global x,y
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x,y))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
In [2]:
#COMET
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import newton
x = np.linspace(0, 6.0, 100)
y = np.linspace(0, 1.4, 100)
font = {'family' : 'serif',
'color' : 'darkred',
'weight' : 'normal',
'size' : 16,
}
plt.title('GRAFICA TAREA 1', fontdict=font)
font = {'family' : 'serif',
'color' : 'darkblue',
'weight' : 'normal',
'size' : 13,
}
font = {'family' : 'serif',
'color' : 'black',
'weight' : 'normal',
'size' : 16,
}
plt.text(2.2, 0.85, r'$\ 1-exp(-x)$', fontdict=font)
plt.text(3, 0.5, r'$\ x/5$', fontdict=font)
plt.plot(x, 1-np.exp(-x), x, x / 5)
def f(x):
return 1-np.exp(-x) - x/5
sol2 = newton(f, 5.0)
font = {'family' : 'serif',
'color' : 'black',
'weight' : 'normal',
'size' : 13,
}
plt.text(2, 1.01, 'Punto de corte x = %f'% sol2, fontdict=font)
plt.show()
In [3]:
#EULER CON INDICADOR DE COORDENADAS
from math import sin
from numpy import arange
from pylab import plot,xlabel,ylabel,show
def f(x,t):
return -x**3 + sin(t)
a = 0.0 # Start of the interval
b = 10.0 # End of the interval
N = 1000 # Number of steps
h = (b-a)/N # Size of a single step
x = 0.0 # Initial condition
tpoints = arange(a,b,h)
xpoints = []
for t in tpoints:
xpoints.append(x)
x += h*f(x,t)
plot(tpoints,xpoints)
xlabel("t")
ylabel("x(t)")
show()
In [4]:
#ENVENODD
print("Enter two integers, one even, one odd.")
m = int(input("Enter the first integer: "))
n = int(input("Enter the second integer: "))
while (m+n)%2==0:
print("One must be even and the other odd.")
m = int(input("Enter the first integer: "))
n = int(input("Enter the second integer: "))
print("The numbers you chose are",m,"and",n)
In [6]:
#HEAT ZHEATPROPAG CON LECTURA DE COORDENADAS
from numpy import empty
from pylab import plot,xlabel,ylabel,show
# Constants
L = 0.01 # Thickness of steel in meters
D = 4.25e-6 # Thermal diffusivity
N = 100 # Number of divisions in grid
a = L/N # Grid spacing
h = 1e-4 # Time-step
epsilon = h/1000
Tlo = 0.0 # Low temperature in Celcius
Tmid = 20.0 # Intermediate temperature in Celcius
Thi = 50.0 # Hi temperature in Celcius
t1 = 0.01
t2 = 0.1
t3 = 0.4
t4 = 1.0
t5 = 10.0
tend = t5 + epsilon
# Create arrays
T = empty(N+1,float)
T[0] = Thi
T[N] = Tlo
T[1:N] = Tmid
Tp = empty(N+1,float)
Tp[0] = Thi
Tp[N] = Tlo
# Main loop
t = 0.0
c = h*D/(a*a)
while t<tend:
# Calculate the new values of T
for i in range(1,N):
Tp[i] = T[i] + c*(T[i+1]+T[i-1]-2*T[i])
T,Tp = Tp,T
t += h
# Make plots at the given times
if abs(t-t1)<epsilon:
plot(T)
if abs(t-t2)<epsilon:
plot(T)
if abs(t-t3)<epsilon:
plot(T)
if abs(t-t4)<epsilon:
plot(T)
if abs(t-t5)<epsilon:
plot(T)
xlabel("x")
ylabel("T")
show()
In [7]:
#CONVERTIR DE POLARES A RECTANGULARES
from math import sin,cos,pi
# Ask the user for the values of r and theta
r = float(input("Ingresa magnitud r: "))
d = float(input("Ingresa angulo en grados: "))
# Convert the angle to radians
theta = d*pi/180
# Calculate the equivalent Cartesian coordinates
x = r*cos(theta)
y = r*sin(theta)
# Print out the results
print("x = ",x,", y = ",y)
In [8]:
#RIPPLES
from math import sqrt,sin,pi
from numpy import empty
from pylab import imshow,gray,show
wavelength = 5.0
k = 2*pi/wavelength
xi0 = 1.0
separation = 20.0 # Separation of centers in cm
side = 100.0 # Side of the square in cm
points = 500 # Number of grid points along each side
spacing = side/points # Spacing of points in cm
# Calculate the positions of the centers of the circles
x1 = side/2 + separation/2
y1 = side/2
x2 = side/2 - separation/2
y2 = side/2
# Make an array to store the heights
xi = empty([points,points],float)
# Calculate the values in the array
for i in range(points):
y = spacing*i
for j in range(points):
x = spacing*j
r1 = sqrt((x-x1)**2+(y-y1)**2)
r2 = sqrt((x-x2)**2+(y-y2)**2)
xi[i,j] = xi0*sin(k*r1) + xi0*sin(k*r2)
# Make the plot
imshow(xi,origin="lower",extent=[0,side,0,side])
gray()
show()
In [9]:
#Programa principal para encontrar la energía utilizando el método de la secante
from numpy import array,arange
# Constants
m = 9.1094e-31 # Mass of electron
hbar = 1.0546e-34 # Planck's constant over 2*pi
e = 1.6022e-19 # Electron charge
L = 5.2918e-11 # Bohr radius
N = 1000
h = L/N
# Potential function
def V(x):
return 0.0
def f(r,x,E):
psi = r[0]
phi = r[1]
fpsi = phi
fphi = (2*m/hbar**2)*(V(x)-E)*psi
return array([fpsi,fphi],float)
# Calculate the wavefunction for a particular energy
def solve(E):
psi = 0.0
phi = 1.0
r = array([psi,phi],float)
for x in arange(0,L,h):
k1 = h*f(r,x,E)
k2 = h*f(r+0.5*k1,x+0.5*h,E)
k3 = h*f(r+0.5*k2,x+0.5*h,E)
k4 = h*f(r+k3,x+h,E)
r += (k1+2*k2+2*k3+k4)/6
return r[0]
# Main program to find the energy using the secant method
E1 = 0.0
E2 = e
psi2 = solve(E1)
target = e/1000
while abs(E1-E2)>target:
psi1,psi2 = psi2,solve(E2)
E1,E2 = E2,E2-psi2*(E2-E1)/(psi2-psi1)
print("E =",E2/e,"eV")
In [10]:
#GRAFICA 3D CON VARIACIONES DE COLOR SEGUN PROFUNDIDAD
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
In [2]:
#SOLUCION POR CRUCE DE 2 CURVAS
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import newton
x = np.linspace(0, 6.0, 100)
y = np.linspace(0, 1.4, 100)
font = {'family' : 'serif',
'color' : 'darkred',
'weight' : 'normal',
'size' : 16,
}
plt.title('GRAFICA TAREA 1', fontdict=font)
font = {'family' : 'serif',
'color' : 'darkblue',
'weight' : 'normal',
'size' : 13,
}
plt.text(2.4, 0.2, 'Entregado por el estudiante:', fontdict=font)
plt.text(2.4, 0.12, 'Diego Javier Mena - 20092005053', fontdict=font)
plt.text(2.4, 0.04, '', fontdict=font)
font = {'family' : 'serif',
'color' : 'black',
'weight' : 'normal',
'size' : 16,
}
plt.text(2.2, 0.85, r'$\ 1-exp(-x)$', fontdict=font)
plt.text(3, 0.5, r'$\ x/5$', fontdict=font)
plt.plot(x, 1-np.exp(-x), x, x / 5)
def f(x):
return 1-np.exp(-x) - x/5
sol2 = newton(f, 5.0)
font = {'family' : 'serif',
'color' : 'black',
'weight' : 'normal',
'size' : 13,
}
plt.text(2, 1.01, 'punto de corte X=%f'% sol2, fontdict=font)
plt.show()
In [12]:
#SUPERFICIE 3D Y PUNTOS EN EL ESPACIO
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import mpl_toolkits.mplot3d.axes3d as axes3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
#Data
fx = [0.673574075,0.727952994,0.6746285,0.797313558,0.37664721,0.67939197,0.748490102,0.722048276,0.767189284,0.768296082,0.732383162,0.748429373,0.751570337,0.698977802,0.703398777,0.802607746,0.786242535,0.366661714,0.792490268,0.698636545,0.769904493,0.762656928,0.478595152,0.759151743,0.728607906,0.778099194,0.728575153,0.703794547]
fy = [0.331657721,0.447817839,0.37733386,0.306640864,0.107229109,0.329287287,0.758907052,0.310634309,0.277462605,0.333935925,0.326699919,0.72242944,0.358848707,0.298222369,0.306303486,0.43058538,0.373973649,0.117132288,0.432939444,0.255479494,0.384761779,0.382446444,0.35914706,0.298360515,0.391041147,0.363895412,0.312359532,0.343344197]
fz = [18.13629648,8.620699842,9.807536512,17.40105183,24.44101897,18.81025228,8.075948931,18.10817229,22.24192367,13.8497555,13.28436202,4.472128831,14.53195939,15.93922217,0,0,11.28194885,0,0,26.12423918,9.200498046,14.01392223,14.14545413,17.8320704,8.985897324,10.53443457,12.48561226,11.80438073]
#generate data for regression equation
Xs = np.arange(0.4, 0.8, 0.005)
Ys = np.arange(0.2, 0.7, 0.005)
Xs, Ys = np.meshgrid(Xs, Ys)
#3D regression solved using DataFit(R), http://www.oakdaleengr.com/
Zs = 41.0909875400163+15.3581432751401*np.log(Xs)+-90.9714747515509*Ys+64.9652271333282*Ys**2
ax.plot(fx, fy, fz, linestyle="none", marker="o", mfc="none", markeredgecolor="red")
#plot wireframe
#ax.plot_wireframe(Xs, Ys, Zs, rstride=4, cstride=4, alpha=0.4)
#plot surface, more colormaps: http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html
ax.plot_surface(Xs, Ys, Zs, rstride=4, cstride=4, alpha=0.4,cmap=cm.jet)
plt.show()
In [2]:
#PUNTOS Y TRIANGULOS EN EL ESPACIO
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def randrange(n, vmin, vmax):
return (vmax-vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
In [8]:
#MALLAS DE SUPERFICIE
# imports specific to the plots in this example
import numpy as np
from matplotlib import cm
from mpl_toolkits.mplot3d.axes3d import get_test_data
fig = plt.figure(figsize=(9.5,5.0))
#---- First subplot
ax = fig.add_subplot(1, 2, 1, projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,
linewidth=0, antialiased=False)
ax.set_zlim3d(-1.01, 1.01)
fig.colorbar(surf, shrink=0.5, aspect=10)
#---- Second subplot
ax = fig.add_subplot(1, 2, 2, projection='3d')
X, Y, Z = get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()
In [3]:
#EJES COORDENADOS DE 3 DIMENSIONES EN EL ESPACIO
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
fig = plt.figure(dpi=100)
ax = fig.add_subplot(111, projection='3d')
#data
fx = [0.673574075,0.727952994,0.6746285]
fy = [0.331657721,0.447817839,0.37733386]
fz = [18.13629648,8.620699842,9.807536512]
#error data
xerror = [0.041504064,0.02402152,0.059383144]
yerror = [0.015649804,0.12643117,0.068676131]
zerror = [3.677693713,1.345712547,0.724095592]
#plot points
ax.plot(fx, fy, fz, linestyle="None", marker="o")
#plot errorbars
for i in np.arange(0, len(fx)):
ax.plot([fx[i]+xerror[i], fx[i]-xerror[i]], [fy[i], fy[i]], [fz[i], fz[i]], marker="_")
ax.plot([fx[i], fx[i]], [fy[i]+yerror[i], fy[i]-yerror[i]], [fz[i], fz[i]], marker="_")
ax.plot([fx[i], fx[i]], [fy[i], fy[i]], [fz[i]+zerror[i], fz[i]-zerror[i]], marker="_")
#configure axes
ax.set_xlim3d(0.55, 0.8)
ax.set_ylim3d(0.2, 0.5)
ax.set_zlim3d(8, 19)
plt.show()
In [21]:
#SOMBRERO 3D
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
step = 0.04
maxval = 1.0
fig = plt.figure()
ax = Axes3D(fig)
# create supporting points in polar coordinates
r = np.linspace(0,1.25,50)
p = np.linspace(0,2*np.pi,50)
R,P = np.meshgrid(r,p)
# transform them to cartesian system
X,Y = R*np.cos(P),R*np.sin(P)
Z = ((R**2 - 1)**2)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet)
ax.set_zlim3d(0, 1)
ax.set_xlabel(r'$\phi_\mathrm{real}$')
ax.set_ylabel(r'$\phi_\mathrm{im}$')
ax.set_zlabel(r'$V(\phi)$')
ax.set_xticks([])
plt.show()
In [16]:
#SUPERFICIE VOLCANICA 3D
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet)
plt.show()
In [ ]:
#PUNTOS EN EL ESPACIO
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = [-10, 3, 4, 5, 10]
Y = [100, 150, 250, 320, 400]
Z = [12, 23, 33, 44, 52]
ax.plot(X,Y,Z, ls="None", marker="o")
ax.set_xlabel("X")
plt.show()
In [20]:
#SUPERFICIE 3D CON MALLAS TRANSPARENTES
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.1)
ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
ax.set_zlim3d(0, 80)
plt.show()
In [4]:
#IDENTIFICANDO COORDENADAS DE PUNTO MAXIMO PARA SIN(X)
import numpy as np
import matplotlib.pyplot as plt
#http://matplotlib.sourceforge.net/examples/pylab_examples/spine_placement_demo.html
fig = plt.figure(figsize=(4, 5))
ax = fig.add_subplot(111)
x = np.arange(-2*np.pi, 2*np.pi, 0.01)
y = np.sin(x)
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.plot(x, y,linewidth="3", alpha=0.3)
ax.plot([0, np.pi/2], [1, 1], ls="--", color="green", linewidth="3",alpha=0.5)
ax.plot([np.pi/2, np.pi/2], [1, 0], ls="--", color="red", linewidth="3",alpha=0.5)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.set_xlim(-2*np.pi, 2*np.pi)
xticker = np.arange(-np.pi-np.pi/2, np.pi+np.pi, np.pi/2)
xlabels = [r"$\frac{-3\pi}{2}$", r"${-\pi}$",r"$\frac{-\pi}{2}$","",r"$\frac{pi}{2}$",r"${\pi}$",r"$\frac{3\pi}{2}$"]
ax.set_xticks(xticker)
ax.set_xticklabels(xlabels, size=17)
ax.text(np.pi, 1.1, "y=sin(x)")
ax.set_ylim(-1.5, 1.5)
yticker = np.arange(-1, 2, 1)
ax.set_yticks(yticker)
plt.show()
In [22]:
#GRAFICA BATALLA NAVAL
import numpy as np
import matplotlib.pyplot as plt
#data
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [3, 2, 5, 7, 4, 2, 4, 6, 7, 8]
ysize = [10, 20, 4, 15, 9, 9, 14, 8, 4, 9]
for i in range (0, len(x)):
plt.plot(x[i], y[i], linestyle="None", marker="o", markersize=ysize[i], color="red")
plt.plot(x, y, linestyle="dotted", color="red")
plt.xlim(np.min(x)-1.3, np.max(x)+1.3) #optional
plt.ylim(np.min(y)-1.3, np.max(y)+1.3) #optional
plt.xlabel("random y")
plt.ylabel("random x")
plt.show()
In [9]:
#EJERCICIO DE FISICA CONEJOS VS LOBOS
#Lotka-Volterra
#This is a predator-prey model of rabbits and foxes.
#The equations are first order, non-linear differential equations.
# du/dt = a*u - b*u*v
# dv/dt = -c*v + d*b*u*v
#
# u - the number of rabbits
# v - the number of foxes
#
# "a" is the natural growing rate of rabbits, when there's no fox
# "b" is the natural dying rate of rabbits, due to predation
# "c" is the natural dying rate of fox, when there's no rabbit
# "d" describes how much a caught rabbit contributes to creating a new fox
#
from numpy import *
from scipy import integrate
import pylab as p
# Definition of parameters
a = 1. #Rabbit growth rate (without foxes)
b = 0.1 #Rabbit death rate (how fast they are being eaten)
c = 1.5 #Fox death rate (not eating)
d = .75 #Fox creation rate from eating a single rabbit
def dX_dt(X, t=0):
""" Return the growth rate of fox and rabbit populations as a single array.
The input X is an array that has both u and v values.
du/dt = a*u - b*u*v
dv/dt = -c*v + d*b*u*v
"""
u=X[0]
v=X[1]
du=(a*u) - (b*u*v)
dv=(-c*v) + (d*b*u*v)
return array([ du , dv ])
def main():
t = linspace(0, 15, 1000) # make 1000 time steps
X0 = array([10, 5]) # initials conditions: 10 rabbits and 5 foxes
X = integrate.odeint(dX_dt, X0, t)
rabbits=X[:,0]
foxes=X[:,1]
p.figure()
p.plot(t, rabbits, 'r-', label='Rabbits')
p.plot(t, foxes , 'b-', label='Foxes')
p.grid()
p.legend(loc='best')
p.xlabel('time')
p.ylabel('population')
p.title('Evolution of fox and rabbit populations')
p.show()
if __name__ == "__main__":
main()
In [2]:
#GRAFICA INTERACTIVA SLIDERS CONEJOS VS. LOBOS
#Lotka-Volterra
#This is a predator-prey model of rabbits and foxes.
#The equations are first order, non-linear differential equations.
# du/dt = a*u - b*u*v
# dv/dt = -c*v + d*b*u*v
#
# u - the number of rabbits
# v - the number of foxes
#
# "a" is the natural growing rate of rabbits, when there's no fox
# "b" is the natural dying rate of rabbits, due to predation
# "c" is the natural dying rate of fox, when there's no rabbit
# "d" describes how much a caught rabbit contributes to creating a new fox
#
from numpy import *
from scipy import integrate
from matplotlib.widgets import Slider
import pylab as p
# Definition of parameters
rgrowth = 1. #Rabbit growth rate (without foxes)
rdeath = 0.1 #Rabbit death rate (how fast they are being eaten)
fdeath = 1.5 #Fox death rate (not eating)
fgrowth = .75 #Fox creation rate from eating a single rabbit
def dX_dt(X, t=0):
""" Return the growth rate of fox and rabbit populations as a single array.
The input X is an array that has both rabbit and fox populations.
change in rabbit population = rabbit growth * rabbit population - rabbit death * rabbit population * fox population
change in fox population = -fox death * fox population + fox growth * rabbit death * rabbit population * fox population
"""
rpop=X[0]
fpop=X[1]
d_rpop=(rgrowth * rpop) - (rdeath * rpop * fpop)
d_fpop=(-fdeath * fpop) + (fgrowth * rdeath * rpop * fpop)
return array([ d_rpop , d_fpop ])
def main():
t = linspace(0, 15, 1000) # make 1000 time steps
initialcond = array([10, 5]) # initials conditions: 10 rabbits and 5 foxes
solution = integrate.odeint(dX_dt, initialcond, t)
rabbits=solution[:,0]
foxes=solution[:,1]
p.figure()
mainaxis=p.axes([.25,.25,.65,.65])
p.plot(t, rabbits, 'r-', label='Rabbits')
p.plot(t, foxes , 'b-', label='Foxes')
p.grid()
p.legend()
p.xlabel('time')
p.ylabel('population')
p.title('Evolution of fox and rabbit populations')
axdeath=p.axes([0.25, 0.1, 0.65, 0.03])
axcreate=p.axes([0.25, 0.15, 0.65, 0.03])
s_foxdeath=Slider(axdeath, 'Fox Death', .1, 3, valinit=fdeath )
s_foxcreate=Slider(axcreate, 'Fox Create', .1, 3, valinit=fgrowth )
def update(val):
global fdeath
global fgrowth
fdeath=s_foxdeath.val
fgrowth=s_foxcreate.val
solution=integrate.odeint(dX_dt, initialcond, t)
rabbits=solution[:,0]
foxes=solution[:,1]
p.axes(mainaxis)
p.cla()
p.plot(t, rabbits, 'r-', label='Rabbits')
p.plot(t, foxes , 'b-', label='Foxes')
p.grid()
p.legend()
p.xlabel('time')
p.ylabel('population')
p.title('Evolution of fox and rabbit populations')
p.draw()
s_foxdeath.on_changed(update)
s_foxcreate.on_changed(update)
p.show()
if __name__ == "__main__":
main()
In [5]:
#CURVAS DE RADIACION DEL CUERPO NEGRO
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 100)
y = np.linspace(0, 50, 100)
font = {'family' : 'serif',
'color' : 'darkred',
'weight' : 'normal',
'size' : 16,
}
plt.title('Ley de Planck', fontdict=font)
plt.text(0.5, 23, r'$\ Physics \ of \ Semiconductor$', fontdict=font)
plt.text(0.5, 21, r'$\ Professor \ Pedro \ Ignacio \ Deaza$', fontdict=font)
plt.plot(x, ((x**5)*(np.exp(1/x)-1))**(-1), x, ((x**5)*(np.exp(1/(0.9*x))-1))**(-1), x, ((x**5)*(np.exp(1/(0.8*x))-1))**(-1))
plt.show()
In [4]:
#MODOS DE PROPAGACION EN FIBRA OPTICA
import numpy as np
import matplotlib.pyplot as plt
n=1
w=1000
e2=0.00005
e1=1e-6
alpha=np.arange(0.1, 20.0, 0.1)
a=n*np.pi/alpha;
b=alpha*np.sqrt( (w**2)*(e2-e1)/(alpha**2) -1 )
x=np.tan(0.5*alpha*a)
y=-1/(np.tan(0.5*alpha*a))
plt.plot(alpha,b,'g')
plt.plot(alpha,x)
plt.plot(alpha,y,'r--')
plt.xlabel('alpha')
plt.xlim(0,20)
plt.ylim(0,10)
plt.xlabel('alpha)')
plt.ylabel('tan(0.5*alpha*a')
plt.title(u'modos de propagacion en fibra optica')
plt.grid()
plt.show()
In [3]:
#SUPERFICIES K-LAMBDA
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
r=np.linspace(0.4,15,50)
th=np.linspace(0,2*np.pi,90)
r,th =np.meshgrid(r, th)
X=r*np.cos(th);
Y=r*np.sin(th);
Z=(np.sin(th))**2*((1/(r)**2) + 1)*np.cos(0 - r + np.arctan(r))
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax.set_xlabel('X=r*cos(th)')
ax.set_ylabel('y=r*sin(th)')
ax.set_zlabel('z')
ax.set_title(u'Superficies k~landa barra')
plt.show()
In [4]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.2, bottom=0.25)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
s = a0*np.sin(2*np.pi*f0*t)
l, = plt.plot(t, s, lw=2, color='red')
plt.axis([0, 1, -10, 10])
axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
def update(val):
amp = samp.val
freq = sfreq.val
l.set_ydata(amp*np.sin(2*np.pi*freq*t))
fig.canvas.draw_idle()
sfreq.on_changed(update)
samp.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
def reset(event):
sfreq.reset()
samp.reset()
button.on_clicked(reset)
rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
def colorfunc(label):
l.set_color(label)
fig.canvas.draw_idle()
radio.on_clicked(colorfunc)
plt.show()
In [2]:
>>> from scipy.constants import codata
>>> codata.value('elementary charge')
Out[2]:
In [3]:
>>> from scipy.constants import codata
>>> codata.unit('atomic unit of action')
Out[3]:
In [5]:
#Diego Javier Mena Amado Cod.:20092005053
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
import scipy.constants
from pylab import plot,xlabel,ylabel,show
from sympy import *
#Ajuste de workstation
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.1, bottom=0.25)
t = np.arange(0, 0.99, 0.001)
a0 = 1
#s = a0*np.sin(2*np.pi*t)
#print (t,a0)
PLANCK =((t**5)*(np.exp(1/(t-a0)-1))**(-1))
l, = plt.plot(t, PLANCK, lw=1, color='red')
#Definimos limites de barrido
#plt.xlim((0.0008, 1))
#plt.ylim((0, 30))
plt.axis([0, 1, 0, 30])
#Agregamos mas resolucion al trazado de las curvas
x = np.linspace(0.01, 1, 1000)
y = np.linspace(0, 30, 1000)
#Asignamos nombres a nuestro sistema de coordenadas
xlabel("t")
ylabel("x(t)")
#Se añaden constantes debido a falta de comprension de libreria para constantes fisicas
k=1.38*10**(-23)
h=6.62*10**(-34) #constante de Planck
c=3*10**8
#Se cargan los estilos para las curvas
style = {'family' : 'serif','color' : 'blue','weight' : 'normal','size' : 14}
style1 = {'family' : 'serif','color' : 'green','weight' : 'normal','size' : 14}
style2 = {'family' : 'serif','color' : 'red','weight' : 'normal','size' : 14}
style3 = {'family' : 'serif','color' : 'black','weight' : 'normal','size' : 14}
style4 = {'family' : 'serif','color' : 'purple','weight' : 'normal','size' : 14}
#Se cargan los label's para identificar cada curva y sus desasrrolladores
plt.title(r'Fisica de Semiconductores', fontdict=style2)
plt.text(0.53, 28, r'$\ Diego \ Javier \ Mena $', fontdict=style3)
plt.text(0.23, 20, r'$\ Ley \ de \ Planck $', fontdict=style)
plt.text(0.52, 18, r'$\ Ley \ de \ Rayleigh-Jeans $', fontdict=style4)
plt.text(0.185, 25, r'$\ Limite \ de \ Wien $', fontdict=style3)
#Ecuación Ley de Planck
plt.plot(x, ((x**5)*(np.exp(1/x)-1))**(-1),
x, ((x**5)*(np.exp(1/(0.9*x))-1))**(-1),
x, ((x**5)*(np.exp(1/(0.8*x))-1))**(-1))
#Ecuación Rayleigh-Jeans
plt.plot(x, 1/(x**4), x,1/(0.9*x**4),x,1/(0.8*x**4) )
#Ecuación Limite de Wien
plt.plot(x,np.exp(((1)/(x)))*10**(-0.87))
#implementamos Slider para variaciones de Ley de Planck
axcolor = 'lightgoldenrodyellow'
axamp = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
samp = Slider(axamp, 'Amp', 0.1, 1.3, valinit=a0)
#Establecemos la funcion a variar con el slider
def update(val):
amp = samp.val
l.set_ydata(((t**5)*(np.exp(1/(t*amp))-1))**(-1))
fig.canvas.draw_idle()
samp.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
#implementamos Cuadro Selector de Color
rax = plt.axes([0.025, 0.05, 0.15, 0.15], axisbg=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
def colorfunc(label):
l.set_color(label)
fig.canvas.draw_idle()
radio.on_clicked(colorfunc)
#Mostramos el Grafico
plt.show()
In [ ]:
In [ ]: