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. #
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]
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.
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.
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()