Machine Generation of Art Patterns in Vector Fields - python

I am trying to rewrite this article:We draw, programming. Machine-generated generation of artistic patterns in vector fields (Russian language) from pseudo-code in Python. I am new to ML, hence the following question arises: How to build a grid of angles and output it through PyCharm? I am at this stage:
import numpy as np
import math
import matplotlib.pyplot as plt
width = 100
height = 100
left_x = int(width * -0.5)
right_x = int(width * 1.5)
top_y = int(height * -0.5)
bottom_y = int(height * 1.5)
resolution = int(width * 0.01)
num_columns = int((right_x - left_x) / resolution)
num_rows = int((bottom_y - top_y) / resolution)
grid=np.ndarray((num_columns, num_rows))
grid[:,:]=math.pi * 0.25
In this code, I create a grid array in which 200 rows and 200 columns, into which the angle 'default_angle' is inserted. Please tell me whether I’m moving in the right direction and how to "draw" a grid, as in an attached link. So far I think I need to use matplotlib.

I believe you need to take a look at meshgrid from numpy
from the meshgrid documentation examples:
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)
Edit. After seeing you r link a better resource is the matplotlib quiver demo
import matplotlib.pyplot as plt
import numpy as np
X = np.arange(-10, 10, 1)
Y = np.arange(-10, 10, 1)
U, V = np.meshgrid(X, Y)
fig, ax = plt.subplots()
q = ax.quiver(X, Y, U, V)
ax.quiverkey(q, X=0.3, Y=1.1, U=10,
label='Quiver key, length = 10', labelpos='E')
plt.show()

You need to make several steps to recreate this:
create vector field based on some function or equation
normalize arrows for proper display
draw line
3.1. set starting parameters
3.2. set while out condition
3.3. calculate new position based on angle from starting point
3.4. get new position index --> net new angle
3.5. update starting positions
draw vector field and line
import numpy as np
import matplotlib.pyplot as plt
size = 50
X = np.arange(1, size, 1)
Y = np.arange(1, size, 1)
U, V = np.meshgrid(X, Y)
# Normalize the arrows:
U = U / np.sqrt(U**2 + V**2)
V = V / np.sqrt(U**2 + V**2)
# create angles field
data = []
for i in np.linspace(0, 180, Y.shape[0]):
data.append([i]*X.shape[0])
angle = np.array(data)
# set starting parameters
x_start_position = 2
y_start_position = 2
step_length = 1.0
point_angle = angle[x_start_position, y_start_position]
line_coordinates = [[x_start_position, y_start_position]]
# collect line points for each step
while x_start_position >= 2:
# calculate tep based on angle
x_step = step_length * np.cos(point_angle*np.pi/180)
y_step = step_length * np.sin(point_angle*np.pi/180)
# calculate new position
x_new_position = x_start_position + x_step
y_new_position = y_start_position + y_step
# get array index of new position
x_new_index = int(x_new_position)
y_new_index = int(y_new_position)
# get new angle
point_angle = angle[y_new_index, x_new_index]
# update start position
x_start_position = x_new_position
y_start_position = y_new_position
# collect results
line_coordinates.append([x_new_position, y_new_position])
# set line coordinates
line_data = np.array(line_coordinates)
x_line = line_data[:,0]
y_line = line_data[:,1]
# plot field
plt.quiver(X, Y, U, V, color='black', angles=angle, width=0.005)
# plot line
plt.plot(x_line, y_line, '-', color='red')
plt.show()
Output:

Related

Holoviz Polygon orientation settings

