SyntaxError: invalid syntax
I have a syntax error, but i could not solve it, need help
error: for k, g in groupby(enumerate(ranges), lambda (i,x):i-x):
Also, 1 question if anyone is able to help me
i am using Ubuntu 18.04, i rosrun this file but got [rosrun] Couldn't find executable named sensor_data_listerner.py below /home/sk/catkin_ws/src/testbot_description
is it because of the ROS python version i am using that caused the error?
the following is the code:
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import sensor_msgs.msg
import random
import numpy as np
from geometry_msgs.msg import Twist
from itertools import *
from operator import itemgetter
LINX = 0.0 #Always forward linear velocity.
THRESHOLD = 1.5 #THRESHOLD value for laser scan.
PI = 3.14
Kp = 0.05
angz = 0
def LaserScanProcess(data):
range_angels = np.arange(len(data.ranges))
ranges = np.array(data.ranges)
range_mask = (ranges > THRESHOLD)
ranges = list(range_angels[range_mask])
max_gap = 40
# print(ranges)
gap_list = []
for k, g in groupby(enumerate(ranges), lambda (i,x):i-x):
gap_list.append(map(itemgetter(1), g))
gap_list.sort(key=len)
largest_gap = gap_list[-1]
min_angle, max_angle = largest_gap[0]*((data.angle_increment)*180/PI), largest_gap[-1]*((data.angle_increment)*180/PI)
average_gap = (max_angle - min_angle)/2
turn_angle = min_angle + average_gap
print(min_angle, max_angle)
print(max_gap,average_gap,turn_angle)
global LINX
global angz
if average_gap < max_gap:
angz = -0.5
else:
LINX = 0.5
angz = Kp*(-1)*(90 - turn_angle)
def main():
rospy.init_node('listener', anonymous=True)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
rospy.Subscriber("scan", sensor_msgs.msg.LaserScan , LaserScanProcess)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
command = Twist()
command.linear.x = LINX
command.angular.z = angz
pub.publish(command)
rate.sleep()
if __name__ == '__main__':
main()
You can't unpack a tuple in the argument list of a lambda expression (or of a def statement) in Python 3. (That's a change from Python 2, where your lambda expression would have been valid.)
You'll have to use
lambda t: t[0] - t[1]
instead.
Related
i am developing a program that can be used to move the turtlebot to specific location using neural network with lidar sensors.
in this program i have some problem, can move the turtlebot and avoid the obstacle, but they cannot go to specific location that i want.
i dont know where the problem is?
theres no problem when compile and run this program (if u talking about the software i used) iam sure that the problem is in my code
import rospy
import random
import numpy as np
import tensorflow as tf
from geometry_msgs.msg import Twist, Point
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import Path
from nav_msgs.msg import Odometry
from geometry_msgs.msg import PoseStamped
from math import atan2
from tf.transformations import euler_from_quaternion
x = 0.0
y = 0.0
theta = 0.0
laser_range = np.array([])
def newOdom(msg):
global x
global y
global theta
x = msg.pose.pose.position.x
y = msg.pose.pose.position.y
rot_q = msg.pose.pose.orientation
(roll,pitch,theta) = euler_from_quaternion ([rot_q.x,rot_q.y,rot_q.z,rot_q.w])
def scan_callback(msg):
global laser_range
laser_range = np.expand_dims(np.array(msg.ranges[:30] + msg.ranges[-30:]), axis = 0)
laser_range[laser_range == np.inf] = 3.5
if __name__ == "__main__":
scan_sub = rospy.Subscriber('scan', LaserScan, scan_callback)
move = rospy.Publisher('cmd_vel', Twist, queue_size = 1)
sub = rospy.Subscriber('/odom',Odometry, newOdom)
rospy.init_node('obstacle_avoidance_tf')
state_change_time = rospy.Time.now()
rate = rospy.Rate(10)
goal = Point()
goal.x = 1
goal.y = 1
model = tf.keras.models.load_model('catkin_ws/src/turtlebot3_neural_network/src/model.hdf5')
while not rospy.is_shutdown():
inc_x = goal.x - x
inc_y = goal.y - y
angle_to_goal = atan2(inc_y,inc_x)
predictions = model.predict(laser_range)
action = np.argmax(predictions)
twist = Twist()
if action == 0 and abs(angle_to_goal - theta) > 0.1:
twist.linear.x = 0.3
else:
twist.angular.z = 0.3
move.publish(twist)
print(x)
print(y)
rate.sleep()
I am having some problems with multi-process in Xlib.thread or ImageGrab.
When I put like 3 or more references to get (getPixel and locateOnScreen(pyautogui)) in multi threads, it works fast and without errors initially, but 2 or 3 hours later the commands are getting slow and an error appears in the cmd warning that "it can't happen!"
Here's an example of the code:
from PIL import ImageGrab, Image
from pymouse import PyMouse
from pykeyboard import PyKeyboard
import time
m = PyMouse()
k = PyKeyboard()
def start(self):
if self.hotkeyEscolhidaManaTraining != None:
self.isManaTrainingOn = True
if self.isManaTrainingOn:
self.timerstartManaTraining=Interval.set_interval(self.startManaTraining, 1)
def startManaTraining(self):
if self.runningTimerManaTraining == True:
self.timerstartManaTraining.cancel()
return
self.runningTimerManaTraining = True
ManaTrainingBox = pyautogui.locateOnScreen('Pics/heal/manaLow.png', 0.8, True)
startBoxLeft = ManaTrainingBox[0]+2
self.startBoxTopManaTraining = ManaTrainingBox[1]+5
pixeisTotais = 92
if self.isManaTrainingOn:
pixelManaTraining = (self.porcentagemEscolhidaManaTraining * pixeisTotais) / 100
self.endBoxLeftManaTraining = startBoxLeft + pixelManaTraining
self.timerManaTraining = Interval.set_interval(self.validateManaTraining, 0.5)
def validateManaTraining(self):
if self.isManaTrainingOn:
pixelRGB = ImageGrab.getPixel((self.endBoxLeftManaTraining, self.startBoxTopManaTraining))
if not self.validatePixelsMana(pixelRGB):
pyautogui.press(self.hotkeyEscolhidaManaTraining)
return
and others 10 code like this in multi-threads, have a way to get all pixels and PNGs in just one 'locateOnScreen' without saving the img?
I ran the below code using rosrun command as a node but not running in a circle anymore. But there's no error in this function.
How to solve this and ran in a circle and stop in initial position?
ROS : Melodic
Ubuntu 18.04
#!/usr/bin/env python
import rospy
import rospkg
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
#defining variables
x = 0
y = 0
theta = 0.0
#main function
def pose_callback(msg):
global x, y, psi
x = msg.x
y = msg.y
psi = msg.theta
print(msg.theta)
if __name__=="__main__":
rospy.init_node('node_turtle_revolve', anonymous = True)
r = rospy.Rate(10)
velocity_publisher = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
while not rospy.is_shutdown():
sub = rospy.Subscriber('/turtle1/pose', Pose, pose_callback)
vel_msg = Twist()
vel_msg.linear.x = 0.2
vel_msg.linear.x = 0.0
vel_msg.linear.x = 0.0
vel_msg.angular.x= 0.0
vel_msg.angular.y= 0.0
vel_msg.angular.z= 0.1
velocity_publisher.publish(vel_msg)
r.sleep
You should change msg as pose
def pose_callback(pose):
global x, y, psi
x = pose.x
y = pose.y
psi = msg.theta
print(msg.theta)
And you should write a if statement
I am trying to use aubio and python for a school project, here's the goal : detect when someone emit two sounds, each with a length of 2s, and with an interval between them of max 3s. The second one need to be higher than the first one. When these conditions are met, the program send a Wake-On-Lan package (not implemented in current code).
import alsaaudio
import numpy as np
import aubio
import time
import threading
class Audio_watcher:
# constants
samplerate = 44100
win_s = 2048
hop_s = win_s // 2
framesize = hop_s
nb_samples = 20
tone_duration = 2.0
per_sampling = tone_duration / nb_samples
tone_max_interval = 3.0
tone_diff_ratio = 2
def __init__(self):
self.last_frequencies = np.zeros(Audio_watcher.nb_samples)
self.last_energies = np.zeros(Audio_watcher.nb_samples)
self.detected_tone = 0
# set up audio input
recorder = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
recorder.setperiodsize(Audio_watcher.framesize)
recorder.setrate(Audio_watcher.samplerate)
recorder.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE)
recorder.setchannels(1)
self.recorder = recorder
pitcher = aubio.pitch("default", Audio_watcher.win_s, Audio_watcher.hop_s, Audio_watcher.samplerate)
pitcher.set_unit("Hz")
pitcher.set_silence(-40)
self.pitcher = pitcher
# A filter
f = aubio.digital_filter(7)
f.set_a_weighting(Audio_watcher.samplerate)
self.f = f
def get_audio(self):
# read and convert data from audio input
_, data = self.recorder.read()
samples = np.fromstring(data, dtype=aubio.float_type)
filtered_samples = self.f(samples)
print(filtered_samples)
# pitch and energy of current frame
freq = self.pitcher(filtered_samples)[0]
print(freq)
self.last_frequencies = np.roll(self.last_frequencies, 1)
self.last_frequencies[0] = freq
self.last_energies = np.roll(self.last_energies, 1)
self.last_energies[0] = np.sum(filtered_samples**2)/len(filtered_samples)
threading.Timer(Audio_watcher.per_sampling, self.get_audio).start()
def reset_detected_tone():
self.detected_tone = 0
def detect_tone(self):
std_last = np.std(self.last_frequencies)
if std_last <= 200 and std_last > 0:
mean_freq = np.mean(self.last_frequencies)
if self.detected_tone == 0:
self.detected_tone = mean_freq
threading.Timer(Audio_watcher.tone_max_interval, self.reset_detected_tone).start()
elif mean_freq > Audio_watcher.tone_diff_ratio * self.detected_tone:
print('wol')
threading.Timer(Audio_watcher.tone_duration, self.detect_tone).start()
aw = Audio_watcher()
aw.get_audio()
aw.detect_tone()
However with this code I get a great delay between the sounds and their detection, I think it has to do with the recorder being called only one time every 0.1s, but I can't find how to give correct parameters to aubio.
Does anyone knows how to configure the constants so it works ?
Thanks a lot !
Found out what was causing this error, I needed to put the code that sets up the audio input in the get_audio function so it renewed everytime
Hi I am working on a script that will solve and plot an ODE using the Runge Kutta method. I want to have the script use different functions so I can expand upon it later. If I write it with out the function definition it works fine, but with the def() it will not open a plot window or print the results. Than you!
from numpy import *
import matplotlib.pyplot as plt
#H=p^2/2-cosq
#p=dp=-dH/dq
#q=dq=dH/dp
t = 0
h = 0.5
pfa = [] #Create arrays that will hold pf,qf values
qfa = []
while t < 10:
q = 1*t
p = -sin(q*t)
p1 = p
q1 = q
p2 = p + h/2*q1
q2 = q + h/2*p1
p3 = p+ h/2*q2
q3 = q+ h/2*p2
p4 = p+ h/2*q3
q4 = q+ h/2*p4
pf = (p +(h/6.0)*(p1+2*p2+3*p3+p4))
qf = (q +(h/6.0)*(q1+2*q2+3*q3+q4))
pfa.append(pf) #append arrays
qfa.append(qf)
t += h #increase time step
print("test")
plt.plot(pfa,qfa)
print("test1")
plt.show()
print("tes2t")
If you have a function declared, you'll need to call it at some point, e.g.:
def rk(p,q,h):
pass # your code here
if __name__ == '__main__':
rk(1,2,1)
Putting the function call within the if __name__ == '__main__' block will ensure that the function is called only when you run the script directly, not when you import it from another script. ( More on that here in case you're interested: What does if __name__ == "__main__": do? )
And here's an even better option; to avoid hard-coding fn args (your real code should have some error-handling for unexpected command-line input):
def rk(p,q,h):
pass # your code here
if __name__ == '__main__':
import argparse
the_parser = argparse.ArgumentParser()
the_parser.add_argument('integers', type=int, nargs=3)
args = the_parser.parse_args()
p,q,h = args.integers
rk(p,q,h)