3D Surface Streaming in Plotly - python

I am trying to generate a 3D surface using Plotly's streaming API and I receive no errors in the actual Python code however I get the "Oops! An error occured while loading this plot's data" on Plotly. Here is my code:
import plotly.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go
from random import uniform
import pandas as pd
import time
tls.set_credentials_file(username='', api_key='')
stream_id = tls.get_credentials_file()['stream_ids']
token = stream_id[-1]
stream_id = dict(token=token)
z = []
surface = go.Surface(z=z, stream=stream_id)
data = [surface]
layout = go.Layout(
title='Test',
autosize=False,
width=500,
height=500,
margin=dict(
l=65,
r=50,
b=65,
t=90
)
)
fig = go.Figure(data=data, layout=layout)
plot_url = py.iplot(fig, filename='elevations-3d-surface', auto_open=True)
s = py.Stream(stream_id=token)
s.open()
matrices = []
for p in range(5):
matrix = []
for x in range(25):
row = []
for y in range(25):
row.append(uniform(25, 100))
matrix.append(row)
test = pd.DataFrame(matrix)
print(test)
matrices.append(matrix)
print(pd.DataFrame(matrices[1]))
i = 0
while True:
step = 3
z = matrices[i]
s.write(go.Surface(z=z))
time.sleep(step)
i += 1
if i == len(matrices):
i = 0
print(i)
# print(pd.DataFrame(z))
s.close()

Got it work, here is my final code:
import plotly.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go
import scipy.ndimage as ndimage
from random import uniform
import pandas as pd
import numpy as np
import time
tls.set_credentials_file(username='', api_key='')
stream_id = tls.get_credentials_file()['stream_ids']
token = stream_id[-1]
stream_id = dict(token=token)
z_init = np.zeros(100).reshape((10, 10))
z = z_init
surface = go.Surface(z=z, stream=stream_id)
data = [surface]
layout = go.Layout(
title='Test',
autosize=False,
width=500,
height=500,
margin=dict(
l=65,
r=50,
b=65,
t=90
)
)
fig = go.Figure(data=data, layout=layout)
plot_url = py.iplot(fig, filename='', auto_open=True)
s = py.Stream(stream_id=token)
s.open()
arr_width = 25
arr_length = 25
matrices = []
for p in range(100):
matrix = []
for x in range(arr_width):
row = []
for y in range(arr_length):
row.append(uniform(-1, 1))
matrix.append(row)
matrices.append(matrix)
##################################################################
# given 2 arrays arr1, arr2, number of steps between arrays, and order of interpolation
# numpoints = 10
# order = 2
# arr1 = matrices[1]
# arr2 = matrices[2]
def interp(arr1, arr2, numpoints, order):
# rejoin arr1, arr2 into a single array of shape (2, 10, 10)
arr = np.r_['0, 3', arr1, arr2]
# define the grid coordinates where you want to interpolate
X, Y = np.meshgrid(np.arange(arr_width), np.arange(arr_length))
k = 0
interp_arr_vec = []
while k <= 1:
coordinates = np.ones((arr_width, arr_length))*k, X, Y
# given arr interpolate at coordinates
interp_arr = ndimage.map_coordinates(arr, coordinates, order=order).T
interp_arr_vec.append(interp_arr)
step = 1 / numpoints
k += step
return interp_arr_vec
##################################################################
sleep_time = .1
i = 0
while True:
between_test = interp(matrices[i], matrices[i+1], 200, 3)
r = 0
for r in range(len(between_test)):
s.write(go.Surface(z=between_test[r]))
time.sleep(sleep_time)
i += 1
print('i = ', i)
time.sleep(3)
if i == len(matrices):
i = 0
s.close()

Related

I'm trying to figure out this error " TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'"