I am using holoviews+bokeh, and I would like to encircle my scatter plot data with a measure of standard deviation. Unfortunately I can't seem to get the orientation setting right. I am confused by the available descriptions:
Orientation in the Cartesian coordinate system, the
counterclockwise angle in radians between the first axis and the
horizontal
and
you can set the orientation (in radians, rotating anticlockwise)
My script and data example:
def create_plot(x, y, nstd=5):
x, y = np.asarray(x), np.asarray(y)
cov_matrix = np.cov([x, y])
eigenvalues, eigenvectors = np.linalg.eig(cov_matrix)
order = eigenvalues.argsort()[0]
angle = np.arctan2(eigenvectors[1, order], eigenvectors[1, order])
x0 = np.mean(x)
y0 = np.mean(y)
x_dir = np.cos(angle) * x - np.sin(angle) * y
y_dir = np.sin(angle) * x + np.cos(angle) * y
w = nstd * np.std(x_dir)
h = nstd * np.std(y_dir)
return hv.Ellipse(x0, y0, (w, h), orientation=-angle) * hv.Scatter((x, y))
c2x = np.random.normal(loc=-2, scale=0.6, size=200)
c2y = np.random.normal(loc=-2, scale=0.1, size=200)
combined = create_plot(c2x, c2y)
combined.opts(shared_axes=False)
Here is a solution, which draws Ellipse around the data. You math is just simplified.
import numpy as np
import holoviews as hv
from holoviews import opts
hv.extension('bokeh')
x = np.random.normal(loc=-2, scale=0.6, size=200)
y = np.random.normal(loc=-2, scale=0.1, size=200)
def create_plot(x, y, nstd=5):
x, y = np.asarray(x), np.asarray(y)
x0 = np.mean(x)
y0 = np.mean(y)
w = np.std(x)*nstd
h = np.std(y)*nstd
return hv.Ellipse(x0, y0, (w, h)) * hv.Scatter((x, y))
combined = create_plot(c2x, c2y)
combined.opts()
This gives you a plot which looks like a circle. To make it more visiable that it is a Ellipse your could genereate the plot calling
def hook(plot, element):
plot.handles['x_range'].start = -4
plot.handles['x_range'].end = 0
plot.handles['y_range'].start = -2.5
plot.handles['y_range'].end = -1
combined.opts(hooks=[hook])
which set fixed ranges and deactivates the auto focus.
In your example w and h were nearly the same, that means, you drawed a cercle. The orientation didn't have any effect. With the code above you can turn the Ellipse like
hv.Ellipse(x0, y0, (w, h), orientation=np.pi/2)
to see that it is working, but there is no need to do it anymore.

stackoverflow error in 2d fipy PDE solver in python

