Python in Maya, syntax error for UV script - python

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()

Related

# Error: RuntimeError: file <maya console> line 54: Connection not made: 'LT_Arm_GeoShape.instObjGroups[0]' -> 'Arm_MATSG.dagSetMembers[-1]'

Here I am iterating over a ordered dictionary which consists of transform , their existing shader and expected shader ( which is the name basically i want the shaders to be of name as Hand_MAT for both Hand_Geo similarly for others ).
If the shader of that name already exists I am just assigning otherwise first I am creating the shader with suitable name then assigning it.
import maya.cmds as cmds
from collections import OrderedDict
res_dict = OrderedDict()
sel_meshes = ["LT_Hand_Geo", "RT_Hand_Geo", "LT_Arm_Geo", "RT_Arm_Geo", "LT_Leg_Geo", "RT_Leg_Geo"]
for mesh in sel_meshes:
#paired_mesh = mesh.replace("LT_","RT") if "LT_" in mesh else mesh.replace("RT_","LT")
if cmds.objExists(mesh):
cmds.select(mesh)
cmds.hyperShade(smn=1)
data = cmds.ls(sl=1)
existing_shader = data[0]
required_shader = mesh.split('_')[1]+'_MAT'
if cmds.objExists(required_shader):
if existing_shader == required_shader:
continue
else:
res_dict[mesh] = [existing_shader, required_shader]
else:
res_dict[mesh] = [existing_shader, required_shader]
cmds.select(clear=True)
for key,value in res_dict.items():
print(key,value)
#cmds.sets("LT_Hand_, e=True, forceElement="Hand_MAT")
map_dict = {}
for transform, shaders in res_dict.items():
existing_shader = shaders[0]
expected_shader = shaders[1]
if cmds.objExists(expected_shader):
shading_engine = cmds.listConnections(expected_shader, type="shadingEngine")[0]
map_dict[transform] = shading_engine
if transform.split('_')[1] == expected_shader.split('_')[0]:
cmds.select(transform, r=1)
print(cmds.ls(sl=1),expected_shading_engine)
cmds.sets(e=1, forceElement=shading_engine)
else:
expected_shading_engine = expected_shader + 'SG'
existing_shading_engine = cmds.listConnections(existing_shader, type="shadingEngine")[0]
new_shader = cmds.duplicate(existing_shader,name=expected_shader,upstreamNodes=1)
new_shading_engine = cmds.duplicate(existing_shading_engine,name=expected_shading_engine,upstreamNodes=1)
cmds.connectAttr("%s.outColor " % expected_shader, "%s.surfaceShader " % expected_shading_engine, f=1)
map_dict[transform] = expected_shading_engine
cmds.select(transform, r=1)
print("---------------------------------")
print(cmds.ls(sl=1),expected_shading_engine)
cmds.sets(e=1, forceElement=expected_shading_engine)
In most cases it's working just fine . But I am getting this error if same shader is assinged to whole body of the character:
# Error: RuntimeError: file <maya console> line 54: Connection not made: 'LT_Arm_GeoShape.instObjGroups[0]' -> 'Arm_MATSG.dagSetMembers[-1]'. Source node will not allow the connection.
Error while parsing arguments. #

Why it resulting a "list index out of range error" on this dijkstra algorithm