I'm running this code any this error keeps popping up "TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'". Most likely this line is causing a problem
----> 2 sols = odeint(VJJmodel,[0,0],ts, args=tuple([params]) )
Please advise.
from scipy.integrate import odeint
import numpy as np
import scipy.constants as const
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
from scipy.integrate import quad
import collections
Ic = 1e-6
Rsg = 10e3
Rn = Rsg
Cj = 2e-15
Rin = 100e0
Vgap = 4*Ic*Rn/np.pi #Gap voltage linked to IcRn, SIS relation
Vn = 1.1 #0.1*Vgap/Ic/Rin
V0 = Vn*Rin*Ic
phi0 = const.value('mag. flux quantum')
wp = 1/np.sqrt(Cj*phi0/2/np.pi/Ic)
params = {'Vn':Vn, 'Rsg': Rsg, 'Rn':Rn, 'Vgap':Vgap, 'Cj':Cj, 'Rin':Rin, 'wp':wp}
print(Vn)
taustop = 20* wp * Rsg*Cj
params['taustop'] = taustop
print(params)
def Rj(V,params):
Vgap = params['Vgap']
if V>Vgap:
return params['Rn']
elif V<=Vgap:
return params['Rsg']
def Q(V,params):
Cj = params['Cj']
Rin = params['Rin']
wp = params['wp']
return Cj*wp/(1/Rj(V,params)+1/Rin)
def Vs(t,params):
if not hasattr(t,'__len__'):
t = np.array([t])
result = []
for x in t:
if x <params['taustop']/2:
result.append(x/(params['taustop']/2)*params['Vn'])
else:
result.append(params['Vn'])
#return params['Vn']
result = np.ones(len(t))*params['Vn']
return np.array(result)
def VJJmodel(z,t,params):
f = z[0]
g = z[1]
V = phi0/2/np.pi*g
fp = g
gp = Vs(t,params)-(1/Q(V,params)*g+np.sin(f))
return np.array([fp,gp])
ts = np.linspace(0,2*taustop,2000)
sols = odeint(VJJmodel,[0,0],ts, args=tuple([params]) )
solsfunc = interp1d(ts,sols.T)
Vjunc = lambda x: phi0/2/np.pi * wp * solsfunc(x)[1]
taurep = 2*np.pi/np.average(np.diff(sols[:,0])/np.diff(ts))
fig = plt.figure(figsize=(10,10))
plt.clf()
plt.subplot(3, 1, 1)
plt.title('Voltage/Vgap')
plt.plot(ts,Vjunc(ts) / Vgap)
plt.subplot(3, 1, 2)
plt.title('Current')
plt.plot(ts,np.sin(solsfunc(ts)[0]))
plt.plot(ts,(Vs(ts,params)*Ic*Rin-Vjunc(ts))/Rin/Ic)
plt.ylim([-2,2])
plt.subplot(3, 1, 3)
plt.title('Phase')
plt.plot(ts,solsfunc(ts)[0])
plt.show()
plt.close(fig)
I tried to rewrite it but it didn't work.

Python matplotlib - set_data and set_3d_properties don't seem to be updating my plot

I am currently working on a Yee Solver script for uni, but when I try to animate my 3D graph, the graph is not what is expected. It works for a 2D plot, but I can't seem to translate that into 3D. From my understanding, set_data and set_3d_properties need a 1D array to work, which I am inputting.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib.widgets import Slider
# Program Variables
wv_lgth_num = 10
graph_type = '3d'
t = 0
# Physical Constants
c = 3e8
mu_r = 1
eps_r = 1
# Source Constants
f = 2e9
omega = 2*f*(np.pi)
amp = 1.0
wv_lgth = c/f
period = 1/f
# Step size
dz = wv_lgth/20
dt = ((c/f)/20)/c
#dt = ((1/f)/20)/1
# Axis Grids
z_grid = np.arange(0,wv_lgth_num*wv_lgth,dz)
t_grid = np.arange(0,10*period,dt)
# Number of steps
num_z = z_grid.size
num_t = t_grid.size
# Coefficients
coe_E = c*dt/(eps_r*dz)
coe_H = c*dt/(mu_r*dz)
# E and H Matricies
E_mat = np.zeros((num_z,num_t))
H_mat = np.zeros((num_z,num_t))
# Generating Values for E and H
for time in range(0,num_t-1):
for pos in range(0,num_z-1):
# Source Wave
if pos == 0:
H_mat[0,time] = amp*np.sin(omega*t_grid[time])
# All cases of Yee Solver
if pos == 1:
if time == 0:
H_mat[1,0] = 0
E_mat[0,0] = 0
else:
H_mat[1,time] = H_mat[1,time-1] + coe_H*(E_mat[1,time-1] - E_mat[0,time-1])
E_mat[0,time] = E_mat[0,time-1] + coe_E*(H_mat[1,time] - H_mat[0,time])
if pos > 1 and pos != num_z-1:
if time == 0:
H_mat[pos,0] = 0
E_mat[pos-1,0] = 0
if time > 0:
H_mat[pos,time] = H_mat[pos,time-1] + coe_H*(E_mat[pos,time-1] - E_mat[pos-1,time-1])
E_mat[pos-1,time] = E_mat[pos-1,time-1] + coe_E*(H_mat[pos,time] - H_mat[pos-1,time])
if pos == num_z-1:
if time == 0:
H_mat[num_z-1,0] = 0
E_mat[num_z-2,0] = 0
E_mat[num_z-1,0] = 0
if time > 0:
H_mat[num_z-1,time] = H_mat[num_z-1,time-1] + coe_H*(E_mat[num_z-1,time-1] - E_mat[num_z-2,time-1])
E_mat[num_z-2,time] = E_mat[num_z-2,time-1] + coe_E*(H_mat[num_z-1,time] - H_mat[num_z-2,time])
E_mat[num_z-1,time] = E_mat[num_z-2,time]
def update(val):
t = slider_time.val
if graph_type == '2d':
a.set_ydata(E_mat[:,t])
b.set_ydata(H_mat[:,t])
if graph_type == '3d':
a.set_3d_properties(E_mat[:,t])
a.set_data(z_grid,np.zeros((num_z,num_t))[:,t])
b.set_3d_properties(np.zeros((num_z,num_t))[:,t])
b.set_data(z_grid,H_mat[:t])
fig.canvas.draw_idle()
print(H_mat)
print(H_mat[:,t].size)
print(z_grid)
print(np.zeros((num_z,num_t))[:,t].size)
# Creating plot
if graph_type == '3d':
fig, ax = plt.subplots()
ax = plt.axes(projection='3d')
b, = ax.plot3D(z_grid,H_mat[:,t],np.zeros((num_z,num_t))[:,t], label='H')
a, = ax.plot3D(z_grid,np.zeros((num_z,num_t))[:,t],E_mat[:,t], label='E')
plt.title('Light Wave')
ax.set_xlabel('z')
ax.set_ylabel('x')
ax.set_zlabel('y')
plt.legend()
ax_time = plt.axes([0.25,0.1,0.65,0.03])
slider_time = Slider(ax_time,'Time',0,num_t-2,valinit=0,valstep=1)
slider_time.on_changed(update)
plt.show()
if graph_type == '2d':
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
a, = plt.plot(z_grid,E_mat[:,t], label='E (yz plane)')
b, = plt.plot(z_grid,H_mat[:,t], label='H (xz plane)')
plt.title('Light Wave')
plt.xlabel('z')
plt.ylabel('x')
plt.legend()
ax_time = plt.axes([0.25,0.1,0.65,0.03])
slider_time = Slider(ax_time,'Time',0,num_t-2,valinit=0,valstep=1)
slider_time.on_changed(update)
plt.show()
Any help would be appreciated. The middle for loop is just generating my functions, using the Yee Method.