I am trying to solve a system of three coupled PDEs and two ODEs (coupled) in 2D. The problem tries to solve for a case of a particle moving in a medium. The medium is given by the fields- velocity components vx, vy, and density m and there is one particle moving in this medium with position Rx, Ry.
It runs fine for a while but then throws up errors:
"Fatal Python error: Cannot recover from stack overflow.
Current thread 0x00007fe155915700 (most recent call first):"
Here is the code:
"""
"""
from fipy import (CellVariable, PeriodicGrid2D, Viewer, TransientTerm, DiffusionTerm,
UniformNoiseVariable, LinearLUSolver, numerix,
ImplicitSourceTerm, ExponentialConvectionTerm, VanLeerConvectionTerm,
PowerLawConvectionTerm, Variable)
import sys
import inspect
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
from scipy.optimize import curve_fit
from scipy.signal import correlate
from scipy.stats import kurtosis
from scipy.interpolate import interp1d
numerix.random.seed(2)
def run_simulation(f0, Total_time):
# Define mesh size and number of points
nx = 50
ny = nx
L = 50
dx = L / nx
dy = dx
mesh = PeriodicGrid2D(dx, dy, nx, ny)
# Variables to use
vx = CellVariable(name='vx', mesh=mesh, hasOld=1)
vy = CellVariable(name='vy', mesh=mesh, hasOld=1)
m = CellVariable(name='m', mesh=mesh, hasOld=1)
# Initial condition
m.setValue(UniformNoiseVariable(mesh=mesh, minimum=0.6215, maximum=0.6225))
vx.setValue(UniformNoiseVariable(mesh=mesh, minimum=0, maximum=0.00001))
vy.setValue(UniformNoiseVariable(mesh=mesh, minimum=0, maximum=0.00001))
#particle position
x0=10.0
y0=25.0
# create grids for grad function
xgrid=np.unique(mesh.x.value)+dx/2
ygrid=np.unique(mesh.y.value)+dy/2
# parameters ------------------------------
B=4.0
Gamma=1.0
gamma=1.0
Dm=0.005
C=100.0
## save the initial positions in Rx,Ry
Rx=Variable(value=x0)
Ry=Variable(value=y0)
theta=Variable(value=0.0) # n-hat = cos(theta) x-hat + sin(theta) y-hat
sigma = 1
dt = 0.05
#-----------------------------------------
x_hat = [1.0, 0.0]
y_hat = [0.0, 1.0]
#------------- dirac delta function --------------
# https://stackoverflow.com/questions/58041222/dirac-delta-source-term-in-fipy
def delta_func(x, y, epsilon):
return ((x < epsilon) & (x > -epsilon) & (y < epsilon) & (y > -epsilon)) * \
(1 + numerix.cos(numerix.pi * x / epsilon) * numerix.cos(numerix.pi * y / epsilon)) / 2 / epsilon
############## equations #############
# renormalized parameters by Gamma
# fields : velocity vector, density scalar
# Gamma * v = -B rho(grad(rho)) + f* n-cap* delta(r-R), B>0, f>0, Gamma>0
# dot(rho) + del.(v rho) = 0
# particle
# dot(R) = (f/gamma)*(n-cap) - (C/gamma) * rho(grad(rho)) C>0
# Gamma=gamma=1, B' = B/Gamma, C'=C/gamma, f'=f/Gamma
######################################
eq_m = (TransientTerm(var=m) + ExponentialConvectionTerm(coeff=x_hat * vx + y_hat * vy, var=m) == DiffusionTerm(coeff=Dm, var=m) )
eq_vx = (ImplicitSourceTerm(coeff=1., var=vx) == -(B/Gamma)*m.grad.dot(x_hat)*(m) + (f0/Gamma)*numerix.cos(theta)* delta_func(mesh.x-Rx,mesh.y-Ry,sigma) )
eq_vy = (ImplicitSourceTerm(coeff=1., var=vy) == -(B/Gamma)*m.grad.dot(y_hat)*(m) + (f0/Gamma)*numerix.sin(theta)* delta_func(mesh.x-Rx,mesh.y-Ry,sigma) )
eq = eq_m & eq_vx & eq_vy
viewer = Viewer(vars=(m))
elapsed = 0.0
ms = []
vxs = []
vys = []
xs = []
ys = []
while elapsed < Total_time:
# Old values are used for sweeping when solving nonlinear values
vx.updateOld()
vy.updateOld()
m.updateOld()
print(elapsed, Rx, Ry)
mgrid=np.reshape(m.value,(nx,ny))
# gradient cal, dydx[0][x,y], dydx[1][x,y] -> x derivative, y derivative at x,y
dydx=np.gradient(mgrid,dx,dy,edge_order=2)
# impose periodic boundary on gradient
dydx[0][nx-1,:]=(mgrid[0,:]-mgrid[nx-2,:])/(2.0*dx)
dydx[0][0,:]=(mgrid[1,:]-mgrid[nx-1,:])/(2.0*dx)
dydx[1][:,ny-1]=(mgrid[:,0]-mgrid[:,ny-2])/(2.0*dy)
dydx[1][:,0]=(mgrid[:,1]-mgrid[:,ny-1])/(2.0*dy)
# solve ode
idx = np.argmin(np.abs(xgrid - Rx))
idy = np.argmin(np.abs(ygrid - Ry))
x0=x0+ ((f0/gamma)*np.cos(theta) - C*mgrid[idx,idy]*dydx[0][idx,idy])*dt
y0=y0+ ((f0/gamma)*np.sin(theta) - C*mgrid[idx,idy]*dydx[1][idx,idy])*dt
if(x0>L):
x0=x0-L
if(x0<0):
x0=x0+L
if(y0>L):
y0=y0-L
if(y0<0):
y0=y0+L
Rx.setValue(x0) # element-wise assignment did not work
Ry.setValue(y0)
elapsed += dt
res = 1e5
old_res = res * 2
step = 0
while res > 1e-5 and step < 5 and old_res / res > 1.01:
old_res = res
res = eq.sweep(dt=dt)
step += 1
# The variable values are just numpy arrays so easy to use!
# save velocity & density
vxs.append(vx.value.copy())
vys.append(vy.value.copy())
ms.append(m.value.copy())
viewer.plot()
# save x and y positions
xs.append(mesh.x.value.copy())
ys.append(mesh.y.value.copy())
return ms, vxs, vys, xs, ys
if __name__ == '__main__':
path = 'result/'
Total_time= 50 #40
f0 = 2
ms, vxs, vys, xs, ys = run_simulation(f0,Total_time)
name = 'f0_{:.4f}'.format(f0)
y = np.array([ms, vxs, vys])
xx = np.reshape(xs,(50,50))
yy = np.reshape(ys,(50,50))
vx = np.reshape(vxs[800][:],(50,50))
vy = np.reshape(vys[800][:],(50,50))
print(np.shape(xx), np.shape(xs), np.shape(vx))
#np.save(path + name, y)
plt.imshow(np.reshape(ms[800][:],(50,50)), aspect='auto', interpolation='bicubic', cmap='jet', extent=[0, 50, 50, 0])
plt.colorbar(label='density m')
plt.xlabel(r'$x $')
plt.ylabel(r'$y $')
plt.gcf().savefig(path + 'rho_'+name+'.png', format='png', bbox_inches='tight')
plt.clf()
#---------------------------------------------
plt.imshow(np.reshape(vxs[800][:],(50,50)), aspect='auto', interpolation='bicubic', cmap='jet', extent=[0, 50, 50, 0])
plt.colorbar(label='velocity vx')
plt.xlabel(r'$x $')
plt.ylabel(r'$y $')
plt.gcf().savefig(path + 'vel_'+name+'.png', format='png', bbox_inches='tight')
plt.clf()
#---------------------------------------------
plt.quiver(xx,yy,vx,vy,scale=3)
plt.xlabel(r'$x $')
plt.ylabel(r'$y $')
plt.gcf().savefig(path + 'v_'+name+'.png', format='png', bbox_inches='tight')
plt.clf()
What can cause this error? I am not defining the equation inside the loop (this caused a similar problem before). Thank you in advance for your help.
UPDATE
I changed the function calling for x.mesh as
delta_func(xp,yp,sigma) where xp and yp are xp=Variable(value=mesh.x-Rx) and yp=Variable(value=mesh.y-Ry). Directly calling the x.mesh might have caused the problem according to an answer to my old question. But that did not help, I am still getting the overflow error. Here is the new version of the code:
"""
"""
from fipy import (CellVariable, PeriodicGrid2D, Viewer, TransientTerm, DiffusionTerm,
UniformNoiseVariable, LinearLUSolver, numerix,
ImplicitSourceTerm, ExponentialConvectionTerm, VanLeerConvectionTerm,
PowerLawConvectionTerm, Variable)
import sys
import inspect
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
from scipy.optimize import curve_fit
from scipy.signal import correlate
from scipy.stats import kurtosis
from scipy.interpolate import interp1d
numerix.random.seed(2)
def run_simulation(f0, Total_time):
# Define mesh size and number of points
nx = 50
ny = nx
L = 50
dx = L / nx
dy = dx
mesh = PeriodicGrid2D(dx, dy, nx, ny)
# Variables to use
vx = CellVariable(name='vx', mesh=mesh, hasOld=1)
vy = CellVariable(name='vy', mesh=mesh, hasOld=1)
m = CellVariable(name='m', mesh=mesh, hasOld=1)
# Initial condition
m.setValue(UniformNoiseVariable(mesh=mesh, minimum=0.6215, maximum=0.6225))
vx.setValue(UniformNoiseVariable(mesh=mesh, minimum=0, maximum=0.00001))
vy.setValue(UniformNoiseVariable(mesh=mesh, minimum=0, maximum=0.00001))
#particle position
x0=10.0
y0=25.0
# create grids for grad function
xgrid=np.unique(mesh.x.value)+dx/2
ygrid=np.unique(mesh.y.value)+dy/2
# parameters ------------------------------
B=4.0
Gamma=1.0
gamma=1.0
Dm=0.005
C=100.0
## save the initial positions in Rx,Ry
Rx=Variable(value=x0)
Ry=Variable(value=y0)
theta=Variable(value=0.0) # n-hat = cos(theta) x-hat + sin(theta) y-hat
sigma = 1
dt = 0.05
#-----------------------------------------
xp=Variable(value=mesh.x-Rx)
yp=Variable(value=mesh.y-Ry)
x_hat = [1.0, 0.0]
y_hat = [0.0, 1.0]
#------------- dirac delta function --------------
# https://stackoverflow.com/questions/58041222/dirac-delta-source-term-in-fipy
def delta_func(x, y, epsilon):
return ((x < epsilon) & (x > -epsilon) & (y < epsilon) & (y > -epsilon)) * \
(1 + numerix.cos(numerix.pi * x / epsilon) * numerix.cos(numerix.pi * y / epsilon)) / 2 / epsilon
############## equations #############
# renormalized parameters by Gamma
# fields : velocity vector, density scalar
# Gamma * v = -B rho(grad(rho)) + f* n-cap* delta(r-R), B>0, f>0, Gamma>0
# dot(rho) + del.(v rho) = 0
# particle
# dot(R) = (f/gamma)*(n-cap) - (C/gamma) * rho(grad(rho)) C>0
# Gamma=gamma=1, B' = B/Gamma, C'=C/gamma, f'=f/Gamma
######################################
eq_m = (TransientTerm(var=m) + ExponentialConvectionTerm(coeff=x_hat * vx + y_hat * vy, var=m) == DiffusionTerm(coeff=Dm, var=m) )
eq_vx = (ImplicitSourceTerm(coeff=1., var=vx) == -(B/Gamma)*m.grad.dot(x_hat)*(m) + (f0/Gamma)*numerix.cos(theta)* delta_func(xp,yp,sigma) )
eq_vy = (ImplicitSourceTerm(coeff=1., var=vy) == -(B/Gamma)*m.grad.dot(y_hat)*(m) + (f0/Gamma)*numerix.sin(theta)* delta_func(xp,yp,sigma) )
eq = eq_m & eq_vx & eq_vy
viewer = Viewer(vars=(m))
elapsed = 0.0
ms = []
vxs = []
vys = []
xs = []
ys = []
while elapsed < Total_time:
# Old values are used for sweeping when solving nonlinear values
vx.updateOld()
vy.updateOld()
m.updateOld()
print(elapsed, Rx, Ry)
mgrid=np.reshape(m.value,(nx,ny))
# gradient cal, dydx[0][x,y], dydx[1][x,y] -> x derivative, y derivative at x,y
dydx=np.gradient(mgrid,dx,dy,edge_order=2)
# impose periodic boundary on gradient
dydx[0][nx-1,:]=(mgrid[0,:]-mgrid[nx-2,:])/(2.0*dx)
dydx[0][0,:]=(mgrid[1,:]-mgrid[nx-1,:])/(2.0*dx)
dydx[1][:,ny-1]=(mgrid[:,0]-mgrid[:,ny-2])/(2.0*dy)
dydx[1][:,0]=(mgrid[:,1]-mgrid[:,ny-1])/(2.0*dy)
# solve ode
idx = np.argmin(np.abs(xgrid - Rx))
idy = np.argmin(np.abs(ygrid - Ry))
x0=x0+ ((f0/gamma)*np.cos(theta) - C*mgrid[idx,idy]*dydx[0][idx,idy])*dt
y0=y0+ ((f0/gamma)*np.sin(theta) - C*mgrid[idx,idy]*dydx[1][idx,idy])*dt
if(x0>L):
x0=x0-L
if(x0<0):
x0=x0+L
if(y0>L):
y0=y0-L
if(y0<0):
y0=y0+L
Rx.setValue(x0) # element-wise assignment did not work
Ry.setValue(y0)
elapsed += dt
res = 1e5
old_res = res * 2
step = 0
while res > 1e-5 and step < 5 and old_res / res > 1.01:
old_res = res
res = eq.sweep(dt=dt)
step += 1
# The variable values are just numpy arrays so easy to use!
# save velocity & density
vxs.append(vx.value.copy())
vys.append(vy.value.copy())
ms.append(m.value.copy())
viewer.plot()
# save x and y positions
xs.append(mesh.x.value.copy())
ys.append(mesh.y.value.copy())
return ms, vxs, vys, xs, ys
if __name__ == '__main__':
path = 'result/'
Total_time= 100 #40
f0 = 2
ms, vxs, vys, xs, ys = run_simulation(f0,Total_time)
name = 'f0_{:.4f}'.format(f0)
y = np.array([ms, vxs, vys])
xx = np.reshape(xs,(50,50))
yy = np.reshape(ys,(50,50))
vx = np.reshape(vxs[380][:],(50,50))
vy = np.reshape(vys[380][:],(50,50))
print(np.shape(xx), np.shape(xs), np.shape(vx))
#np.save(path + name, y)
plt.imshow(np.reshape(ms[380][:],(50,50)), aspect='auto', interpolation='bicubic', cmap='jet', extent=[0, 50, 50, 0])
plt.colorbar(label='density m')
plt.xlabel(r'$x $')
plt.ylabel(r'$y $')
plt.gcf().savefig(path + 'rho_'+name+'.png', format='png', bbox_inches='tight')
plt.clf()
#---------------------------------------------
plt.imshow(np.reshape(vxs[380][:],(50,50)), aspect='auto', interpolation='bicubic', cmap='jet', extent=[0, 50, 50, 0])
plt.colorbar(label='velocity vx')
plt.xlabel(r'$x $')
plt.ylabel(r'$y $')
plt.gcf().savefig(path + 'vel_'+name+'.png', format='png', bbox_inches='tight')
plt.clf()
#---------------------------------------------
plt.quiver(xx,yy,vx,vy,scale=3)
plt.xlabel(r'$x $')
plt.ylabel(r'$y $')
plt.gcf().savefig(path + 'v_'+name+'.png', format='png', bbox_inches='tight')
plt.clf()
I must confess that I ran out of patience before getting the stack overflow error, but I was able to identify the problem.
It's a similar (although more subtle) issue to what you reported before. Because theta is declared as a Variable,
x0=x0+ ((f0/gamma)*np.cos(theta) - C*mgrid[idx,idy]*dydx[0][idx,idy])*dt
y0=y0+ ((f0/gamma)*np.sin(theta) - C*mgrid[idx,idy]*dydx[1][idx,idy])*dt
result in longer and longer Variable expressions (and longer and longer step times). I.e., x0 = (((x0_0 + dx0_1) + dx0_2) + dx0_3) + dx0_4 + ...
Changing these to
x0=x0+ (((f0/gamma)*np.cos(theta) - C*mgrid[idx,idy]*dydx[0][idx,idy])*dt).value
y0=y0+ (((f0/gamma)*np.sin(theta) - C*mgrid[idx,idy]*dydx[1][idx,idy])*dt).value
resolves this issue.
Addressing the warning following the question edit
The warning in the comments about "...has been cast to a constant CellVariable" is due to:
xp=Variable(value=mesh.x-Rx)
yp=Variable(value=mesh.y-Ry)
This is definitely not recommended. This takes the MeshVariable objects mesh.x and mesh.y and then throws away the mesh. When the result is later associated with a mesh, e.g., by multiplying by another MeshVariable or using as a SourceTerm, FiPy warns because it looks like it could fit on the mesh, but it's not on a mesh. Just use
xp=mesh.x-Rx
yp=mesh.y-Ry

