Can't give dict to function (AttributeError) - python

I am programming the robot Sawyer from rethinkrobotics and
I want to call the function set_joint_position() with the dictionary limb_joints, like this:
...
limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position))
#-print("Joints: " + str(tuple(resp.joints[0].position)))
#-rospy.loginfo("\nIK Joint Solution:\n%s", limb_joints)
else:
rospy.logerr("INVALID POSE - No Valid Joint Solution Found.")
rospy.logerr("Result Error %d", resp.result_type[0])
return False
while not rospy.is_shutdown():
print("Moving robot to joint solution...")
limb.set_joint_positions(limb_joints)
...
The error I get is: AttributeError: 'str' object has no attribute 'set_joint_positions'
What may be helpful:
function def
def set_joint_positions(self, positions):
"""
Commands the joints of this limb to the specified positions.
...
#type positions: dict({str:float})
#param positions: joint_name:angle command
...
and the output if I uncomment the rospy.loginfo and let the program run:
IK Joint Solution:
{'right_j6': 3.00655557165754, 'right_j5': 0.542373122535165, 'right_j4': 0.3206092859358142, 'right_j3': 2.1274699085764, 'right_j2': 0.33896690311766786, 'right_j1': -1.062786744876718, 'right_j0': 0.2720637178544216}
I am new to python and don't get why it isn't working.
In the tutorial on their website the function is called like I do it too.
full code
def __init__(self):
# Verify limb parameters
print("Validating limbs...")
rp = intera_interface.RobotParams()
valid_limbs = rp.get_limb_names()
if not valid_limbs:
rp.log_message(("Cannot detect any limb parameters on this robot. "
"Exiting."), "ERROR")
return
# Verify robot is enabled
print("Getting robot state... ")
rs = intera_interface.RobotEnable()
print("Enabling robot... ")
rs.enable()
print("Done.")
#Move in neutral position
print("Moving to neutral position... ")
limb = intera_interface.Limb('right')
#limb.move_to_neutral()
print("Done.")
def doit(self, limb = "right"):
# Initialising IK services
ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService"
iksvc = rospy.ServiceProxy(ns, SolvePositionIK)
ikreq = SolvePositionIKRequest()
hdr = Header(stamp=rospy.Time.now(), frame_id='base')
# Defining a new pose
poses = {
'right': PoseStamped(
header=hdr,
pose=Pose(
position=Point(
x=0.450628752997,
y=0.161615832271,
z=0.217447307078,
),
orientation=Quaternion(
x=0.704020578925,
y=0.710172716916,
z=0.00244101361829,
w=0.00194372088834,
),
),
),
}
# Add desired pose for inverse kinematics
ikreq.pose_stamp.append(poses[limb])
# Request inverse kinematics from base to "right_hand" link
ikreq.tip_names.append('right_hand')
try:
rospy.wait_for_service(ns, 5.0)
# resp enthaelt momentane joint positions
resp = iksvc(ikreq)
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
# Check if result valid, and type of seed ultimately used to get solution
if(resp.result_type[0] > 0):
# Seed is optional, default mode: each strategy will be used
seed_str = {
ikreq.SEED_USER: 'User Provided Seed',
ikreq.SEED_CURRENT: 'Current Joint Angles',
ikreq.SEED_NS_MAP: 'Nullspace Setpoints',
}.get(resp.result_type[0], 'None')
rospy.loginfo("SUCCESS\nValid Joint Solution Found from Seed Type:\n%s" %(seed_str,))
# Format solution into Limb API-compatible dictionary
limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position))
#-print("Joints: " + str(tuple(resp.joints[0].position)))
# Formatted print of joints (instead of rospy.loginfo())
#print("\nIK Joint Solution:")
#pp = pprint.PrettyPrinter(indent=4)
#pp.pprint(limb_joints)
rospy.loginfo("\nIK Joint Solution:\n%s", limb_joints)
rospy.loginfo("------------------")
else:
rospy.logerr("INVALID POSE - No Valid Joint Solution Found.")
rospy.logerr("Result Error %d", resp.result_type[0])
return False
while not rospy.is_shutdown():
print("Moving robot to joint solution...")
limb.set_joint_positions(limb_joints)
rospy.sleep(0.01)
return True
if __name__ == '__main__':
# Init Node for communication with Master
rospy.init_node("PickAndPlace", anonymous=True)
# Calling init
pickandplace = PickAndPlace()
print("--- Initialisation complete. ---")
print("Calling doit()...")
pickandplace.doit()

Related

Python in Maya, syntax error for UV script

I'm trying to assign root UVs to an alembic Maya XGen file, so that I can give the XGen fur the colours of the mesh underneath in Unreal Engine. I have a jaguar mesh with UVs assigned, and am trying to transfer them to the alembic groom. I'm using the Epic code, however I keep getting an "# Error: invalid syntax# " notification. I'm using Maya 2022. I'm not very experienced at all in programming, so I would hugely appreciate it if anyone is able to spot what is causing the code to crash. Thank you so much in advance!
Epic documentation: https://docs.unrealengine.com/4.27/en-US/WorkingWithContent/Hair/XgenGuidelines/
from maya import cmds
from maya import OpenMaya
import os
def create_root_uv_attribute(curves_group, mesh_node, uv_set='map1'):
'''
Create "groom_root_uv" attribute on group of curves.
'''
# check curves group
if not cmds.objExists(curves_group):
raise RuntimeError('Group not found: "{}"'.format(curves_group))
# get curves in group
curve_shapes = cmds.listRelatives(curves_group, shapes=True, noIntermediate=True)
curve_shapes = cmds.ls(curve_shapes, type='nurbsCurve')
if not curve_shapes:
raise RuntimeError('Invalid curves group. No nurbs-curves found in group.')
else:
print "found curves"
print curve_shapes
# get curve roots
points = list()
for curve_shape in curve_shapes:
point = cmds.pointPosition('{}.cv[0]'.format(curve_shape), world=True)
points.append(point)
# get uvs
values = list()
uvs = find_closest_uv_point(points, mesh_node, uv_set=uv_set)
for u, v in uvs:
values.append([u, v, 0])
#print (str(u) + " , " + str(v) )
# create attribute
name = 'groom_root_uv'
cmds.addAttr(curves_group, ln=name, dt='vectorArray')
cmds.addAttr(curves_group, ln='{}_AbcGeomScope'.format(name), dt='string')
cmds.addAttr(curves_group, ln='{}_AbcType'.format(name), dt='string')
cmds.setAttr('{}.{}'.format(curves_group, name), len(values), *values, type='vectorArray')
cmds.setAttr('{}.{}_AbcGeomScope'.format(curves_group, name), 'uni', type='string')
cmds.setAttr('{}.{}_AbcType'.format(curves_group, name), 'vector2', type='string')
return uvs
def find_closest_uv_point(points, mesh_node, uv_set='map1'):
'''
Find mesh UV-coordinates at given points.
'''
# check mesh
if not cmds.objExists(mesh_node):
raise RuntimeError('Node not found: "{}"'.format(mesh_node))
# check uv_set
uv_sets = cmds.polyUVSet(mesh_node, q=True, allUVSets=True)
if uv_set not in uv_sets:
raise RuntimeError('Invalid uv_set provided: "{}"'.format(uv_set))
# get mesh as dag-path
selection_list = OpenMaya.MSelectionList()
selection_list.add(mesh_node)
mesh_dagpath = OpenMaya.MDagPath()
selection_list.getDagPath(0, mesh_dagpath)
mesh_dagpath.extendToShape()
# get mesh function set
fn_mesh = OpenMaya.MFnMesh(mesh_dagpath)
uvs = list()
for i in range(len(points)):
script_util = OpenMaya.MScriptUtil()
script_util.createFromDouble(0.0, 0.0)
uv_point = script_util.asFloat2Ptr()
point = OpenMaya.MPoint(*points[i])
fn_mesh.getUVAtPoint(point, uv_point, OpenMaya.MSpace.kWorld, uv_set)
u = OpenMaya.MScriptUtil.getFloat2ArrayItem(uv_point, 0, 0)
v = OpenMaya.MScriptUtil.getFloat2ArrayItem(uv_point, 0, 1)
uvs.append((u, v))
return uvs
def abc_export(filepath, node=None, start_frame=1, end_frame=1, data_format='otawa', uv_write=True):
job_command = '-frameRange {} {} '.format(start_frame, end_frame)
job_command += '-dataFormat {} '.format(data_format)
job_command += '-attr groom_root_uv '
if uv_write:
job_command += '-uvWrite '
job_command += '-root {} '.format(node)
job_command += '-file {} '.format(filepath)
cmds.AbcExport(verbose=True, j=job_command)
def main():
export_directory = 'D:/Projects/Jaguar_Groom/Jag_Groom_copied_14_07/New/Maya_Xgen'
hair_file = os.path.join(export_directory, 'hair_export.abc')
curve_top_group= 'alembic_curves:jaguar_main_fur_splineDescription'
uv_mesh='retopo_furmesh'
create_root_uv_attribute( curve_top_group , uv_mesh)
abc_export(hair_file, curve_top_group)
main()
This runs fine for me with one modification. I updated both print statements in create_root_uv_attribute(...) to have braces ().
By default Maya 2022 uses Python 3 while this code seems to be written for Python 2 e.g. print 'Hello World' is valid in 2 but invalid in 3, print('Hello World') is expected.
You can launch Maya 2022 in Python 2 by following the instructions in the link below:
https://knowledge.autodesk.com/support/maya/learn-explore/caas/CloudHelp/cloudhelp/2022/ENU/Maya-Scripting/files/GUID-C0F27A50-3DD6-454C-A4D1-9E3C44B3C990-htm.html
I've included the updated code below.
from maya import cmds
from maya import OpenMaya
import os
def create_root_uv_attribute(curves_group, mesh_node, uv_set='map1'):
'''
Create "groom_root_uv" attribute on group of curves.
'''
# check curves group
if not cmds.objExists(curves_group):
raise RuntimeError('Group not found: "{}"'.format(curves_group))
# get curves in group
curve_shapes = cmds.listRelatives(curves_group, shapes=True, noIntermediate=True)
curve_shapes = cmds.ls(curve_shapes, type='nurbsCurve')
if not curve_shapes:
raise RuntimeError('Invalid curves group. No nurbs-curves found in group.')
else:
print("found curves")
print(curve_shapes)
# get curve roots
points = list()
for curve_shape in curve_shapes:
point = cmds.pointPosition('{}.cv[0]'.format(curve_shape), world=True)
points.append(point)
# get uvs
values = list()
uvs = find_closest_uv_point(points, mesh_node, uv_set=uv_set)
for u, v in uvs:
values.append([u, v, 0])
# create attribute
name = 'groom_root_uv'
cmds.addAttr(curves_group, ln=name, dt='vectorArray')
cmds.addAttr(curves_group, ln='{}_AbcGeomScope'.format(name), dt='string')
cmds.addAttr(curves_group, ln='{}_AbcType'.format(name), dt='string')
cmds.setAttr('{}.{}'.format(curves_group, name), len(values), *values, type='vectorArray')
cmds.setAttr('{}.{}_AbcGeomScope'.format(curves_group, name), 'uni', type='string')
cmds.setAttr('{}.{}_AbcType'.format(curves_group, name), 'vector2', type='string')
return uvs
def find_closest_uv_point(points, mesh_node, uv_set='map1'):
'''
Find mesh UV-coordinates at given points.
'''
# check mesh
if not cmds.objExists(mesh_node):
raise RuntimeError('Node not found: "{}"'.format(mesh_node))
# check uv_set
uv_sets = cmds.polyUVSet(mesh_node, q=True, allUVSets=True)
if uv_set not in uv_sets:
raise RuntimeError('Invalid uv_set provided: "{}"'.format(uv_set))
# get mesh as dag-path
selection_list = OpenMaya.MSelectionList()
selection_list.add(mesh_node)
mesh_dagpath = OpenMaya.MDagPath()
selection_list.getDagPath(0, mesh_dagpath)
mesh_dagpath.extendToShape()
# get mesh function set
fn_mesh = OpenMaya.MFnMesh(mesh_dagpath)
uvs = list()
for i in range(len(points)):
script_util = OpenMaya.MScriptUtil()
script_util.createFromDouble(0.0, 0.0)
uv_point = script_util.asFloat2Ptr()
point = OpenMaya.MPoint(*points[i])
fn_mesh.getUVAtPoint(point, uv_point, OpenMaya.MSpace.kWorld, uv_set)
u = OpenMaya.MScriptUtil.getFloat2ArrayItem(uv_point, 0, 0)
v = OpenMaya.MScriptUtil.getFloat2ArrayItem(uv_point, 0, 1)
uvs.append((u, v))
return uvs
def abc_export(filepath, node=None, start_frame=1, end_frame=1, data_format='otawa', uv_write=True):
job_command = '-frameRange {} {} '.format(start_frame, end_frame)
job_command += '-dataFormat {} '.format(data_format)
job_command += '-attr groom_root_uv '
if uv_write:
job_command += '-uvWrite '
job_command += '-root {} '.format(node)
job_command += '-file {} '.format(filepath)
cmds.AbcExport(verbose=True, j=job_command)
def main():
export_directory = 'D:/Projects/Jaguar_Groom/Jag_Groom_copied_14_07/New/Maya_Xgen'
hair_file = os.path.join(export_directory, 'hair_export.abc')
curve_top_group='alembic_curves:jaguar_main_fur_splineDescription'
uv_mesh='retopo_furmesh'
create_root_uv_attribute( curve_top_group , uv_mesh)
abc_export(hair_file, curve_top_group)
main()

Depth first search algorithm skipping spaces in maze?

After concluding the first lecture of Harvard's AI course on edX, I have decided to implement the concepts taught, first being the depth-first search algorithm.
The objective of this program is to input a maze in text file mazefile and find a path from S to G using the depth-first search algorithm.
The project currently consists of 4 files, (1) the code with the class methods to operate or use the (2) text file which contains the maze, another text file (3) that contains the result file (where the AI has explored) and the main python script (4). Here they are, feel free to copy and paste these into a folder and to see how they run.
processText.py (file 1)
#code to process the mazefile file.
class importMaze:
def __init__(self,maze):
self.fileLines = []
self.fileName = maze
self.switch = False
self.toBeReturned = []
def processThis(self):
f = open(self.fileName,"r")
for x in f:
self.fileLines.append(x[:-1])
f.close()
for i in self.fileLines:
if self.switch == True:
if str(i) == "END":
self.switch = False
else:
self.toBeReturned.append(i)
else:
if str(i) == "START":
self.switch = True
return self.toBeReturned
class mazePointer:
def __init__(self,mazearray):
self.Sample = mazearray
self.initialPosition = []
for y in range(0, len(self.Sample)):
for x in range(0,len(self.Sample[y])):
if str(self.Sample[y][x]) == "S":
self.initialPosition = [x,y]
self.currentPosition = self.initialPosition
def whatIs(self,xcoordinate,ycoordinate):
return (self.Sample[ycoordinate])[xcoordinate]
def nearbyFreeSpaces(self,search):
self.freeSpaces = []
if self.whatIs(self.currentPosition[0]-1,self.currentPosition[1]) == search:
self.freeSpaces.append([self.currentPosition[0]-1,self.currentPosition[1]])
if self.whatIs(self.currentPosition[0]+1,self.currentPosition[1]) == search:
self.freeSpaces.append([self.currentPosition[0]+1,self.currentPosition[1]])
if self.whatIs(self.currentPosition[0],self.currentPosition[1]-1) == search:
self.freeSpaces.append([self.currentPosition[0],self.currentPosition[1]-1])
if self.whatIs(self.currentPosition[1],self.currentPosition[1]+1) == search:
self.freeSpaces.append([self.currentPosition[1],self.currentPosition[1]+1])
return self.freeSpaces
def moveTo(self,position):
self.currentPosition = position
TestingTrack.py (the main file)
from processText import importMaze, mazePointer
testObject = importMaze("mazefile")
environment = testObject.processThis()
finger = mazePointer(environment)
frontier = []
explored = []
result = ""
def Search():
global result
if len(finger.nearbyFreeSpaces("G")) == 1: #If the goal is bordering this space
result = finger.nearbyFreeSpaces("G")[0]
explored.append(finger.currentPosition)
else:
newPlaces = finger.nearbyFreeSpaces("F") #finds the free spaces bordering
for i in newPlaces:
if i in explored: #Skips the ones already visited
pass
else:
frontier.append(i)
while result == "":
explored.append(finger.currentPosition)
Search()
finger.moveTo(frontier[-1])
frontier.pop(-1)
exploredArray = []
for y in range(len(environment)): #Recreates the maze, fills in 'E' in where the AI has visited.
holder = ""
for x in range(len(environment[y])):
if [x,y] in explored:
holder+= "E"
else:
holder+= str(environment[y][x])
exploredArray.append(holder)
def createResult(mazeList,title,append): #Creating the file
file = open("resultfile",append)
string = title + " \n F - Free \n O - Occupied \n S - Starting point \n G - Goal \n E - Explored/Visited \n (Abdulaziz Albastaki 2020) \n \n (top left coordinate - 0,0) \n "
for i in exploredArray:
string+= "\n" + str(i)
string+= "\n \n Original problem \n"
for i in environment:
string+= "\n" +str(i)
file.write(string)
file.close()
def tracingPath():
initialExplored = explored
proceed = True
newExplored = []
for i in explored:
finger.moveTo() #incomplete
print(explored)
createResult(exploredArray,"DEPTH FIRST SEARCH", "w")
mazefile (the program will read this file to get the maze)
F - Free
O - Occupied
S - Starting point
G - Goal
(Abdulaziz Albastaki 2020)
START
OOOOOOOOOOOOOOOO
OFFFFFFFFFFFFFGO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OSFFFFFFFFFFFFFO
OOOOOOOOOOOOOOOO
END
Made by Abdulaziz Albastaki in October 2020
You can change the maze and its size however it must
-Respect the key above
-Have ONE Starting point and goal
-The maze must be in between 'START' and 'END'
-The maze MUST be surrounded by occupied space
SAMPLE PROBLEMS:
OOOOOOOOOOOOOOOO
OFFFFFFFFFFFFFGO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OSFFFFFFFFFFFFFO
OOOOOOOOOOOOOOOO
OOOOOOOOOOOOOOOOO
OFOFFFFFOOOFFFOOO
OFFFOOOFOOFFOOOFO
OFOOOOOFOOFOOOOFO
OSFGFFFFFFFFFFFFO
OOOOOOOOOOOOOOOOO
There is also a resultfile, however if you would just create an empty textfile with that name (no extension), the program will fill it in with results.
The problem is with the resultfile, here it is:
DEPTH FIRST SEARCH
F - Free
O - Occupied
S - Starting point
G - Goal
E - Explored/Visited
(Abdulaziz Albastaki 2020)
(top left coordinate - 0,0)
OOOOOOOOOOOOOOOO
OFFFFFFFFFFFFFGO
OFOOOOOOOOOOOOEO
OFOOOOOOOOOOOOEO
OFOOOOOOOOOOOOEO
OEOOOOOOOOOOOOEO
OEFFFEEEEEEEEEEO
OOOOOOOOOOOOOOOO
Original problem
OOOOOOOOOOOOOOOO
OFFFFFFFFFFFFFGO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OFOOOOOOOOOOOOFO
OSFFFFFFFFFFFFFO
OOOOOOOOOOOOOOOO
The AI skipped a few spaces to get to the goal, why is it doing so?
Feel free to ask me for any clarifications.
There are the following issues:
the last if block in nearbyFreeSpaces uses a wrong index:
if self.whatIs(self.currentPosition[1],self.currentPosition[1]+1) == search:
self.freeSpaces.append([self.currentPosition[1],self.currentPosition[1]+1])
should be:
if self.whatIs(self.currentPosition[0],self.currentPosition[1]+1) == search:
self.freeSpaces.append([self.currentPosition[0],self.currentPosition[1]+1])
The final position is not correctly added to the path. The last line of this block:
if len(finger.nearbyFreeSpaces("G")) == 1: #If the goal is bordering this space
result = finger.nearbyFreeSpaces("G")[0]
explored.append(finger.currentPosition)
...should be:
explored.append(result)

How to prevents a AssertionError from stop Python code?

I want to do a system using a Autorules fuzzy controller where i create rules from process real data.
My problem is when i use the new data to simulate the fuzzy controller with the rules extracted of the older data, i get a error about the crisp output that cannot be calculated because do not exist rules enough, what is totally normal because my fuzzy system needs more rules and that's my point! I want to implement a new routine that analyses the crisp input/output and create new rules from this data, after that, i want to go back in my code and simulate again.
Is there a function that blocks the AssertionError from stop the code and redirect to another def or to a previously code line?
I tried to find some lib with a function that allows me to redirect the error steady to stop the code but no sucess. I think i will have to change the skfuzzy defuzz def code to allow to make it.
Thank you very much.
''' python
step = stp_ini
k = 0
delay = stp_ini
end = stp_fim - stp_ini
Tout_sim = pd.DataFrame(columns=['val'])
Vent_sim = pd.DataFrame(columns=['val'])
start = timeit.default_timer()
for step in range(end-k):
clear_output(wait=True)
simulation.input['PCA1'] = comp1n[step+delay]
simulation.input['PCA2'] = comp2n[step+delay]
simulation.input['PCA3'] = comp3n[step+delay]
simulation.input['PCA4'] = comp4n[step+delay]
simulation.input['Vent'] = dataoutf.NumVentOn[step+delay]
simulation.compute()
Tout_sim = Tout_sim.append({'val':simulation.output['Tout']},ignore_index=True)
stop = timeit.default_timer()
if ((step/(stp_fim-k-1))*100) < 5:
expected_time = "Calculating..."
else:
time_perc = timeit.default_timer()
expected_time = np.round( ( (time_perc-start)/(step/(end-k-1)) )/60,2)
'''
~\AppData\Local\Continuum\anaconda3\lib\site-packages\skfuzzy\control\controlsystem.py in defuzz(self)
587 self.var.defuzzify_method)
588 except AssertionError:
--> 589 raise ValueError("Crisp output cannot be calculated, likely "
590 "because the system is too sparse. Check to "
591 "make sure this set of input values will "
ValueError: Crisp output cannot be calculated, likely because the system is too sparse. Check to make sure this set of input values will activate at least one connected Term in each Antecedent via the current set of Rules.
edit:
I try to wrap the line code ValueError by try but the ValueError is activated yet
def defuzz(self):
"""Derive crisp value based on membership of adjective(s)."""
if not self.sim._array_inputs:
ups_universe, output_mf, cut_mfs = self.find_memberships()
if len(cut_mfs) == 0:
raise ValueError("No terms have memberships. Make sure you "
"have at least one rule connected to this "
"variable and have run the rules calculation.")
try:
return defuzz(ups_universe, output_mf,
self.var.defuzzify_method)
except AssertionError:
try:
new_c1 = []
new_c2 = []
new_c3 = []
new_c4 = []
new_vent = []
new_tout = []
newcondition1 = []
newcondition2 = []
newcondition3 = []
newcondition4 = []
newcondition5 = []
newcondition6 = []
#input
n = 0
for n in range(len(namespca)):
new_c1.append(fuzz.interp_membership(PCA1.universe, PCA1[namespcapd.name.loc[n]].mf, comp1n[step]))
new_c2.append(fuzz.interp_membership(PCA2.universe, PCA2[namespcapd.name.loc[n]].mf, comp2n[step]))
new_c3.append(fuzz.interp_membership(PCA3.universe, PCA3[namespcapd.name.loc[n]].mf, comp3n[step]))
new_c4.append(fuzz.interp_membership(PCA4.universe, PCA4[namespcapd.name.loc[n]].mf, comp4n[step]))
n = 0
for n in range(len(namesvent)):
new_vent.append(fuzz.interp_membership(Vent.universe, Vent[namesventpd.name.loc[n]].mf, dataoutf.NumVentOn[step]))
#output
n = 0
for n in range(len(namestemp)):
new_tout.append(fuzz.interp_membership(Tout.universe, Tout[namestemppd.name.loc[n]].mf, dataoutf.TsaidaHT[step]))
#new_c1 = np.transpose(new_c1)
new_c1_conv = pd.DataFrame(new_c1)
#new_c2 = np.transpose(new_c2)
new_c2_conv = pd.DataFrame(new_c2)
#new_c3 = np.transpose(new_c3)
new_c3_conv = pd.DataFrame(new_c3)
#new_c4 = np.transpose(new_c4)
new_c4_conv = pd.DataFrame(new_c4)
#new_vent = np.transpose(new_vent)
new_vent_conv = pd.DataFrame(new_vent)
#new_tout = np.transpose(new_tout)
new_tout_conv = pd.DataFrame(new_tout)
i=0
for i in range(pcamf):
newcondition1.append([new_c1_conv.idxmax(axis=0) == i])
newcondition2.append([new_c2_conv.idxmax(axis=0) == i])
newcondition3.append([new_c3_conv.idxmax(axis=0) == i])
newcondition4.append([new_c4_conv.idxmax(axis=0) == i])
i=0
for i in range(ventmf):
newcondition5.append([new_vent_conv.idxmax(axis=0) == i])
i=0
for i in range(tempmf):
newcondition6.append([new_tout_conv.idxmax(axis=0) == i])
choicelistpca = namespca
choicelistvent = namesvent
choicelisttout = namestemp
new_c1_rules = np.select(newcondition1, choicelistpca)
new_c2_rules = np.select(newcondition2, choicelistpca)
new_c3_rules = np.select(newcondition3, choicelistpca)
new_c4_rules = np.select(newcondition4, choicelistpca)
new_vent_rules = np.select(newcondition5, choicelistvent)
new_tout_rules = np.select(newcondition6, choicelisttout)
new_rules = np.vstack([new_c1_rules,new_c2_rules,new_c3_rules,new_c4_rules,new_vent_rules,new_tout_rules])
new_rules = new_rules.T
new_rulespd = pd.DataFrame(new_rules,columns=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'])
#Checar se a nova regra está dentro do conjunto de regras fuzzy atual
if pd.merge(new_rulespd,AutoRules, on=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'],how='inner').empty:
print('Nova regra não encontrada no conjunto atual de regras fuzzy!')
else:
pd.merge(new_rulespd,AutoRules, on=['PCA1','PCA2','PCA3','PCA4','Vent','Tout'],how='inner')
"""except AssertionError:
raise ValueError("Crisp output cannot be calculated, likely "
"because the system is too sparse. Check to "
"make sure this set of input values will "
"activate at least one connected Term in each "
"Antecedent via the current set of Rules.")"""
else:
# Calculate using array-aware version, one cut at a time.
output = np.zeros(self.sim._array_shape, dtype=np.float64)
it = np.nditer(output, ['multi_index'], [['writeonly', 'allocate']])
for out in it:
universe, mf = self.find_memberships_nd(it.multi_index)
out[...] = defuzz(universe, mf, self.var.defuzzify_method)
return output
Wrap the line of code that raises ValueError in a try. And decide what to do in its except ValueError: clause. Perhaps continue-ing on to the next iteration might be reasonable.

Stop Python script running on a nao robot touching his head

My problem is the following. I have a script in Python that is executed so that the robot does perform various actions without stopping until the execution stops, however for security reasons (in case the robot goes crazy and wants to kill us all) I need to add this instruction to stop it using the touch sensor of his head in case this is pressed.
I read a little about the ALTouch module with which the TouchChanged() module can be generated, but it acts on all the sensors (including movements) and not only with the touch sensor on the head.
Any ideas or related documentation will be welcomed.
Here´s some of my code:
class SoundProcessingModule(object):
def __init__( self, app):
ttsProxy.say("Touch my head at any moment to stop me")
super(SoundProcessingModule, self).__init__()
app.start()
session = app.session
self.audio_service = session.service("ALAudioDevice")
self.isProcessingDone = False
self.nbOfFramesToProcess = 100
self.framesCount=0
self.micFront = []
self.module_name = "SoundProcessingModule"
def startProcessing(self):
self.audio_service.setClientPreferences(self.module_name, 16000, 3, 0)
self.audio_service.subscribe(self.module_name)
while self.isProcessingDone == False:
time.sleep(1)
self.audio_service.unsubscribe(self.module_name)
def processRemote(self, nbOfChannels, nbOfSamplesByChannel, timeStamp, inputBuffer):
#ReadyToDance
postureProxy.goToPosture("StandInit", 0.5)
self.framesCount = self.framesCount + 1
if (self.framesCount <= self.nbOfFramesToProcess):
print(self.framesCount)
self.micFront=self.convertStr2SignedInt(inputBuffer)
rmsMicFront = self.calcRMSLevel(self.micFront)
print ("Nivel RMS del microfono frontal = " + str(rmsMicFront))
rmsArray.insert(self.framesCount-1,rmsMicFront)
#-40 y -30
if promedio >= -40 and promedio <= -30 :
#Some dance moves
#-29 y -20
elif promedio >= -29 and promedio <= -20:
#Some dance moves
#-19 y -11
elif promedio >= -19 and promedio <= -11:
#Some dance moves
else :
self.isProcessingDone=True
#Plot RMS signal
plt.plot(rmsArray)
plt.ylabel('RMS')
plt.xlabel('Frames')
plt.text(np.argmin(rmsArray), np.min(rmsArray) - 0.1, u'Mínimo', fontsize=10, horizontalalignment='center',
verticalalignment='center')
plt.text(np.argmax(rmsArray), np.max(rmsArray) + 0.1, u'Máximo', fontsize=10, horizontalalignment='center',
verticalalignment='center')
print("")
print ("El promedio total del sonido es: " + str(np.mean(rmsArray)))
print("El maximo total del sonido es: " + str(np.max(rmsArray)))
print("El minimo total del sonido es: " + str(np.min(rmsArray)))
plt.show()
postureProxy.goToPosture("Sit", 1.0)
def calcRMSLevel(self,data) :
rms = 20 * np.log10( np.sqrt( np.sum( np.power(data,2) / len(data) )))
return rms
def convertStr2SignedInt(self, data) :
signedData=[]
ind=0;
for i in range (0,len(data)/2) :
signedData.append(data[ind]+data[ind+1]*256)
ind=ind+2
for i in range (0,len(signedData)) :
if signedData[i]>=32768 :
signedData[i]=signedData[i]-65536
for i in range (0,len(signedData)) :
signedData[i]=signedData[i]/32768.0
return signedData
def StiffnessOn(proxy):
# We use the "Body" name to signify the collection of all joints
pNames = "Body"
pStiffnessLists = 1.0
pTimeLists = 1.0
proxy.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
#Es necesario estar al pendiente de la IP del robot para moficarla
parser.add_argument("--ip", type=str, default="nao.local",
help="Robot IP address. On robot or Local Naoqi: use '127.0.0.1'.")
parser.add_argument("--port", type=int, default=9559,
help="Naoqi port number")
args = parser.parse_args()
# Inicializamos proxys.
try:
proxy = ALProxy("ALMotion", "nao.local", 9559)
except Exception, e:
print "Could not create proxy to ALMotion"
print "Error was: ", e
try:
postureProxy = ALProxy("ALRobotPosture", "nao.local", 9559)
except Exception, e:
print "Could not create proxy to ALRobotPosture"
print "Error was: ", e
try:
ttsProxy = ALProxy("ALTextToSpeech" , "nao.local", 9559)
except Exception, e:
print "Could not create proxy to ALTextToSpeech"
print "Error was: ", e
try:
memory = ALProxy("ALMemory" , "nao.local", 9559)
except Exception, e:
print "Could not create proxy to ALMemory"
print "Error was: ", e
try:
connection_url = "tcp://" + args.ip + ":" + str(args.port)
app = qi.Application(["SoundProcessingModule", "--qi-url=" + connection_url])
except RuntimeError:
print ("Can't connect to Naoqi at ip \"" + args.ip + "\" on port " + str(args.port) +".\n"
"Please check your script arguments. Run with -h option for help.")
sys.exit(1)
MySoundProcessingModule = SoundProcessingModule(app)
app.session.registerService("SoundProcessingModule", MySoundProcessingModule)
MySoundProcessingModule.startProcessing()
The robot dances according to the RMS level captured from the front mic, but I need to stop it at anytime when the head sensor (or any sensor) is touched.
Instead of subscribing to TouchChanged, you can subscribe to the head only with the 3 events (for the 3 tactile buttons):
FrontTactilTouched
MiddleTactilTouched
RearTactilTouched
They will be raised with value 1 when touch starts, and 0 when touch ends. So you will want to filter and only stop your dance when value is 1.

AttributeError: 'bool' object has no attribute 'items'

I'm a beginner in python. I'm currently try to deal with use the IK to move the robot arm. When I try to run my program the arm was able to move to the my setted starting position but when it's going to next step it shows me this error:AttributeError: 'bool' object has no attribute 'items'
This is my program:
class Pick_Place (object):
#def __init__(self,limb,hover_distance = 0.15):
def __init__(self,limb):
self._limb = baxter_interface.Limb(limb)
self._gripper = baxter_interface.Gripper(limb)
self._gripper.calibrate(limb)
#self.gripper_open()
#self._verbose = verbose
ns = "ExternalTools/" + limb + "/PositionKinematicsNode/IKService"
self._iksvc = rospy.ServiceProxy(ns,SolvePositionIK)
rospy.wait_for_service(ns, 5.0)
def move_to_start (self,start_angles = None):
print ("moving.....")
if not start_angles:
print ("it is 0")
start_angles = dict(zip(self._joint_names, [0]*7))
self._guarded_move_to_joint_position(start_angles)
self.gripper_open()
rospy.sleep(1.0)
print ("moved!!!")
#########################IK_Server################################################
def ik_request (self,pose):
hdr = Header(stamp=rospy.Time.now(),frame_id='base')
ikreq = SolvePositionIKRequest()
ikreq.pose_stamp.append(PoseStamped(header=hdr, pose=pose))
try:
resp = self._iksvc (ikreq)
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
limb_joints = {}
limb_joints = dict(zip(resp.joints[0].name, resp.joints[0].position))
return limb_joints
###################################################################################
def _guarded_move_to_joint_position(self,joint_angles):
print ("joint position.....")
self._limb.move_to_joint_positions(joint_angles)
def gripper_open (self):
self._gripper.open()
rospy.sleep(1.0)
def gripper_close (self):
self._gripper.close()
rospy.sleep(1.0)
#################################Individual_Motion####################################
def _approach (self, pose):
print ("\nApproaching.....")
approach = copy.deepcopy(pose)
approach.position.z = approach.position.z #+ self._hover_distance
joint_angles = self.ik_request(approach)
self._guarded_move_to_joint_position(joint_angles)
print ("\nApproached.....")
def _retract (self):
print ("\nRetracting.....")
current_pose = self._limb.endpoint_pose()
ik_pose = Pose()
ik_pose.position.x = current_pose['position'].x
ik_pose.position.y = current_pose['position'].y
ik_pose.position.z = current_pose['position'].z #+ self._hover_distance
ik_pose.orientation.x = current_pose['orientation'].x
ik_pose.orientation.y = current_pose['orientation'].y
ik_pose.orientation.z = current_pose['orientation'].z
ik_pose.orientation.w = current_pose['orientation'].w
joint_angles = self.ik_request(ik_pose)
self._guarded_move_to_joint_position(joint_angles)
print ("\nRetracted......")
def _servo_to_pose (self, pose):
print ("\nPosing.....")
joint_angles = self.ik_request(pose)
self._guarded_move_to_joint_position(joint_angles)
print ("\nPosed.....")
##########################Motion_of_pick_and_place#####################################
def pick (self,pose):
print ("\nPicking_1.....")
# open the gripper
self.gripper_open()
# servo above pose
self._approach(pose)
# servo to pose
self._servo_to_pose(pose)
# close gripper
self.gripper_close()
# retract to clear object
self._retract()
print ("\nPicked")
def place (self,pose):
print ("\nPlacing_1.....")
# servo above pose
self._approach(pose)
# servo to pose
self._servo_to_pose(pose)
# open the gripper
self.gripper_open()
# retract to clear object
self._retract()
print ("\nPlaced")
###########################Main_Program############################################
def main():
print ("Initializing....")
rospy.init_node("ylj_ik_traTest")
print("Getting the robot state.....")
rs= baxter_interface.RobotEnable()
print ("Enabling....")
rs.enable()
limb = 'left'
#hover_distance = 0.15
starting_joint_angles = {'left_s0': -0.50,
'left_s1': -1.30,
'left_e0': -0.60,
'left_e1': 1.30,
'left_w0': 0.20,
'left_w1': 1.60,
'left_w2': -0.30}
#pnp = Pick_Place(limb,hover_distance)
pnp = Pick_Place(limb)
overhead_orientation = Quaternion(
x=-0.0249590815779,
y=0.999649402929,
z=0.00737916180073,
w=0.00486450832011)
ball_poses = list()
#1st ball point
ball_poses.append(Pose(
position = Point(x=0.7, y=0.15, z=-0.1),
orientation = overhead_orientation))
#2nd ball point
ball_poses.append(Pose(
position = Point(x=0.75, y=0.0, z=-0.1),
orientation = overhead_orientation))
pnp.move_to_start(starting_joint_angles)
idx = 0
while not rospy.is_shutdown():
print ("\nPicking.....")
pnp.pick(ball_poses[idx])
print ("\nPlacing.....")
idx = (idx+1) % len(ball_poses)#?????
pnp.place(ball_poses[idx])
return 0
if __name__ == '__main__':
sys.exit(main())
And this is the error shows me:
Initializing....
Getting the robot state.....
Enabling....
[INFO] [WallTime: 1466477391.621678] Robot Enabled
moving.....
joint position.....
moved!!!
Picking.....
Picking_1.....
Approaching.....
joint position.....
Traceback (most recent call last):
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 197, in <module>
sys.exit(main())
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 188, in main
pnp.pick(ball_poses[idx])
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 122, in pick
self._approach(pose)
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 88, in _approach
self._guarded_move_to_joint_position(joint_angles)
File "/home/baxter/ros_ws/src/baxter_examples/scripts/ylj_research/ylj_ik_traTest.py", line 72, in _guarded_move_to_joint_position
self._limb.move_to_joint_positions(joint_angles)
File "/home/baxter/ros_ws/src/baxter_interface/src/baxter_interface/limb.py", line 368, in move_to_joint_positions
diffs = [genf(j, a) for j, a in positions.items() if
AttributeError: 'bool' object has no attribute 'items'
Does anyone had met this kind of error before? Please help me, thank you.
The error tells you that booleans (either True or False) don't have an attribute "items".
When you call
self._limb.move_to_joint_positions(joint_angles) you are passing the argument "joint_angles" which becomes "positions" in the function
move_to_joint_positions().
Looking into the source code of the library you're using, it tells you what it wants positions to be:
#type positions: dict({str:float})
In short, it wants joint_angles to be a dictionary mapping strings to floats and you passed a boolean. Let's look into how you got joint_angles:
joint_angles = self.ik_request(ik_pose)
In the body of your method, you return False every time:
def ik_request (self,pose):
...
except (rospy.ServiceException, rospy.ROSException), e:
rospy.logerr("Service call failed: %s" % (e,))
return False
Returning a boolean is clearly not what you want to do, and it is the cause of this error.
You're trying to access the elements of a boolean value, which is not allowed. In your example, positions is a true/false value and not what you're expecting it to be. There's some section of the code where positions is being assigned to a boolean. You should walk through your code and look for any line that contains positions = something.

Categories

Resources