How to Animate a 3D graph on Python

I'm looking to animate my graph (below) and I'm not sure where or how to start since I have no experience animating. I'm not sure how it works or what the structure of the code should be, so if someone can offer a pseudo-code or an algorithm, I would greatly appreciate it. I have provided the code I used to graph the plot below, too.
enter code here
from scipy.integrate import odeint
import scipy as sci
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as ani
# Universal Gravitational Const.
G = 6.674e-11
# Defining Mass
m1 = 2
m2 = 3.5
m3 = 2.3
# Init positions in graph (array)
pos1 = [-5,0,1]
pos2 = [5,0,10]
pos3 = [0,1,3]
p01 = np.array(pos1)
p02 = np.array(pos2)
p03 = np.array(pos3)
# Init velocities (array)
vi1 = [1,0.01,0]
vi2 = [-5,0,1]
vi3 = [0,-1,0]
v01 = np.array(vi1)
v02 = np.array(vi2)
v03 = np.array(vi3)
#Function
def derivs_func(y,t,G,m1,m2,m3):
d1 = y[:3]
d2 = y[3:6]
d3 = y[6:9]
v1 = y[9:12]
v2 = y[12:15]
v3 = y[15:18]
dist12 = np.sqrt((pos2[0]-pos1[0])**2 + (pos2[1]-pos1[1])**2 + (pos2[2]-pos1[2])**2)
dist13 = np.sqrt((pos3[0]-pos1[0])**2 + (pos3[1]-pos1[1])**2 + (pos3[2]-pos1[2])**2)
dist23 = np.sqrt((pos3[0]-pos2[0])**2 + (pos3[1]-pos2[1])**2 + (pos3[2]-pos2[2])**2)
dv1dt = m2 * (d2-d1)/dist12**3 + m3 * (d3-d1)/dist13**3
dv2dt = m1 * (d1-d2)/dist12**3 + m3 * (d3-d2)/dist23**3
dv3dt = m1 * (d1-d3)/dist13**3 + m2 * (d2-d3)/dist23**3
dd1dt = v1
dd2dt = v2
dd3dt = v3
derivs = np.array([dd1dt,dd2dt,dd3dt,dv1dt,dv2dt,dv3dt])
derivs3 = derivs.flatten()
return derivs3
yo = np.array([p01, p02, p03, v01, v02, v03])
y0 = yo.flatten()
time = np.linspace(0,200,500)
sol = odeint(derivs_func, y0, time, args = (G,m1,m2,m3))
x1 = sol[:,:3]
x2 = sol[:,3:6]
x3 = sol[:,6:9]
fig = plt.figure(figsize = (15,15))
ax = fig.add_subplot(111,projection = '3d')
ax.plot(x1[:,0],x1[:,1],x1[:,2],color = 'b')
ax.plot(x2[:,0],x2[:,1],x2[:,2],color = 'm')
ax.plot(x3[:,0],x3[:,1],x3[:,2],color = 'g')
ax.scatter(x1[-1,0],x1[-1,1],x1[-1,2],color = 'b', marker = 'o', s=30, label = 'Mass 1')
ax.scatter(x2[-1,0],x2[-1,1],x2[-1,2],color = 'm', marker = 'o',s=90, label = 'Mass 2')
ax.scatter(x3[-1,0],x3[-1,1],x3[-1,2],color = 'g', marker = 'o',s=60, label = 'Mass 3')
ax.legend()