creating a set of random points on the surface of a sphere

i wrote a code to generate a set of random points on the surface of concentric spheres,where on each sphere I would generate a certain number of points depending on how many concentric sphere surfaces I want as seen in the code written below,you can try to run it and maybe get a better understanding of the issue at hand:
class point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
R_list=(0.001 , 0.002, 0.003 , 0.004 ,0.005)
num_points = 1000/len(R_list)
LD1 = 0.05
LD23 = 0.025
obj_points = []
condition = True
for R in R_list:
while len(rpoints) < num_points:
theta = np.random.uniform(-math.pi, math.pi)
phi = np.random.uniform(-math.pi, math.pi)
pi = R * math.cos(theta) * math.sin(phi) + (LD1 / 2), R * math.sin(theta) * math.sin(phi) + (
LD23 / 2), R * math.cos(phi) + (LD23 / 2)
obj_points.append(point(pi[0], pi[1], pi[2]))
# plott array
lt = len(obj_points)
Vis_arr = np.zeros((lt, 3))
n = 0
for n in range(0, lt-1 ):
Vis_arr[n][0] = obj_points[n].x
Vis_arr[n][1] = obj_points[n].y
Vis_arr[n][2] = obj_points[n].z
# scattering of points
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# scattering of points
ax.scatter3D(Vis_arr[:, 0], Vis_arr[:, 1], Vis_arr[:, 2], marker="o")
# graph output fully no evolution
plt.show()
but when I run the code a random point appears out of nowhere:
I suspect that this is an error in creating the arrays of points but I cant detect the exact reason of the problem.
You have two errors in your code:
while len(rpoints) < num_points:
should be:
while len(obj_points) < num_points:
and
for n in range(0, lt-1 ):
should be:
for n in range(0, lt ):