I tried to implement a dijkstra algorithm on my own graph but it doesn't run instead it says that "list index out of range"
here is the code that i tried
it works on a smaller graph like with 6 nodes but mine has 39 nodes and the maker of this code said that "At every iteration analyze the list and how the list is accessed using print()..it will help troubleshoot the error" what is that supposed to mean ?
so after a while i realized it resulting that because the algorithm reached a dead end like in node (A,B,C,AL) so when i tried to go from A to F
it reached a dead end on B, can i get a help how to fix this please ?
import sys
from heapq import heapify, heappush, heappop
def dijsktra(graph,src,dest):
inf = sys.maxsize
node_data = {'A':{'cost':inf,'pred':[]},
'B':{'cost':inf,'pred':[]},
'C':{'cost':inf,'pred':[]},
'D':{'cost':inf,'pred':[]},
'E':{'cost':inf,'pred':[]},
'F':{'cost':inf,'pred':[]},
'G':{'cost':inf,'pred':[]},
'H':{'cost':inf,'pred':[]},
'I':{'cost':inf,'pred':[]},
'J':{'cost':inf,'pred':[]},
'K':{'cost':inf,'pred':[]},
'L':{'cost':inf,'pred':[]},
'M':{'cost':inf,'pred':[]},
'N':{'cost':inf,'pred':[]},
'O':{'cost':inf,'pred':[]},
'P':{'cost':inf,'pred':[]},
'Q':{'cost':inf,'pred':[]},
'R':{'cost':inf,'pred':[]},
'S':{'cost':inf,'pred':[]},
'T':{'cost':inf,'pred':[]},
'U':{'cost':inf,'pred':[]},
'V':{'cost':inf,'pred':[]},
'W':{'cost':inf,'pred':[]},
'X':{'cost':inf,'pred':[]},
'Y':{'cost':inf,'pred':[]},
'Z':{'cost':inf,'pred':[]},
'AA':{'cost':inf,'pred':[]},
'AB':{'cost':inf,'pred':[]},
'AC':{'cost':inf,'pred':[]},
'AD':{'cost':inf,'pred':[]},
'AE':{'cost':inf,'pred':[]},
'AF':{'cost':inf,'pred':[]},
'AG':{'cost':inf,'pred':[]},
'AH':{'cost':inf,'pred':[]},
'AI':{'cost':inf,'pred':[]},
'AJ':{'cost':inf,'pred':[]},
'AK':{'cost':inf,'pred':[]},
'AL':{'cost':inf,'pred':[]},
'AM':{'cost':inf,'pred':[]},
}
node_data[src]['cost'] = 0
visited = []
temp = src
for i in range(38):
if temp not in visited: # TODO: Reassign source
visited.append(temp)
min_heap = []
for j in graph[temp]:
if j not in visited:
cost = node_data[temp]['cost'] + graph[temp][j]
if cost < node_data[j]['cost']:
node_data[j]['cost'] = cost
node_data[j]['pred'] = node_data[temp]['pred'] + [temp]
heappush(min_heap,(node_data[j]['cost'],j))
heapify(min_heap)
temp = min_heap[0][1]
print("Shortest Distance: " + str(node_data[dest]['cost']))
print("Shortest Path: " + str(node_data[dest]['pred'] + list(dest)))
if __name__ == "__main__":
graph = {
'A':{'D':105.3},
'B':{'E':65},
'C':{'AM':103.4},
'D':{'A':105.3,'E':132.8,'J':165.8},
'E':{'B':65,'D':132.8,'F':176.6,'H':78.3},
'F':{'E':176.6,'R':181.8,'AM':20.3},
'G':{'H':63,'K':57.2},
'H':{'E':78.3,'G':63,'I':65,'O':101.2},
'I':{'H':65,'P':104},
'J':{'D':165.8,'K':125.6,'L':25.9},
'K':{'G':57.2,'J':125.6,'N':37.5},
'L':{'J':25.9,'M':68,'Y':177.7},
'M':{'L':25.9,'N':56,'V':124},
'N':{'K':37.5,'M':56,'O':77.4},
'O':{'H':101.2,'N':77.4,'P':70.2,'W':128.6},
'P':{'I':104,'O':70.2,'Q':68},
'Q':{'P':68,'R':45,'T':102.9},
'R':{'F':181.8,'Q':45,'S':51},
'S':{'R':51,'U':104.3,'AM':193.3},
'T':{'Q':102.9,'U':84.35,'X':21.6},
'U':{'S':104.3,'A':84.35,'AF':160.7},
'V':{'M':124,'W':128,'Z':45},
'W':{'O':128.6,'V':128,'X':150.7,'AD':132.9},
'X':{'T':21.6,'W':150.7,'AE':166.8},
'Y':{'L':177.7,'Z':100.9,'AA':39.8},
'Z':{'V':45,'Y':100.9,'AB':34},
'AA':{'Y':39.8,'AB':100.3,'AH':258.5},
'AB':{'Z':34,'AA':100.3,'AC':47.8},
'AC':{'AB':47.8,'AD':126,'AH':60.37},
'AD':{'W':132.9,'AE':110.2,'AK':93.14,'AC':126},
'AE':{'X':166.8,'AI':82.2,'AD':110.2},
'AF':{'U':160.7,'AG':13.7,'AI':181.2},
'AG':{'AF':13.7},
'AH':{'AA':285.5,'AC':60.37,'AJ':33.8},
'AI':{'AE':82.2,'AF':181.2,'AK':110},
'AJ':{'AH':33.8,'AK':119.3,'AL':52},
'AK':{'AD':93.14,'AI':110,'AJ':119.3},
'AI':{'AJ':52},
'AM':{'C':103.4,'S':193.3,'F':20.3}
}
source = 'A'
destination = 'F'
dijsktra(graph,source,destination)
it said error instead on this line
temp = min_heap[0][1]

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.

osmnx road connecting two city aren't identified (missing node of border)

I have an Dijsktra Algorithm that I apply on a graph that I get from open street map. It works fine with a single graph.
But when I compose a graph of two neighboring city, the same algorithm doesn't find any way between the graphs .. I noticied that road connecting two city weren't identified by any osmid. :-/
Did I missed some thing ?
class Pathfinding(nx.MultiDiGraph):
def __init__(self, incomin_graphe_data = None, **attr):
nx.MultiDiGraph.__init__(self,incomin_graphe_data,**attr)
def dijsktra(self,depart,final):
inf = float("inf")
F ,ds, s= set(), None ,None
D = {i: inf for i in self.nodes}
D[ depart ] = 0
pred = {}
priority_queue = [(0 , depart)]
while s != final:
ds, s = heapq.heappop(priority_queue)
F.add(s)
for y in self.neighbors(s):
w = self[s][y][0]['lenght']
dy = ds + w
if y not in F :
if D[y] > dy :
D[y] = dy
heapq.heappush(priority_queue,(dy,y))
pred[y] = s
path = [s]
while s != depart:
s = pred[s]
path.append(s)
return path
There is the Dijkstra that I use and the following type graph are MultiDiGraph.
add_Aubervilliers = "Aubervilliers, France"
Graphe_Aubervilliers = ox.graph_from_place(add_Aubervilliers, network_type='drive')
add_Saint_denis = " Saint denis, France "
Graphe_Saint_denis = ox.graph_from_place(add_Saint_denis, network_type = "drive")
Graph_Paris_Auber = nx.compose_all([ Graphe_Saint_denis, Graphe_Aubervilliers ])
I also tryied with the following commande
add_Saint_denis = " Saint denis, France "
Graphe_Saint_denis = ox.graph_from_adress(add_Saint_denis, infrastructure='way['highway']')
But it give the same problem... Did I missed something ?
All you need is to set truncate_by_edge to True.

Can't give dict to function (AttributeError)

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()

Categories

Resources