I'm trying to install vpython with python3.5 on windows 10.
I used the following commands in the cmd:
pip install vpython
pip install update --ipython
If I then try to run some vpython code (copied from internet to simulate projectile motion):
from vpython import *
from math import sin, cos
initialHeight = 4.6
initialVelocity = 24
Angle = 65
#Set up the display window
scene1 = display(title = "Projectile Motion for the uninitiated",
x=0,y=0, width=800, height=600,
range=10, background=colour.white,
center = (10,initialHeight,0))
#Create objects
table = box(pos=(-1,initialHeight - 1,0), size=(5,1,4))
ball1 = sphere(pos=(0,initialHeight,0),radius=1,
color=color.green, make_trail = true)
ball2 = sphere(pos=(0,initialHeight,0),radius=1,
color=color.red, make_trail = true)
floor = box(pos=(0,0,0), size =(100,0.25,10))
t=0
dt=0.01
g=-32 #ft/s**2
Fgrav = vector(0,g*dt,0)
#velocity vector for ball1
ball1v = vector(initialVelocity*cos(Angle*pi/180),
initialVelocity*sin(Angle*pi/180),0)
#This loop puts it into motion
while True:
rate(30) #speeds it up
ball1v = ballv + Fgrav
ball1.pos += ball1.v*dt
ball2.pos = (initialVelocity*cos(Angle*pi/180)*t,
initialHeight + initialVelocity*t*sin(Angle*pi/180) - 16*t**2)
if ball1.y < 0: #when ball hits floor
print("ball1.pos = ", ball1.pos, "t = ", t)
print("ball2.pos = ", ball2.pos, "t = ", t)
break
When I run this I then get the following errors:
Traceback (most recent call last):
File "C:/Users/yours_truly/Google Drive/Python/projectile motion.py", line 1, in <module>
from vpython import *
File "C:\Users\yours_truly\AppData\Local\Programs\Python\Python35-32\lib\site-packages\vpython\__init__.py", line 10, in <module>
from .vpython import *
File "C:\Users\yours_truly\AppData\Local\Programs\Python\Python35-32\lib\site-packages\vpython\vpython.py", line 442, in <module>
get_ipython().kernel.comm_manager.register_target('glow', GlowWidget)
AttributeError: 'NoneType' object has no attribute 'kernel'
I cannot understand the problem here, nor can I make sense of the discussions of this that I have found online. Can anyone tell me what the score is here? Is vpython incompatible with python 3.5 (which I've read in some places) or is there a workaround (which I've also read in other places)?
Thank you.
I cannot remember when exactly support for Python 3.5 became available; it is certainly supported now. But the problem may have been associated with the fact that the program has a number of errors. Here is a version that works, including with Python 3.5 on Windows 10. The corrections were to change true -> True, bal
from vpython import *
from math import sin, cos
initialHeight = 4.6
initialVelocity = 24
Angle = 65
#Set up the display window
scene1 = display(title = "Projectile Motion for the uninitiated",
x=0,y=0, width=800, height=600,
range=10, background=color.white,
center = (10,initialHeight,0))
#Create objects
table = box(pos=vec(-1,initialHeight - 1,0), size=vec(5,1,4))
ball1 = sphere(pos=vec(0,initialHeight,0),radius=1,
color=color.green, make_trail = True)
ball2 = sphere(pos=vec(0,initialHeight,0),radius=1,
color=color.red, make_trail = True)
floor = box(pos=vec(0,0,0), size =vec(100,0.25,10))
t=0
dt=0.01
g=-32 #ft/s**2
Fgrav = vector(0,g*dt,0)
#velocity vector for ball1
ball1v = vector(initialVelocity*cos(Angle*pi/180),
initialVelocity*sin(Angle*pi/180),0)
#This loop puts it into motion
while True:
rate(30) #speeds it up
ball1v = ball1v + Fgrav
ball1.pos += ball1v*dt
ball2.pos = vec(initialVelocity*cos(Angle*pi/180)*t,
initialHeight + initialVelocity*t*sin(Angle*pi/180) - 16*t**2,0)
if ball1.pos.y < 0: #when ball hits floor
print("ball1.pos = ", ball1.pos, "t = ", t)
print("ball2.pos = ", ball2.pos, "t = ", t)
break
Related
I have the following code, which runs well under Visual Studio Code with python 3.9.10, opencv 4.5.5 and numpy 1.22.1.
I would like to migrate this code into the Spyder IDE (Version 5, another notebook), python 3.8, opencv 4.5.1 and numpy 1.22.2.
In spyder, I get the error message TypeError: only integer scalar arrays can be converted a scalar index in line: output_layers = [layer_names[i-1]...] (marked line down in the code section)
I have already checked other answers on this site such as
TypeError when indexing a list with a NumPy array: only integer scalar arrays can be converted to a scalar index
which suggests list comprehension, but in my understanding I am already implemented this.
What is the reason for running currectly in on environment but not in the other?
import cv2
import numpy as np
def get_output_layers(net):
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
return output_layers
def draw_prediction(img, class_id, confidence, x, y, x_plus_w, y_plus_h):
label = str(classes[class_id])
color = COLORS[class_id]
cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)
cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
image = cv2.imread('horses.jpg')
Width = image.shape[1]
Height = image.shape[0]
scale = 0.00392
classes = None
with open(r'yolov3.txt', 'r') as f:
classes = [line.strip() for line in f.readlines()]
COLORS = np.random.uniform(0, 255, size=(len(classes), 3))
net = cv2.dnn.readNet('yolov3.weights','yolov3.cfg')
blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)
net.setInput(blob)
outs = net.forward(get_output_layers(net))
class_ids = []
confidences = []
boxes = []
conf_threshold = 0.5
nms_threshold = 0.4
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0] * Width)
center_y = int(detection[1] * Height)
w = int(detection[2] * Width)
h = int(detection[3] * Height)
x = center_x - w / 2
y = center_y - h / 2
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)
for i in indices:
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
draw_prediction(image, class_ids[i], confidences[i], round(x), round(y),
round(x+w), round(y+h))
cv2.imshow("object detection", image)
cv2.waitKey()
cv2.imwrite("object-detection.jpg", image)
cv2.destroyAllWindows()
there were subtle, recent api changes wrt handling std::vector in python
(4.5.1 still expects a 2d array, but it's 1d in 4.5.5)
to avoid the whole trouble, please simply use:
output_layers = net.getUnconnectedOutLayersNames()
(like it is done in the sample)
I have a system of 18 linear (i'm assuming) PDEs. Howe ever they are very awkwardly shaped PDEs. Every time I try to use FiPy to solve the system of coupled PDEs I get an error. I have fixed most of them on my own but I can't seem to get past this one.
First you will need a list of equations that will be added later in the program:
import time
from fipy import Variable, FaceVariable, CellVariable, Grid1D, Grid2D, ExplicitDiffusionTerm, TransientTerm, DiffusionTerm, Viewer,PowerLawConvectionTerm, ImplicitSourceTerm
from fipy.tools import numerix
import math
import numpy as np
import sympy as sp
Temperature = 500.0 #Temperature in Celsius
Temp_K = Temperature + 273.15 #Temperature in Kelvin
Ea = [342,7,42,45,34] #Activation energy in order from the list excel/word file
#Frequency factor ko (Initial k)
k_0 =[5.9 * (10**15), 1.3 * (10**13), 1.0 * (10**12), 5.0 * (10**11), 1.2 * (10**13)]
fk1 = [math.exp((-1.0 * x)/(R*Temp_K)) for x in Ea] #Determines k value at given temperature value (exp(-Ea/R*T))
final_k = [fk1*k_0 for fk1,k_0 in zip(fk1,k_0)] #Multiplys by the inital k value to determine the k value at the given temperature (ko * exp(-Ea/R*T))
final_kcm = [x for x in final_k]
def rhs(eq):
eq_list = [-1.0*final_kcm[0]*EDC - final_kcm[1]*EDC*R1 - final_kcm[2]*EDC*R2 - final_kcm[3]*EDC*R4 - final_kcm[4]*EDC*R5 - final_kcm[5]*EDC*R6,
final_kcm[2]*EDC*R2 - final_kcm[8]*EC*R1 + final_kcm[13]*VCM*R2,
final_kcm[1]*EDC*R1 + final_kcm[6]*R2*R1 + final_kcm[7]*R1*R3 + final_kcm[8]*R1*EC + final_kcm[9]*R1*C11 + final_kcm[10]*R1*C112 + final_kcm[12]*R1*VCM + 2.0*final_kcm[20]*R1*C2H2,
2.0*final_kcm[20]*R2*C2H2,
final_kcm[15]*R5*VCM,
return eq_list[eq]
Here is the rest of the program I use to generate the system of PDEs.
EDC = CellVariable(mesh=mesh, hasOld=True, value=10)
EC = CellVariable(mesh=mesh, hasOld=True, value=0)
HCl = CellVariable(mesh=mesh, hasOld=True, value=0)
Coke = CellVariable(mesh=mesh, hasOld=True, value=0)
CP = CellVariable(mesh=mesh, hasOld=True, value=0)
EDC.constrain(10, mesh.facesLeft)
EC.constrain(0., mesh.facesLeft)
HCl.constrain(0., mesh.facesLeft)
Coke.constrain(0., mesh.facesLeft)
CP.constrain(0., mesh.facesLeft)
nsp =18
u_x = [[ [0,]*nsp for n in range(nsp) ]]
for z in range(nsp):
u_x[0][z][z] = 1.0
eq0 = TransientTerm(var = EDC) == PowerLawConvectionTerm(coeff = u_x, var = EDC) + ImplicitSourceTerm(rhs(0),var = EDC)
eq1 = TransientTerm(var = EC) == PowerLawConvectionTerm(coeff = u_x, var = EC) + ImplicitSourceTerm(rhs(1),var = (EC))
eq2 = TransientTerm(var = HCl) == PowerLawConvectionTerm(coeff = u_x, var = HCl) + ImplicitSourceTerm(rhs(2),var = (HCl))
eq3 = TransientTerm(var = Coke) == PowerLawConvectionTerm(coeff = u_x, var = Coke) + ImplicitSourceTerm(rhs(3),var = (Coke))
eq4 = TransientTerm(var = CP) == PowerLawConvectionTerm(coeff = u_x, var = CP) + ImplicitSourceTerm(rhs(4),var = (CP))
eqn = eq0 & eq1 & eq2 & eq3 & eq4
if __name__ == '__main__':
viewer = Viewer(vars = (EDC,EC,HCl,Coke,CP))
viewer.plot()
for t in range(1):
EDC.updateOld()
EC.updateOld()
HCl.updateOld()
Coke.updateOld()
CP.updateOld()
eqn.solve(dt=1.e-3)
Sorry for the long code but I can't really show it any other way. Anyway this is the error it returns :
File
"C:\Users\tjcze\Anaconda3\lib\site-packages\fipy\matrices\scipyMatrix.py",
line 218, in addAt
assert(len(id1) == len(id2) == len(vector))
AssertionError
What should I do to get this system to work correctly?
The error is because of whatever you're trying to do with u_x. u_x should be a rank-1 FaceVariable.
Its shape should be #dims x #faces (or #dims x 1); it should not be (#eqns x #eqns).
Setting u_x = [1.] gets rid of the AssertionError.
You will then get a series of warnings:
UserWarning: sweep() or solve() are likely to produce erroneous results when `var` does not contain floats.
Fix this by initializing all of your CellVariables with floats, e.g.,
EDC = CellVariable(mesh=mesh, hasOld=True, value=10.)
instead of
EDC = CellVariable(mesh=mesh, hasOld=True, value=10)
With those changes, the code runs. It doesn't do anything interesting, but that's hardly surprising, as it's way too complicated at this stage. 18 equations only obfuscates things. I strongly recommend you troubleshoot this problem with <= 2 equations.
At this point, your equations aren't coupled at all (eq0 only implicitly depends on EDC, eq1 only on EC, etc.). This isn't wrong, but not terribly useful. Certainly no point in the eq = eq0 & eq1 & ... syntax. EDC is the only variable with a chance of evolving, and it's constant, so it won't evolve, either.
In future, please provide examples that actually run (up to the point of the error, anyway).
I run domoticz on a PI3b with Raspbian, for better effiency the PI3b has now a 7" screen to show domotics behaviour + weather-station information + internet forecast...
To show all of this I've coded a C++/WXWidget app with graphics for temp/pressure...
Temp/pressures graphs are with Python3/matplotlib plotted, saved as 3 png files. The Python script read datas in files and plot/save the graphs.
It works good from terminal.... but no way to work with crontab, or with an "os.execute()" from events lua-scripts of domoticz...
I've pushed Up all permissions/access for scripts and png files (read/write)
One python script read data from bme280 sensor, crontab 2 minutes, no problem, it works from terminal, crontab, lua events...
Second script read datas, plot graphs and send http json command in order to update a device in domoticz. This works fine from terminal, but not from domoticz (lua os.execute()) or from crontab.
call in crontab:
sudo /usr/bin/python3 /home/pi/Desktop/graph.py
call from domoticz lua script:
os.execute('sudo /usr/bin/python3 /home/pi/Desktop/graph.py')
from terminal it works fine with python, /usr/bin/python, or /usr/bin/python3 (--> matplotlib)
python --version = 3.7.0
It looks like a problem beetween many python versions, the good one is not called from crontab and lua-scripts.... How to fix-it ?
default python version to 2.7.0, 3.0, 3.6, 3.7 tested to check problem with env/bin/path...
only problem found with urllib.urlopen changed with "urlopen from urllib.request"
#!/usr/bin/python3
import matplotlib.lines as lines
import matplotlib.pyplot as plt
#import urllib ---> urllib.urlopen() works with /usr/bin/python
from urllib.request import urlopen #---> to work with /usr/bin/python3
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(which='major', axis='x', color=(0.6, 0.6, 0.6), linewidth=1)
ax.patch.set_color('black')
fig.set_facecolor((0.0, 0.0, 0.0))
fig.set_size_inches(26.25, 7.42)
fig.patch.set_facecolor('black')
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
plt.ylim(0, 63)
plt.xlim(0, 210)
plt.style.use('dark_background')
list = []
d1 = 0
d2 = 0
d3 = 0
def readf( str ): #open/read file, fill the list
list[:] = []
with open(str) as infile: #parsing to float
numbers = infile.read()
numbers = numbers.replace(" ","").replace("\r","").replace("\n","")
for num in numbers.split(";"):
n = float(num)
list.append(n)
infile.close()
if str == "/home/pi/Dev/PI-Weather_Station/pressval.txt":
t = len(list) - 1
t1 = t - 6
t2 = t - 12
t3 = t - 24
d1 = list[t] - list[t1]
d2 = list[t] - list[t2]
d3 = list[t] - list[t3]
if d1 < 0 and d2 < 0:
httpresponse = urlopen("http://192.168.x.xxx:xxxx/json.htm?type=command¶m=updateuservariable&vname=tendance&vtype=2&vvalue=baisse")
elif d1 < 0 and d2 > 0:
httpresponse = urlopen("http://192.168.x.xxx:xxxx/json.htm?type=command¶m=updateuservariable&vname=tendance&vtype=2&vvalue=stable")
elif d1 > 0 and d2 > 0:
httpresponse = urlopen("http://192.168.x.xxx:xxxx/json.htm?type=command¶m=updateuservariable&vname=tendance&vtype=2&vvalue=hausse")
elif d1 > 0 and d2 < 0:
httpresponse = urlopen("http://192.168.x.xxx:xxxx/json.htm?type=command¶m=updateuservariable&vname=tendance&vtype=2&vvalue=stable")
return;
def chart( stg ): #plot/save the charts
o = len(list)
omin = 1400
omax = -50
i = 0
n = 0
line = lines.Line2D([i, i+1], [list[i], list[i+1]], lw=1, color='blue', axes=ax)
if o > 210:
i = o - 210
n = i
while i < o-1:
if stg == "/home/pi/Dev/PI-Weather_Station/tex.png":
line = lines.Line2D([i, i+1], [list[i], list[i+1]], lw=3, color=(0.0, 0.7, 1.0), axes=ax)
ax.add_line(line)
elif stg == "/home/pi/Dev/PI-Weather_Station/tin.png":
line = lines.Line2D([i, i+1], [list[i], list[i+1]], lw=3, color='yellow', axes=ax)
ax.add_line(line)
elif stg == "/home/pi/Dev/PI-Weather_Station/press.png":
line = lines.Line2D([i, i+1], [list[i], list[i+1]], lw=3, color='red', axes=ax)
ax.add_line(line)
if list[i] < omin:
omin = list[i]
if list[i] > omax:
omax = list[i]
i += 1
ax.axis([n, o, omin - 0.1, omax + 0.1])
ax.axhline((omax+omin)/2, 0, 1)
ax.axvline(n+30, 0, 1)
ax.axvline(n+60, 0, 1)
ax.axvline(n+90, 0, 1)
ax.axvline(n+120, 0, 1)
ax.axvline(n+150, 0, 1)
ax.axvline(n+180, 0, 1)
fig.savefig(stg, dpi = 10, bbox_inches = 'tight')
return;
readf("/home/pi/Dev/PI-Weather_Station/texval.txt")
chart("/home/pi/Dev/PI-Weather_Station/tex.png")
readf("/home/pi/Dev/PI-Weather_Station/tinval.txt")
chart("/home/pi/Dev/PI-Weather_Station/tin.png")
readf("/home/pi/Dev/PI-Weather_Station/pressval.txt")
chart("/home/pi/Dev/PI-Weather_Station/press.png")
plt.close()
Oky,
source: Generating a PNG with matplotlib when DISPLAY is undefined
that was a pb with matplotlib, the script runs fine in terminal but for others it needs more codes:
#!/usr/bin/python
import matplotlib
matplotlib.use('Agg')
I am trying to make a program which can help me on finding Area using Radius. but its output is very weird, take a look!
Pi = 3.1415929203539825
print('What is the Radius') #asking for Radius
R = input()
A = str(Pi) * int(R) * int(R)
print("The Area of this circle will be " + str(A) + "")
when R = 5, this is what it outputs:
3.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.14159292035398253.1415929203539825
You don't need to cast pi to a string. Doing so repeats the string
Try this instead
from math import pi
R = float(input("enter a radius: "))
A = pi * (R**2)
I have been learning python for physics,
im using VIDLE - Py 2.7,
I open a new file and without saving enter this code:
from visual import *
scene.width = 800
scene.height = 600
scene.autoscale = 0
scene.range = (100, 100, 100)
scene.center = (0, 40, 0)
#scene.fullscreen = 1
ball = sphere(pos=(0,103,1),radius = 2)
ground = box(pos=(0,-1,0),size=(100,2,100))
building = box(size = (6,100,6),pos=(0,50,0),color=color.blue)
gravity = 9.8 # m/s**2
velocityX = 7 #m/s
seconds = 0
dt = 0.05
finished = False
while not finished:
rate(100) # dont run through loop more than 100 times/sec
seconds += dt
#position equation; y(t) = y0 + v0*t + .5 * a * t**2
ballY = 100 - .5 * gravity * seconds**2
ballX = velocityX * seconds
ball.pos = vector(ballX, ballY, 0)
if ballY -2 <=0:
finished = True
print "seconds to drop: " + str(seconds)
this successfully runs the program, but when i save it as a .py and then try to run it again in the same way I get an error
Traceback (most recent call last):
File "/Users/bencallaghan/Desktop/psyre.py", line 1
from visual import *
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/VPython-6.05-py2.7-macosx-10.6-intel.egg/visual/init.py", line 34
from visual_common.create_display import *
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/VPython-6.05-py2.7-macosx-10.6-intel.egg/visual_common/create_display.py", line 10
import wx as _wx
File "/usr/local/lib/wxPython-2.9.4.0/lib/python2.7/site-packages/wx-2.9.4-osx_cocoa/wx/init.py", line 45
from wx._core import *
File "/usr/local/lib/wxPython-2.9.4.0/lib/python2.7/site-packages/wx-2.9.4-osx_cocoa/wx/_core.py", line 5
import new
File "/Users/bencallaghan/Desktop/new.py", line 8
from pylab import scatter,xlabel,ylabel,xlim,ylim,show
ImportError: No module named pylab
My guess is that its running in some type of shell within Vpython that has access to visual and pylab but when I save it then tries to access them from somewhere else and it can't.
But beyond that reasoning I have little idea where to go from there
any ideas?
For starters, you need to import pylab in the same way that you imported vpython at the first line.
from pylab import*
Also, it seems you will need to indent this way so that your position/velocity updates are contained within your while loop. Hope this helps
while not finished:
rate(100) # dont run through loop more than 100 times/sec
seconds += dt
#position equation; y(t) = y0 + v0*t + .5 * a * t**2
ballY = 100 - .5 * gravity * seconds**2
ballX = velocityX * seconds
ball.pos = vector(ballX, ballY, 0)
if ballY -2 <=0:
finished = True
print "seconds to drop: " + str(seconds)
PS Not sure if the space between "import" and "*" is causing problems on your first line as well, should be:
from visual import*
not:
from visual import *
but this may be ok