VIDLE - Py 2.7 after saving as .py, no longer runs - vpython

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

Related

Brickwall Frequency Splitter Python

Hey guys so I am trying to make a Brickwall Frequency Splitter in python 3.+, by this I mean that say I have an audio file, I want to split the audio file into 6 different bands, Sub, Lows, Low-Mids, Mids, High-Mids, Highs. However, I don't want to use a butter filter instead I want a filter that cuts any other frequencies below and above the desired range lets say I want from 200Hz to 400Hz I want a clean cut of them frequencies.
Thanks,
elliott
Currently my code looks like this I have a filter going on but it is like a sweep and doesn't really work for me:
import numpy as np
import sounddevice as sd
import os
import soundfile as sf
import matplotlib.pyplot as plt
sampling_rate = 44100
duration_in_seconds = 30
highpass = False
amplitude = 0.3
duration_in_samples = int(duration_in_seconds *
sampling_rate)
folder_number = 1
folder_number_str = str(folder_number)
folder_type = 'short/'
cut_type = '/30CUT/'
audio_file_dir = os.listdir('for_analysis/' + folder_type + folder_number_str + cut_type)[0]
audio_dir = 'for_analysis/' + folder_type + folder_number_str + cut_type
print(audio_dir)
print(audio_file_dir)
length = len(audio_dir)
file_format = audio_dir[length - 3:]
full_path = audio_dir + audio_file_dir
print(full_path)
data, fs = sf.read(full_path)
print(data.shape, fs)
plt.plot(data)
input_signal = data
cutoff_frequency = np.geomspace(50, 50, input_signal.shape[0])
allpass_output = np.zeros_like(input_signal)
dn_1 = 0
for n in range(input_signal.shape[0]):
break_frequency = cutoff_frequency[n]
tan = np.tan(np.pi * break_frequency / sampling_rate)
a1 = (tan - 1) / (tan + 1)
allpass_output[n] = a1 * input_signal[n] + dn_1
dn_1 = input_signal[n] - a1 * allpass_output[n]
if highpass:
allpass_output *= -1
filter_output = input_signal + allpass_output
filter_output *= 0.5
filter_output *= amplitude
sd.play(filter_output, sampling_rate)
sd.wait()
Unfortutantly, I have searched around the internet to be left with no result. If you have any documentation I could read to help me with this that would be great, or better any code you could show to aid.
Here is my desired result

If statement check mistake

I had a code with if statements and the code found the cosine value of the user-defined angle in radial. I typed the code to Taylor Series up to 12!. The code is;
import numpy as np
import matplotlib.pyplot as plt
import math
teta = np.arange(-8*np.pi, 8*np.pi+0.1,0.1)
P_ = [None]*len(teta)
ang_ = np.zeros(len(teta))
def func(teta):
for i in range(len(teta)):
if teta[i]<=0:
if abs(teta[i])%np.pi>=np.pi:
ang_[i] = (abs(teta[i])%(2*np.pi)-2*np.pi)*(-1)
else:
ang_[i] = (abs(teta[i])%(2*np.pi))*(-1)
else:
if teta[i]%2*np.pi >= np.pi:
ang_[i] = teta[i] % (2*np.pi) - 2*np.pi
else:
ang_[i] = teta[i] % (2*np.pi)
P_[i] = 1 - (1/2)*((ang_[i])**2) + (1/math.factorial(4))*((ang_[i])**4) - (1/math.factorial(6))*((ang_[i])**6) + (1/math.factorial(8))*((ang_[i])**8) - (1/math.factorial(10))*((ang_[i])**10) + (1/math.factorial(12))*((ang_[i])**12)
return P_
plt.plot(teta, func(teta), "b:+")
plt.plot(teta, np.cos(teta), "k--")
plt.grid()
plt.show
And the code cannot calculate when the teta angle is greater than 6 or -6. when I checked the code by debugging the step, that teta angle is -6.18319, jump over if statement
if abs(teta[i])%2*np.pi >= np.pi and teta[i]<-np.pi:
and jumps into
elif abs(teta[i])%np.pi >= 0 and teta[i]<0:
and code transverse the teta value to another angle array named ang_, and it determines by
ang_[i] = (abs(teta[i])%(2*np.pi))*(-1)
Thus the result of the function is over 2.
I will be glad if you would help me. Thanks a lot.
I found the mistake and the correct code is;
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 1 13:54:51 2022
#author: burak
"""
import numpy as np
import matplotlib.pyplot as plt
import math
user_degree = int(input('cosine value of angle in degree')) / 180 * np.pi
teta = np.arange(-user_degree, user_degree+0.1,0.1)
P_ = [None]*len(teta)
ang_ = np.zeros(len(teta))
def func(teta):
for i in range(len(teta)):
if teta[i]<=0:
teta = abs(teta)
if teta[i]%(2*np.pi) >= np.pi:
ang_[i] = (teta[i]%(2*np.pi)) - 2 * np.pi
else:
ang_[i] = (teta[i]%(2*np.pi))
else:
if teta[i]%(2*np.pi) >= np.pi:
ang_[i] = teta[i] % (2*np.pi) - 2 * np.pi
else:
ang_[i] = teta[i] % (2*np.pi)
P_[i] = 1 - (1/2)*((ang_[i])**2) + (1/math.factorial(4))*((ang_[i])**4) - (1/math.factorial(6))*((ang_[i])**6) + (1/math.factorial(8))*((ang_[i])**8) - (1/math.factorial(10))*((ang_[i])**10) + (1/math.factorial(12))*((ang_[i])**12)
return P_
plt.plot(teta, func(teta), "b:+")
plt.plot(teta, np.cos(teta), "k--")
plt.grid()
plt.show
The purpose of this code is to obtain correct cosine values of given angle. I asked the qs that the code cannot step to the correct if condition. for example when the angle is greater than np.pi the resul was above 1. I changed the code as when the angle is lesser than zero and greater than np.pi, code calculates absolute value of angle. Then the step moves to the correct condition. The next calculation is when the absolute value of teta greater then np.pi, the code substructs np.pi. At last the Taylor Series calculation matched with the np.cos() calculation.

How to print the progress of a task at somewhere fixed in python3.7

I'm trying to run a time time-consuming 'for' loop, and want to print the process in the fixed place of the console and refresh each loop
I try print function like this
for i in range(total):
...some code....
print('---%.2f---'%(float(i)/total), sep='')
It seems does't work
I use this answer to display progress bar:
The methods used:
def startProgress(title):
global progress_x
sys.stdout.write(title + ": [" + "-"*50 + "]" + chr(8)*51)
sys.stdout.flush()
progress_x = 0
def progress(x):
global progress_x
x = int(x * 50 // 100)
sys.stdout.write("#" * (x - progress_x))
sys.stdout.flush()
progress_x = x
def endProgress():
sys.stdout.write("#" * (50 - progress_x) + "]\n")
sys.stdout.flush()
An example of use:
import time
import sys
startProgress("Test")
for i in range(500):
progress(i * 100 / 500)
time.sleep(.1)
endProgress()
The progress will look like this with the # moving at the same time of the progress:

How to fix crontab issue or 'os.execute()' issue with python script?

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&param=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&param=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&param=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&param=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')

Installing and running vpython with Python 3.5 on Windows 10

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

Resources