Plotting 3D Surface with Sage Math

I am trying to plot a 3D surface using SageMath Cloud but I am having some trouble because the documentation for matplotlib does not appear to be very thorough and is lacking in examples. Anyways the program I have written is to plot the Heat Equation solution that I got from analytical method.
The case is:
Heat Equation
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from sympy import *
from math import *
x = np.linspace(-8, 8, 100)
t = np.linspace(-8, 8, 100)
n = symbols('n', integer=True)
X, T = np.meshgrid(x, t)
an = float(2 / 10) * integrate(50 * sin(radians((2 * n + 1) * pi * x / 20)), (x, 0, 10))
Z = summation(an * e**(2 * n + 1 / 20)**2*pi**2*t * sin(radians((2 * n + 1) * pi * x / 20)), (n, 0, oo))
fig = plt.figure()
ax = fig.gca(projection = '3d')
surf = ax.plot_surface(X, T, Z,
rstride = 3,
cstride = 3,
cmap = cm.coolwarm,
linewidth = 0.5,
antialiased = True)
fig.colorbar(surf,
shrink=0.8,
aspect=16,
orientation = 'vertical')
ax.view_init(elev=60, azim=50)
ax.dist=8
plt.show()
I am getting this error when I run the code to plot the graph: "Error in lines 7-7
Traceback (most recent call last):
File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 968, in execute
exec compile(block+'\n', '', 'single') in namespace, locals
File "", line 1, in
File "/projects/sage/sage-7.3/local/lib/python2.7/site-packages/numpy/core/function_base.py", line 93, in linspace
dt = result_type(start, stop, float(num))
TypeError: data type not understood"
Please, any and all help is very greatly appreicated. I think the error comes up because I defined x = np.linspace(-8, 8, 100) and t = np.linspace(-8, 8, 100) but it is necessary to make the original program run. I am unsure of how to correct this so the graph plots properly. Thanks!
Your piece of code has problem with these two lines:
an = float(2 / 10) * integrate(50 * sin(radians((2 * n + 1) * pi * x / 20)), (x, 0, 10))
Z = summation(an * e**(2 * n + 1 / 20)**2*pi**2*t * sin(radians((2 * n + 1) * pi * x / 20)), (n, 0, oo))
I would suggest that you use simple for-loop to compute some other simple values for Z first to confirm that everythng is fine. Try replace the 2 lines with this:
# begin simple calculation for Z
# offered just for example
Z = []
y = symbols('y') # declare symbol for integration
for ix,ea in enumerate(x):
ans = integrate(y * sin(ea / 20), (y, 0, x[ix])) # integrate y from y=0 to y=x(ix)
Z.append(ans)
Z = np.array(Z, dtype=float) # convert Z to array
# end of simple calculation for Z
When you run it, you should get some plot as a result. For your intended values of Z, you have better situation to compute them with simple for-loop.

