How to make a progress bar/meter in web2py? - python

I made a progress meter in web2py, but it only shows up in the terminal window. How can I make the progress bar/meter to work in the web2py's HTML page?
Here's a part of the code:
k = 1 # This is the loop variable for subplots.
for counter in nus:
fig = plt.figure()
D = E*(h**3)/(12*(1-counter**2)) # Cylindrical rigidity.
T0 = (L**2)/(D*np.pi**2)*T0_orig # Nondimensional tension.
amax = T0/kappa # Maximum allowed alpha (to keep tension nonnegative everywhere).
alphas = [0, (10**-6)*amax, (10**-4)*amax, (10**-2)*amax] # Nondimensional alphas to use for plot.
workdone = 0.0 # How much of the Figure has been calculated? 0.0 = none, 1.0 = Figure is ready to show.
workstep = 100.0/len(alphas) # How much work is done during one step in the loop? If there are 4 steps in the loop, then then step will be 100.0/4 = 25.0.
for alpha in alphas:
lambda_, xx, f = nonhomog_solver(kappa, alpha, nu, nx)
V0 = np.sqrt( T0_orig/m + np.pi**2 * D/(m*L**2)*lambda_ )
if (k == 1):
V0_ref = V0
# Figure 1
fig_a = fig.add_subplot(2,2,k)
fig.subplots_adjust(hspace=0.4)
if (k == 1):
fig_a.set_title(r'$\alpha / \alpha_{max} = %.2g, V_{0}^{ref} = %.6g$ m/s' % (alpha/amax, V0))
else:
fig_a.set_title(r'$\alpha / \alpha_{max} = %.2g, V_{0}/V_{0}^{ref} = %.6g$' % (alpha/amax, V0/V0_ref))
fig_a.plot(xx,f)
plt.xlim(-kappa,kappa)
plt.xlabel(r'$\eta$')
plt.ylim(-0.1,1.1)
if ((k == 1) or (k == 3)):
plt.ylabel(r'$f(\eta)$')
workdone = workdone + workstep
print "Figure 1:", workdone, "%/100.0% done."
# Let's get ready for the next subfigure.
k = k + 1

You might be better off asking the mailing list.
Is your code inside (or called by) a controller function? Note, print statements don't send any output to web pages (i.e., they don't affect the HTTP response) -- to do that, your controller needs to return a dict to a view (or return a string). For a progress bar, you may end up needing to use Ajax (also, see here).
This Client Tools module has a progress bar example (scroll to the "Even more examples" section). I haven't used it and am not sure it fits your use case, but it may give you some ideas.

Related

Is there a function to move the objs in blender in new position

i use a python script to sent hand landmark points (use opencv, mediapipe) in blender with a udp socket,after receiving the data another python scripts which runs in blender area and using the first one as module use the data to locate 21 sheres in the new position as the landmark points with the code
import bpy
import udpserver
# Update is called once per frame
def main():
data = udpserver.main()
data_str = str(data)
points = data_str.replace('[', '')
points = points.replace(']', '')
data_use = points.split(",")
print(f"incoming data: {data_use}")
# Select the cube objects in Blender
bpy.ops.object.select_all(action='DESELECT')
for i in range(0, 21):
bpy.data.objects['point.%03d' % i].select_set(True)
points_shere = bpy.context.selected_objects
for i in range(0, 21):
x = (float(data_use[i * 3])) / 100
y = (float(data_use[i * 3 + 1])) / 100
z = (float(data_use[i * 3 + 2])) / 100
points_shere[i].location = (x, y, z)
# Register the function to be called every frame
bpy.app.handlers.frame_change_post.append(main)
if __name__ == '__main__':
main()
finally, first it receives only some data no in continioysly way and secondly it removes the obj all together if anyone can help me with some advises or ideas i will be thankfull thanks
i try to receive a solution or ideas

Animated plot 'list' object has no attribute 'set_data', even though I'm following advice given in response to other similar questions?