Bokeh how to get GlyphRenderer for Annotation

With Bokeh, how do I get a handle to the Renderer (or GlyphRenderer) for an Annotation? Is this possible?
I would like to be able to toggle a Band (which is an Annotation) on and off with an interactive legend, so I need to be able to pass a list of Renderers to the LegendItem constructor.
This code:
maxline = fig.line(x='Date', y=stn_max, line_width=0.5, legend=stn_max, name="{}_line".format(stn_max), color=stn_color, alpha=0.75, source=source)
minline = fig.line(x='Date', y=stn_min, line_width=0.5, legend=stn_min, name="{}_line".format(stn_min), color=stn_color, alpha=0.75, source=source)
band = bkm.Band(base='Date', lower=stn_min, upper=stn_max, fill_alpha=0.50, line_width=0.5, fill_color=stn_color, source=source)
bkm.LegendItem(label=stn, renderers=[maxline, minline, band])
Produces this error
...
ValueError: expected an element of List(Instance(GlyphRenderer)), got seq with invalid items [Band(id='1091', ...)]
For LegendItem only instances of GlyphRenderer can be passed to its renderers attribute and Band is not based on GlyphRenderer so it gives error. In the code below the Band visibility is being toggled by means of a callback:
from bokeh.plotting import figure, show
from bokeh.models import Band, ColumnDataSource, Legend, LegendItem, CustomJS
import pandas as pd
import numpy as np
x = np.random.random(2500) * 140 - 20
y = np.random.normal(size = 2500) * 2 + 5
df = pd.DataFrame(data = dict(x = x, y = y)).sort_values(by = "x")
sem = lambda x: x.std() / np.sqrt(x.size)
df2 = df.y.rolling(window = 100).agg({"y_mean": np.mean, "y_std": np.std, "y_sem": sem})
df2 = df2.fillna(method = 'bfill')
df = pd.concat([df, df2], axis = 1)
df['lower'] = df.y_mean - df.y_std
df['upper'] = df.y_mean + df.y_std
source = ColumnDataSource(df.reset_index())
p = figure(tools = "pan,wheel_zoom,box_zoom,reset,save")
scatter = p.scatter(x = 'x', y = 'y', line_color = None, fill_alpha = 0.3, size = 5, source = source)
band = Band(base = 'x', lower = 'lower', upper = 'upper', source = source)
p.add_layout(band)
p.title.text = "Rolling Standard Deviation"
p.xaxis.axis_label = 'X'
p.yaxis.axis_label = 'Y'
callback = CustomJS(args = dict(band = band), code = """
if (band.visible == false)
band.visible = true;
else
band.visible = false; """)
legend = Legend(items = [ LegendItem(label = "x", renderers = [scatter, band.source.selection_policy]) ])
legend.click_policy = 'hide'
scatter.js_on_change('visible', callback)
p.add_layout(legend)
show(p)
Result:

How to square the individual matrix value using python?

Cost function implemented with Python:
**Thanks for help to achieve this.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
load_data = pd.read_csv('C:\python_program\ex1data1.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
plt.scatter(load_data[0],load_data[1],marker='+',c = 'r')
plt.title("Cost_Function")
plt.xlabel("Population of City in 10,000s")
plt.ylabel("Profit in $10,000s")
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
prediction = np.dot(X,theta.T)
error = (prediction-y.T)
error_df = pd.DataFrame(error)
#square the error
squared_error = np.square(error_df)
sum = np.sum(squared_error)
print(sum)
J = np.sum(squared_error) / (2 * m)
print(J)
Data reference link: searchcode.com/codesearch/view/5404318
repeat the following steps and let me know
load_data = pd.read_csv('data.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
#print(m)
#plt.scatter(load_data[0],load_data[1])
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
print(theta.T)
prediction = np.matmul(X,theta.T)
error = (prediction-y)
error_df = pd.DataFrame(error)
squared_error = np.square(error_df)
print(squared_error)

Categories