Python: heat density plot in a disk

My goal is to make a density heat map plot of sphere in 2D. The plotting code below the line works when I use rectangular domains. However, I am trying to use the code for a circular domain. The radius of sphere is 1. The code I have so far is:
from pylab import *
import numpy as np
from matplotlib.colors import LightSource
from numpy.polynomial.legendre import leggauss, legval
xi = 0.0
xf = 1.0
numx = 500
yi = 0.0
yf = 1.0
numy = 500
def f(x):
if 0 <= x <= 1:
return 100
if -1 <= x <= 0:
return 0
deg = 1000
xx, w = leggauss(deg)
L = np.polynomial.legendre.legval(xx, np.identity(deg))
integral = (L * (f(x) * w)[None,:]).sum(axis = 1)
c = (np.arange(1, 500) + 0.5) * integral[1:500]
def r(x, y):
return np.sqrt(x ** 2 + y ** 2)
theta = np.arctan2(y, x)
x, y = np.linspace(0, 1, 500000)
def T(x, y):
return (sum(r(x, y) ** l * c[:,None] *
np.polynomial.legendre.legval(xx, identity(deg)) for l in range(1, 500)))
T(x, y) should equal the sum of c the coefficients times the radius as a function of x and y to the l power times the legendre polynomial where the argument is of the legendre polynomial is cos(theta).
In python: integrating a piecewise function, I learned how to use the Legendre polynomials in a summation but that method is slightly different, and for the plotting, I need a function T(x, y).
This is the plotting code.
densityinterpolation = 'bilinear'
densitycolormap = cm.jet
densityshadedflag = False
densitybarflag = True
gridflag = True
plotfilename = 'laplacesphere.eps'
x = arange(xi, xf, (xf - xi) / (numx - 1))
y = arange(yi, yf, (yf - yi) / (numy - 1))
X, Y = meshgrid(x, y)
z = T(X, Y)
if densityshadedflag:
ls = LightSource(azdeg = 120, altdeg = 65)
rgb = ls.shade(z, densitycolormap)
im = imshow(rgb, extent = [xi, xf, yi, yf], cmap = densitycolormap)
else:
im = imshow(z, extent = [xi, xf, yi, yf], cmap = densitycolormap)
im.set_interpolation(densityinterpolation)
if densitybarflag:
colorbar(im)
grid(gridflag)
show()
I made the plot in Mathematica for reference of what my end goal is
If you set the values outside of the disk domain (or whichever domain you want) to float('nan'), those points will be ignored when plotting (leaving them in white color).

Categories

Resources