Manifold
class.
In [1]:
# THE BACKEND currently in use is inline plotting -- (if preferable, RESTART KERNEL to change to a GUI BACKEND OF CHOICE).
# '%matplotlib' command shows current GUI (interactive) backend defaulted.
# you cab also change backend with other magic commands such as '%matplotlib qt5'.
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import HTML
%load_ext autoreload
%autoreload 2
In [2]:
%cd ~/Documents/brownian-manifold/
to make sure we are in the brownian-manifold directory:
In [3]:
%pwd
Out[3]:
In [4]:
from brownian_manifold.manifold import Manifold
In [5]:
Manifold?
Invoke Manifold
and instantiate sphere_manifold
and cylinder_manifold
(or whatever you would like to name the specific instances of Manifold
)
In [6]:
# specify the inital paramters for 2-sphere
sphere_manifold = Manifold(manifold='sphere',
radius_sphere=1,
final_time=137.5,
n_steps=275000,
plt_interactive=False)
#note:
#setting plt_interactive to False is equivalent to plt.ioff -- meaning that interactive mode is off for mpl plotting.
#for the purpose of the Manifold Class -- plt.ioff is better for inline plotting and displaying for github.
# however for a GUI backend, interactive plotting (plt.ion / plt_interactive=True)
# is very useful when wanting to explore and/or update any plot that have been made.
In [7]:
# specify the inital paramters for finite cylinder
cylinder_manifold = Manifold(manifold='cylinder',
radius_cylinder=1,
height_cylinder=10,
final_time=137.5,
n_steps=275000,
plt_interactive=False)
#note:
#setting plt_interactive to False is equivalent to plt.ioff -- meaning that interactive mode is off for mpl plotting.
#for the purpose of the Manifold Class -- plt.ioff is better for inline plotting and displaying for github.
# however for a GUI backend, interactive plotting (plt.ion / plt_interactive=True)
# is very useful when wanting to explore and/or update any plot that have been made.
sphere_manifold
(or whatever you named it) instance of Manifold
. Let's inspect the object.type sphere_manifold.
then the tab
key on your keyboard to see the attributes and methods
Lets just print the inital attributes that we assigned to the instance:
In [8]:
print(sphere_manifold.manifold)
print(sphere_manifold.radius_sphere)
print(sphere_manifold.final_time)
print(sphere_manifold.n_steps)
# self.step_size should equal self.final_time/self.n_steps
print(sphere_manifold.step_size)
In [9]:
sphere_manifold.get_sphere?
In [10]:
sphere_surface_data = sphere_manifold.get_sphere(plot=True)
plot_sphere
method with the ability to change default plotting options:Requires the variable storing the get_sphere
surface of sphere data (i.e. this is a positional argument). The variable was named above as sphere_surface_data
(but could be named anything).
Some changeable matplotlib
option include:
show_axes
: default is False.has_title
: default is True.antialiased
: default is False. False shows lines on the sphere and when set to True the lines fade away. color
: default is cyanalpha
: transparency of the surface (0.0-transparent to 1.0-opaque) default is 0.2
In [11]:
sphere_manifold.plot_sphere?
In [12]:
sphere_manifold.plot_sphere(sphere_surface_data,
color='magenta',
alpha=0.7,
antialiased=True,
show_axes=True)
In [13]:
print(cylinder_manifold.manifold)
print(cylinder_manifold.radius_cylinder)
print(cylinder_manifold.height_cylinder)
print(cylinder_manifold.final_time)
print(cylinder_manifold.n_steps)
# self.step_size should equal self.final_time/self.n_steps
print(cylinder_manifold.step_size)
In [14]:
cylinder_manifold.get_cylinder?
In [15]:
cylinder_surface_data = cylinder_manifold.get_cylinder(plot=True)
plot_cylinder
method with the ability to change default plotting options:Requires the variable storing the get_cylinder
surface of sphere data (i.e. this is a positional argument). The variable was named above as cylinder_surface_data
(but could be named anything).
plot_sphere
method) for the options that can be changed. show_axes=True
it is visually informative to compare the height and radius of the finite cylinder.
In [16]:
cylinder_manifold.plot_cylinder(cylinder_surface_data,
color='magenta',
alpha=0.7,
antialiased=True,
show_axes=True)
In [17]:
sphere_simdata = sphere_manifold.simulate_brownian_sphere()
In [18]:
data_sphere = pd.DataFrame({'Step Number': np.arange(1,sphere_manifold.n_steps+1),
'X' : sphere_simdata[:,0],
'Y' : sphere_simdata[:,1],
'Z' : sphere_simdata[:,2]})
df = pd.DataFrame(data_sphere)
In [19]:
def hover(hover_color="#ffff99"):
return dict(selector="tr:hover",
props=[("background-color", "%s" % hover_color)])
styles = [
hover(),
dict(selector="th", props=[("font-size", "140%"),
("text-align", "center")]),
dict(selector="caption", props=[("caption-side", "bottom"),
('color', 'red'),
("text-align", "center"),
("font-size", "180%")]),
]
In [20]:
html1 = (df.head(11).style.set_table_styles(styles))
html1
Out[20]:
In [21]:
html2 = (df.tail(11).style.set_table_styles(styles)
.set_caption("Success, rotation back to the pole."))
html2
Out[21]:
Sucess: Rotated back to the pole!
[Making sure the last step is rotated back to pole (0,0,1) (and the steps are very small)]
plot_brownian_sphere method
To plot a figure after creating the simulation data simply;
steptoplot
with a list steps numbers you would like to plot per figure as the argument
In [22]:
sphere_manifold.plot_brownian_sphere(sphere_simdata,steptoplot=[275000],show_axes=True,)
In [23]:
sphere_manifold.plot_brownian_sphere(sphere_simdata,steptoplot=[10000,275000])
In [24]:
sphere_manifold.plot_brownian_sphere(sphere_simdata,steptoplot=[20000,80000,200000,275000])
In [25]:
from scipy.integrate import dblquad
#This takes a function (input as string) in cartesian coordinates and
#returns the integral of this function over the surface of the unit sphere
#after dividing by the surface area to normalize
def surface_int(f):
#convert function string to spherical coordinates assuming radius of one
#the new x is theta and the new y is phi in spherical coordinates
g='('
for i in range(len(f)):
if f[i] == 'x':
g = g+'(np.sin(y)*np.cos(x))'
elif f[i] == 'y':
g = g+'(np.sin(y)*np.sin(x))'
elif f[i] == 'z':
g = g+'(np.cos(y))'
else:
g = g+f[i]
#adds Jacobian to make the returned string the integrand
g = g+')*np.sin(y)'
#calculate the integral over the surface of the unit sphere
R = dblquad(eval('lambda y,x: '+g),0,2*np.pi,lambda x: 0,lambda x: np.pi)
#divide by surface area
return (R[0])/(4*np.pi)
In [26]:
test1 = surface_int('4*x**2 + 7*y**2')
In [27]:
print(test1)
In [28]:
test2 = surface_int('3*x**2 + y**2 + z**2')
In [29]:
print(test2)
In [30]:
dt=sphere_manifold.step_size
all_steps = np.arange(1,sphere_manifold.n_steps+1)
time_label= np.arange(dt,sphere_manifold.final_time+dt,dt)
In [31]:
tester_function_cum_output = np.cumsum(4*(sphere_simdata[:,0]**2) + 7**(sphere_simdata[:,1]**2))
space_average = tester_function_cum_output/all_steps
In [32]:
tester_function_cum_output2 = np.cumsum(3*(sphere_simdata[:,0]**2) + (sphere_simdata[:,1])**2 + (sphere_simdata[:,2])**2)
space_average2 = tester_function_cum_output2/all_steps
In [44]:
fig = plt.figure(figsize=(10,7))
ax = plt.gca()
ax.set_title("Testing for Uniform Coverage \n of the Brownian motion on $S^2$ \n\n\
red dashed-line is \n double integral of $f$ \n over surface of unit sphere",fontsize=16)
ax.set_ylabel("Space Average- \n Brownian Motion's trajectory",fontsize=18)
ax.set_xlabel('Step number (time)',fontsize=18)
ax.set_xlim(0,sphere_manifold.n_steps)
ax.set_ylim(0,4.6)
ax.legend("",title= 'blue: $f$ = $4x^2 + 7y^2$ \n\
using the simulation data',loc=5,fontsize=25)
plt.plot(all_steps,space_average,'b-')
plt.plot(all_steps,[test1]*len(all_steps),'r--')
if hasattr(plt.get_current_fig_manager(), 'window'):
fig_mgr = plt.get_current_fig_manager()
fig_mgr.window.showMinimized()
else:
plt.show()
In [46]:
fig = plt.figure(figsize=(10,7))
ax = plt.gca()
ax.set_title("Testing for Uniform Coverage \n of the Brownian motion on $S^2$ \n\n\
magenta dashed-line is \n double integral of $f$ \n over surface of unit sphere",fontsize=16)
ax.set_ylabel("Space Average- \n Brownian Motion's trajectory",fontsize=18)
ax.set_xlabel('Step number (time)',fontsize=18)
ax.set_xlim(0,sphere_manifold.n_steps)
ax.set_ylim(0,2.1)
ax.legend("",title= 'green: f = $3x^2 + y^2 + z^2$ \n\
using the simulation data',loc=5,fontsize=25)
plt.plot(all_steps,space_average2,'g-')
plt.plot(all_steps,[test2]*len(all_steps),'m--')
if hasattr(plt.get_current_fig_manager(), 'window'):
fig_mgr = plt.get_current_fig_manager()
fig_mgr.window.showMinimized()
else:
plt.show()