Let me preface this by letting everyone know that I'm still somewhat new to programming, so I'm sure my code's probably fairly inefficient in some parts with some potentially cringeworthy lines. I apologize in advance.
Anyways, I'm trying to program a 2D physics simulator that simulates the interaction between two celestial bodies given a set of initial conditions, and then animates their trajectories. The problem is, when I run my code, I get the following error: AttributeError: 'list' object has no attribute 'set_data', specifically citing the line.set_data([],[]) command in init(). This error points at line 61, which I've marked below (I cut out some unnecessary comments & definitely messed up the line numbers for the code snippet you're seeing below). Here is my code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# ->> Initialize Figure <<-
fig = plt.figure() # creates figure window
ax = plt.axes(xlim=(x[0],x[-1]),ylim=(y[0],y[-1])) # creates axis object
plotColors = ("blue","red","green","black") # colors to use in plots (qty. must match or exceed numBodies)
line, = ax.plot([],[],lw=2) # creates blank line object
lines = [] # list that contains line objects for simulated bodies
numBodies = 2 # number of bodies to intitialize (not necessarily simulate)
numArgs = 2 # DO NOT CHANGE: number of bodies to simulate
xBody1,xBody2 = [],[] # tracks x-coordinates for both simulated bodies
yBody1,yBody2 = [],[] # tracks y-coordinates for both simulated bodies
print("-- One --")
# ->> Initialize list of line objects for all bodies <<-
for i in range(numArgs):
line_obj = ax.plot([],[],lw=2,color=plotColors[i])
lines.append(line_obj)
print("-- Two --")
# ->> Initialize Animation Frame Initialization Function <<-
def init():
for line in lines:
line.set_data([],[]) #............................................<<<<<<< LINE 61 <<<<<<<
return lines
print("-- Three --")
# ->> Initialize Animation Function (called sequentially) <<-
def animate(i):
xList = [xBody1,xBody2] # contains x-coordinate data for each body
yList = [yBody1,yBody2] # contains y-coordinate data for each body
for num,line in enumerate(lines): # for index in range(0,1):
line.set_data(xList[num],yList[num]) # set data for each line separately
plt.pause(0.1)
return lines
# ->> Initialize Numerical Calculation Sequence <<-
def calculate(lastP,lastV,lastA): # calculates each iteration of movements
x1 = lastP[0] + lastV[0]*dt + 0.5*lastA[0]*np.square(dt)
y1 = lastP[1] + lastV[1]*dt + 0.5*lastA[1]*np.square(dt)
x2 = lastP[2] + lastV[2]*dt + 0.5*lastA[2]*np.square(dt)
y2 = lastP[3] + lastV[3]*dt + 0.5*lastA[3]*np.square(dt)
vx1 = lastV[0] + lastA[0]*dt
vy1 = lastV[1] + lastA[1]*dt
vx2 = lastV[2] + lastA[2]*dt
vy2 = lastV[3] + lastA[3]*dt
fx1 = G*m1*m2/np.square(x2-x1)
fy1 = G*m1*m2/np.square(y2-y1)
fx2 = G*m1*m2/np.square(x1-x2)
fy2 = G*m1*m2/np.square(y1-y2)
ax1 = fx1/m1
ay1 = fy1/m1
ax2 = fx2/m2
ay2 = fy2/m2
pos = [x1,y1,x2,y2]
vel = [vx1,vy1,vx2,vy2]
force = [fx1,fy1,fx2,fy2]
acc = [ax1,ay1,ax2,ay2]
return pos,vel,force,acc
# ->> Initialize Simulation Function
def simulate(sPos,sVel,sAcc): # handles calculations & data management for animation
xx1,xx2 = [],[]
yy1,yy2 = [],[]
xx1.append(sPos[0])
yy1.append(sPos[1])
xx2.append(sPos[2])
yy2.append(sPos[3])
Pos,Vel,Force,Acc = calculate(sPos,sVel,sAcc)
for t in range(N):
lastPos = Pos
lastVel = Vel
lastAcc = Acc
Pos,Vel,Force,Acc = calculate(lastPos,lastVel,lastAcc)
xx1.append(Pos[0])
yy1.append(Pos[1])
xx2.append(Pos[2])
yy2.append(Pos[3])
return xx1,yy1,xx2,yy2
print("-- Four --")
# ->> Specify Simulation Quantities <<-
G = 1 # gravitational constant (actually equals 6.67430e-11)
tmin = 0
tmax = 10000
N = 20000
dt = (tmax-tmin)/N
# ->> Specify Initial Conditions <<-
m1 = 1000 # mass of body 1 (kg)
m2 = 1000 # mass of body 2 (kg)
x1s = 10 # starting x-coordinate of body 1
y1s = 90 # starting y-coordinate of body 1
x2s = 90 # starting x-coordinate of body 2
y2s = 10 # starting y-coordinate of body 2
fx1s = 0 # initial x-directed force on body 1 (N) at t=0-
fy1s = 0 # initial y-directed force on body 1 (N) at t=0-
fx2s = 0 # initial x-directed force on body 2 (N) at t=0-
fy2s = 0 # initial y-directed force on body 2 (N) at t=0-
ax1s = fx1s/m1 # initial x-acceleration of body 1 (m/s^2)
ay1s = fy1s/m1 # initial y-acceleration of body 1 (m/s^2)
ax2s = fx2s/m2 # initial x-acceleration of body 2 (m/s^2)
ay2s = fy2s/m2 # initial y-acceleration of body 2 (m/s^2)
vx1s = 0 # initial x-velocity of body 1 (m/s)
vy1s = 0 # initial y-velocity of body 1 (m/s)
vx2s = 0 # initial x-velocity of body 2 (m/s)
vy2s = 0 # initial y-velocity of body 2 (m/s)
# ->> Initialize Physics Vectors <<-
mass = [m1,m2]
Pos = [x1s,y1s,x2s,y2s]
xPos = [x1s,x2s]
yPos = [y1s,y2s]
Force = [fx1s,fy1s,fx2s,fy2s]
xForce = [fx1s,fx2s]
yForce = [fy1s,fy2s]
Acc = [ax1s,ay1s,ax2s,ay2s]
xAcc = [ax1s,ax2s]
yAcc = [ay1s,ay2s]
Vel = [vx1s,vy1s,vx2s,vy2s]
xVel = [vx1s,vx2s]
yVel = [vy1s,vy2s]
simulate(Pos,Vel,Acc)
print(type(line))
print("-- Five --")
# ->> ANIMATE SIMULATION <<-
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
Here's what's messing me up: I know this error is usually given when you "fail to unpack the list of Line2D object", as mentioned in the answer to this question. To solve this, you should include a comma next to the variable you're trying to "unpack". In this case, when I initialized line towards the top of my code snippet, I definitely included that comma. So I'm very confused as to why I'm getting this error message? For reference, I've been following this example for creating the animated plot, and I believe I've been consistent with their code for the most part.
Moreover, I created a few print() statements to help me see various stages of the code's execution. This is what the output looks like before the error message:
-- One --
-- Two --
-- Three --
-- Four --
<class 'matplotlib.lines.Line2D'>
-- Five --
As you can see, the line variable is of type lines.Line2D right before the simulation begins, which should be exactly what we want (right?). My suspicion is that there's something weird going on under the hood once simulation() is called, but I'm not competent enough to navigate this process.
Can anyone help me figure out what's going wrong in my code? Thanks.

Conway's Game of Life using Python matplotlib

I just started learning Python in a while, so we have to do this homework, which writes a program to run the Conway's Game of Life using matplotlib. My professor has done part of codes and we have to fill the code under the TODO comments. So I wrote it, and I didn't know why it didn't run the animation. What had I done wrong? Thanks so much guys !!! The comments in the program are pretty long since they are kind of instructions.
# life.py - Once complete, this program will play the game of
# life.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# The update function is needed for the animation
# to work properly. It has four parameters:
# frameNum - this is handled by the animation, don't change this.
# img - the plot that is passed and changed, don't change this.
# world - the two-D array that represents the world for the
# game of life. This will be updated to the next gen.
# N - the size of the world (which is square).
def update( frameNum, img, world, N ) :
newWorld = world.copy( )
## TODO - Write code here to update the cells in newWorld
## for the next generation of life. Remember to
## use the toroidal model. Rather than making
## special cases for row/column 0 and N-1, just
## use the % operator.
for i in range (N):
for j in range (N):
total= (world[(i-1)%N][(j-1)%N]+world[(i-1)%N][j]+world[(i-1)%N][(j+1)%N]+
world[i][(j-1)%N]+world[i][(j+1)%N]+ world[(i+1)%N][(j-1)%N]+
world[(i+1)%N][j]+ world[(i+1)%N][(j+1)%N])/255
if world[i][j]== 255:
if total>3 or total<2:
newWorld[i][j]== 0
elif total==3:
newWorld[i][j]== 255
img.set_data( newWorld )
world[:] = newWorld[:]
return img
N = 50
SPEED = 100
PROB_LIFE = 40
## TODO - Write code here to create the initial population
## of the world. I recommend creating an N x N array that
## is initially filled with random numbers from 0 to 99.
## Then use the PROB_LIFE to change the entries to be
## either alive (255) or dead (0).
world= np.random.choice([0,255], N*N, p=[1-((PROB_LIFE)/100),(PROB_LIFE)/100]).reshape(N,N)
fig, ax = plt.subplots( )
img = ax.imshow( world, interpolation='nearest' )
ani = animation.FuncAnimation( fig, update, fargs = ( img, world, N ),
frames = 10, interval = SPEED,
save_count = 50 )
plt.show( )
# This is the end of the program. You should not need
# anything after this point.
You have to use = instead of == to assign new values in
newWorld[i][j] = 0 # need `=` instead of `==
newWorld[i][j] = 255 # need `=` instead of `==
and now you will see animation.
But you have also mistake with elif - wrong indention - correctly
if world[i][j] == 255:
if total > 3 or total < 2:
newWorld[i][j] = 0
elif total == 3:
newWorld[i][j] = 255
or more readable
if world[i][j] == 255:
if total > 3 or total < 2:
newWorld[i][j] = 0
else:
if total == 3:
newWorld[i][j] = 255

Incorporating a function into an ODE integration

This question is probably very simple but for the life of me I can't figure it out. Basically, I have a neuron whose voltage I'm modeling, but I have it receiving input spikes from other neurons randomly. So a friend of mine helped to create a function that essentially has some excitatory neurons provide a random Poisson spike which increases the voltage randomly and some inhibitory neurons providing downward spikes lowering the voltage. I've included the code below. Basically the step I'm trying to figure out how to do is how to make the I_syn term in the iterative step work. I would normally think to just write I_syn[i-1], but that gives me an error:
'function' object has no attribute '__getitem__'.
So I'm sure this question is really simple, but it's a problem I don't know how to overcome. How do I get this program to iterate the I_syn term properly so I can do a basic iterative scheme of an ODE while including a function defined previously in the code? It's important because I'll likely have more complicated neuron equations in the near future, so it would be much better to write the functions beforehand and then call them into the iteration step as needed. Thank you!
from numpy import *
from pylab import *
## setup parameters and state variables
T = 50 # total time to simulate (msec)
dt = 0.125 # simulation time step (msec)
time = arange(0, T+dt, dt) # time array
t_rest = 0 # initial refractory time
## LIF properties
Vm = zeros(len(time)) # potential (V) trace over time
Rm = 1 # resistance (kOhm)
Cm = 10 # capacitance (uF)
tau_m = Rm*Cm # time constant (msec)
tau_ref = 4 # refractory period (msec)
Vth = 1 # spike threshold (V)
V_spike = 0.5 # spike delta (V)
## Stimulus
I = 1.5 # input current (A)
N = 1000
N_ex = 0.8*N #(0..79)
N_in = 0.2*N #(80..99)
G_ex = 0.1
K = 4
def I_syn(spks, t):
"""
Synaptic current
spks = [[synid, t],]
"""
if len(spks) == 0:
return 0
exspk = spks[spks[:,0]<N_ex] # Check for all excitatory spikes
delta_k = exspk[:,1] == t # Delta function
if np.any(delta_k) > 0:
h_k = np.random.rand(len(delta_k)) < 0.90 # probability of successful transmission
else:
h_k = 0
inspk = spks[spks[:,0] >= N_ex] #Check remaining neurons for inhibitory spikes
delta_m = inspk[:,1] == t #Delta function for inhibitory neurons
if np.any(delta_m) > 0:
h_m = np.random.rand(len(delta_m)) < 0.90
else:
h_m = 0
isyn = C_m*G_ex*(np.sum(h_k*delta_k) - K*np.sum(h_m*delta_m))
return isyn
## iterate over each time step
for i, t in enumerate(time):
if t > t_rest:
Vm[i] = Vm[i-1] + (-Vm[i-1] + I_syn*Rm) / tau_m * dt
if Vm[i] >= Vth:
Vm[i] += V_spike
t_rest = t + tau_ref
## plot membrane potential trace
plot(time, Vm)
title('Leaky Integrate-and-Fire Example')
ylabel('Membrane Potential (V)')
xlabel('Time (msec)')
ylim([0,2])
show()
I_syn is just a function so using I_syn[i-1] will throw this error:
'function' object has no attribute '__getitem__'
If what you are looking for is a return value from the function, then you should first call it and then access what you want.
# pass related arguments as well since the function expects it
I_syn(arg1, arg2)[i-1]

Alternative for r's Exponential smoothing state space model in python/scikit/numpy

In R we have one good forecasting model like:
ets(y, model="ZZZ", damped=NULL, alpha=NULL, beta=NULL, gamma=NULL,
phi=NULL, additive.only=FALSE, lambda=NULL,
lower=c(rep(0.0001,3), 0.8), upper=c(rep(0.9999,3),0.98),
opt.crit=c("lik","amse","mse","sigma","mae"), nmse=3,
bounds=c("both","usual","admissible"), ic=c("aicc","aic","bic"),
restrict=TRUE, allow.multiplicative.trend=FALSE, use.initial.values=FALSE, ...)
In this method if we assign any variable, it automatically gets season type,trend & error type like model="ZZZ"/"AMA"/"MMZ" and some of the factors are auto adjusted to get accurate results.
In python do we have anything similar to ets in either
pandas/numpy/scipy/scikit?
By my research:
Ewma in pandas is similar, but we need to hardcode all the parameters to fixed ones.
In Holtwinter we need to write detailed methods for all the trend and season types.
So instead of that do we have any ready-made functions which takes
dataframes as input and provides forecasting values, without writing
any inner functions for parameters ourselves?
Any Fine tuned regression models scikit/statsmodels?
After searching around a bit, I haven't found anything that seems really promising as an ets alternative for python. There are some tries though: StatsModels and pycast's Forecasting methods, which you can check if they suit your needs.
One option you can use to workaround the missing implementation is to run an R script from python using the subprocess module. There is a very good article on how to do this here.
In order to do the later:
You need to create an R script (ex. my_forecast.R), which will
calculate (using ets) and print the forecasts on a file, or on stdout (with the cat() command), in order to use them after the script
runs.
You can run the R script from a python script as follows:
import subprocess
# You need to define the command that will run the Rscript from the subprocess
command = 'Rscript'
path2script = 'path/to/my_forecast.R'
cmd = [command, path2script]
# Option 1: If your script prints to a file
subprocess.run(cmd)
f = open('path/to/created/file', 'r')
(...Do stuff from here...)
# Option 2: If your script prints to stdout
forecasts = subprocess.check_output(cmd, universal_newlines=True)
(...Do stuff from here...)
You can also add arguments to your cmd, which will be utilized by your Rscript as command line arguments, as follows:
args = [arg0, arg1, ...]
cmd = [command, path2script] + args
Then pass cmd to the subprocess
EDIT:
I found an exemplary series of articles on the Holt-Winters Forecasting: part1, part2 and part3. Besides the easy to comprehend analysis in those articles, Gregory Trubetskoy (the author) has provided the code he developed:
Initial trend:
def initial_trend(series, slen):
sum = 0.0
for i in range(slen):
sum += float(series[i+slen] - series[i]) / slen
return sum / slen
# >>> initial_trend(series, 12)
# -0.7847222222222222
Initial Seasonal Components:
def initial_seasonal_components(series, slen):
seasonals = {}
season_averages = []
n_seasons = int(len(series)/slen)
# compute season averages
for j in range(n_seasons):
season_averages.append(sum(series[slen*j:slen*j+slen])/float(slen))
# compute initial values
for i in range(slen):
sum_of_vals_over_avg = 0.0
for j in range(n_seasons):
sum_of_vals_over_avg += series[slen*j+i]-season_averages[j]
seasonals[i] = sum_of_vals_over_avg/n_seasons
return seasonals
# >>> initial_seasonal_components(series, 12)
# {0: -7.4305555555555545, 1: -15.097222222222221, 2: -7.263888888888888,
# 3: -5.097222222222222, 4: 3.402777777777778, 5: 8.069444444444445,
# 6: 16.569444444444446, 7: 9.736111111111112, 8: -0.7638888888888887,
# 9: 1.902777777777778, 10: -3.263888888888889, 11: -0.7638888888888887}
Finally the algorithm:
def triple_exponential_smoothing(series, slen, alpha, beta, gamma, n_preds):
result = []
seasonals = initial_seasonal_components(series, slen)
for i in range(len(series)+n_preds):
if i == 0: # initial values
smooth = series[0]
trend = initial_trend(series, slen)
result.append(series[0])
continue
if i >= len(series): # we are forecasting
m = i - len(series) + 1
result.append((smooth + m*trend) + seasonals[i%slen])
else:
val = series[i]
last_smooth, smooth = smooth, alpha*(val-seasonals[i%slen]) + (1-alpha)*(smooth+trend)
trend = beta * (smooth-last_smooth) + (1-beta)*trend
seasonals[i%slen] = gamma*(val-smooth) + (1-gamma)*seasonals[i%slen]
result.append(smooth+trend+seasonals[i%slen])
return result
# # forecast 24 points (i.e. two seasons)
# >>> triple_exponential_smoothing(series, 12, 0.716, 0.029, 0.993, 24)
# [30, 20.34449316666667, 28.410051892109554, 30.438122252647577, 39.466817731253066, ...
You can place those in a file, ex: holtwinters.py inside a folder with the following structure:
forecast_folder
|
└── __init__.py
|
└── holtwinters.py
From here on, this is a python module which you can place inside every project structure you want and use it anywhere inside that project, simply by importing it.
ETS is now available in python as part of the Statsmodels' most recent release. Here is a simple example of its use:
from statsmodels.tsa.api import ExponentialSmoothing
# make our own periodic data
# 3 weeks of hourly data
m = 24
days = 21
x = np.array(range(days * m)) / (m / 2 / np.pi)
st = 4 * np.sin(x)
lt = np.linspace(0, 15, days * m)
bt = 100
e = np.random.normal(scale=0.5, size=x.shape)
# make the ts we wish to forecast
y = lt + st + bt + e
# our guessed parameters
alpha = 0.4
beta = 0.2
gamma = 0.01
# initialise model
ets_model = ExponentialSmoothing(y, trend='add', seasonal='add',
seasonal_periods=24)
ets_fit = ets_model.fit(smoothing_level=alpha, smoothing_slope=beta,
smoothing_seasonal=gamma)
# forecast p hours ahead
p_ahead = 48
yh = ets_fit.forecast(p_ahead)
# plot the y, y_smoothed and y_hat ts'
plt.plot(y, label='y')
plt.plot(ets_fit.fittedvalues, label='y_smooth')
plt.plot(range(days * m, days * m + p_ahead),yh, label='y_hat')
plt.legend()
plt.show()
Here are more examples in notebook form.
Finally, here is the source code, should you wish to take a look over it.

Categories

Resources