Get name of attributes - python

I'd like to get the name of any attribute while iterating over it.
the ts3defines.py looks like this:
class VirtualServerProperties(object):
VIRTUALSERVER_UNIQUE_IDENTIFIER = 0
VIRTUALSERVER_NAME = 1
VIRTUALSERVER_WELCOMEMESSAGE = 2
VIRTUALSERVER_PLATFORM = 3
VIRTUALSERVER_VERSION = 4
VIRTUALSERVER_MAXCLIENTS = 5
VIRTUALSERVER_PASSWORD = 6
VIRTUALSERVER_CLIENTS_ONLINE = 7
VIRTUALSERVER_CHANNELS_ONLINE = 8
VIRTUALSERVER_CREATED = 9
VIRTUALSERVER_UPTIME = 10
VIRTUALSERVER_CODEC_ENCRYPTION_MODE = 11
VIRTUALSERVER_ENDMARKER = 12
the getItems(object) function looks like this:
def getItems(object):
return [getattr(object, a) for a in dir(object)
if not a.startswith('__') and not callable(getattr(object, a))]
the code in question looks like this:
for var in getItems(ts3defines.VirtualServerProperties):
(err, var) = ts3.getServerVariable(schid, var)
if err == ts3defines.ERROR_ok and var != "" and var != 0:
i.append('{0}: {1}'.format(var.__name__, var))
My question is about the var.__name__ shouldn't that return the string VIRTUALSERVER_BLA, etc?
Why does it cause?
11/25/2017 16:07:44 pyTSon.PluginHost.infoData Error Error calling infoData of python plugin Extended Info: Traceback (most recent call last):
File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\pluginhost.py", line 476, in infoData
data = p.infoData(schid, aid, atype)
File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\info\__init__.py", line 160, in infoData
return self.getServerInfo(schid)
File "C:/Users/blusc/AppData/Roaming/TS3Client/plugins/pyTSon/scripts\info\__init__.py", line 148, in getServerInfo
i.append('{0}: {1}'.format(var.__name__, var))
AttributeError: 'int' object has no attribute '__name__'

I don't understand why you're trying to access __name__. You already have the name within the getItems method; it's a. You should return that and use it in the loop.
def getItems(object):
return [(a, getattr(object, a)) for a in dir(object)
if not a.startswith('__') and not callable(getattr(object, a))]
...
for name, var in getItems(ts3defines.VirtualServerProperties):
(err, var) = ts3.getServerVariable(schid, var)
if err == ts3defines.ERROR_ok and var != "" and var != 0:
i.append('{0}: {1}'.format(name, var))

Related

Stuck on Python "KeyError: <exception str() failed>" in BFS code of a water jug scenario

Intended Function of code: Takes a user input for the volume of 3 jars(1-9) and output the volumes with one of the jars containing the target length. jars can be Emptied/Filled a jar, or poured from one jar to another until one is empty or full.
With the code I have, i'm stuck on a key exception error .
Target length is 4 for this case
Code:
`
class Graph:
class GraphNode:
def __init__(self, jar1 = 0, jar2 = 0, jar3 = 0, color = "white", pi = None):
self.jar1 = jar1
self.jar2 = jar2
self.jar3 = jar3
self.color = color
self.pi = pi
def __repr__(self):
return str(self)
def __init__(self, jl1 = 0, jl2 = 0, jl3 = 0, target = 0):
self.jl1 = jl1
self.jl2 = jl2
self.jl3 = jl3
self.target = target
self.V = {}
for x in range(jl1 + 1):
for y in range(jl2 + 1):
for z in range(jl3 + 1):
node = Graph.GraphNode(x, y, z, "white", None)
self.V[node] = None
def isFound(self, a: GraphNode) -> bool:
if self.target in [a.jar1, a.jar2, a.jar3]:
return True
return False
pass
def isAdjacent(self, a: GraphNode, b: GraphNode) -> bool:
if self.V[a]==b:
return True
return False
pass
def BFS(self) -> [] :
start = Graph.GraphNode(0, 0, 0, "white")
queue=[]
queue.append(start)
while len(queue)>0:
u=queue.pop(0)
for v in self.V:
if self.isAdjacent(u,v):
if v.color =="white":
v.color == "gray"
v.pi=u
if self.isFound(v):
output=[]
while v.pi is not None:
output.insert(0,v)
v=v.pi
return output
else:
queue.append(v)
u.color="black"
return []
#######################################################
j1 = input("Size of first jar: ")
j2 = input("Size of second jar: ")
j3 = input("Size of third jar: ")
t = input("Size of target: ")
jar1 = int(j1)
jar2 = int(j2)
jar3 = int(j3)
target = int(t)
graph1 = Graph(jar1, jar2, jar3, target)
output = graph1.BFS()
print(output)
`
**Error: **
line 37, in isAdjacent
if self.V[a]==b:
KeyError: <exception str() failed>
Strange but when I first ran this in the IPython interpreter I got a different exception:
... :35, in Graph.isAdjacent(self, a, b)
34 def isAdjacent(self, a: GraphNode, b: GraphNode) -> bool:
---> 35 if self.V[a]==b:
36 return True
37 return False
<class 'str'>: (<class 'RecursionError'>, RecursionError('maximum recursion depth exceeded while getting the str of an object'))
When I run it as a script or in the normal interpreter I do get the same one you had:
... line 35, in isAdjacent
if self.V[a]==b:
KeyError: <exception str() failed>
I'm not sure what this means so I ran the debugger and got this:
File "/Users/.../stackoverflow/bfs1.py", line 1, in <module>
class Graph:
File "/Users/.../stackoverflow/bfs1.py", line 47, in BFS
if self.isAdjacent(u,v):
File "/Users/.../stackoverflow/bfs1.py", line 35, in isAdjacent
if self.V[a]==b:
KeyError: <unprintable KeyError object>
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /Users/.../stackoverflow/bfs1.py(35)isAdjacent()
-> if self.V[a]==b:
(Pdb) type(a)
<class '__main__.Graph.GraphNode'>
(Pdb) str(a)
*** RecursionError: maximum recursion depth exceeded while calling a Python object
So it does seem like a maximum recursion error. (The error message you originally got is not very helpful). But the words <unprintable KeyError object> are a clue. It looks like it was not able to display the KeyError exception...
The culprit is this line in your class definition:
def __repr__(self):
return str(self)
What were you trying to do here?
The __repr__ function is called when the class is asked to produce a string representation of itself. But yours calls the string function on the instance of the class so it will call itself! So I think you actually generated a second exception while the debugger was trying to display the first!!!.
I replaced these lines with
def __repr__(self):
return f"GraphNode({self.jar1}, {self.jar2}, {self.jar3}, {self.color}, {self.pi})"
and I don't get the exception now:
Size of first jar: 1
Size of second jar: 3
Size of third jar: 6
Size of target: 4
Traceback (most recent call last):
File "/Users/.../stackoverflow/bfs1.py", line 77, in <module>
output = graph1.BFS()
File "/Users/.../stackoverflow/bfs1.py", line 45, in BFS
if self.isAdjacent(u,v):
File "/Users/.../stackoverflow/bfs1.py", line 33, in isAdjacent
if self.V[a]==b:
KeyError: GraphNode(0, 0, 0, white, None)
This exception is easier to interpret. Now it's over to you to figure out why this GraphNode was not found in the keys of self.V!

‘module’ object has no attribute ‘MStatus' in Maya python Api 2020

I am trying to build a command in python for Maya following a course on youtube and it's showing this error "# Error: RuntimeError: file line 2: AttributeError: file C:/Users/saeed/OneDrive/Documents/maya/2020/Plugins/vertexParticle.py line 23: 'module' object has no attribute 'MStatus' # "
I checked Maya API documents and we should have "MStatus" class but I have no idea why it's not accepted, I tried to use "MStatusCode" and it's showing same error.
from maya import OpenMaya
from maya import OpenMayaMPx
from maya import OpenMayaFX
import sys
commandName = "vertexParticle"
kHelpFlag = "-h"
kHelpLongFlag = "-help"
kSparseFlag = "-s"
kSparseLongFlag = "-sparse"
helpMessage = "This command will attach a particle for each vertex"
class pluginCommand(OpenMayaMPx.MPxCommand):
sparse = None
def __init__(self):
OpenMayaMPx.MPxCommand.__init__(self)
def argumentParser(self, argList):
syntax = self.syntax()
parserArguments = OpenMaya.MArgDatabase(syntax, argList)
if parserArguments.isFlagSet(kSparseFlag):
self.sparse = parserArguments.flagArgumentDouble(kSparseFlag, 0)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kSparseLongFlag):
self.sparse = parserArguments.flagArgumentDouble(kSparseLongFlag, 0)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kHelpFlag):
self.setResult(helpMessage)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kHelpLongFlag):
self.setResult(helpMessage)
return OpenMaya.MStatus.kSuccess
def isUndoable(self):
return True
def undoIt(self):
print "undo"
mFnDagNode = OpenMaya.MFnDagNode(self.mObjParticle)
mDagMod = OpenMaya.MDagModifier()
mDagMod.deleteNode(mFnDagNode.parent(0))
mDagMod.doIt()
return OpenMaya.MStatus.kSuccess
def redoIt(self):
mSel = OpenMaya.MSelectionList()
mDagPath = OpenMaya.MDagPath()
mFnMesh = OpenMaya.MFnMesh()
OpenMaya.MGlobal.getActiveSelectionList(mSel)
if mSel.length() >= 1:
try:
mSel.getDagPath(0, mDagPath)
mFnMesh.setObject(mDagPath)
except:
print "please select a poly mesh"
return OpenMaya.MStatus.kUnknownParameter
else:
print "please select a poly mesh"
return OpenMaya.MStatus.kUnknownParameter
mPointArray = OpenMaya.MPointArray()
mFnMesh.getPoints(mPointArray, OpenMaya.MSpace.kWorld)
mFnParticle = OpenMayaFX.MFnParticleSystem()
self.mObjParticle = mFnParticle.create()
mFnParticle = OpenMayaFX.MFnParticleSystem(self.mObjParticle)
counter == 0
for i in xrange(mPointArray.length()):
if i%self.sparse == 0:
mFnParticle.emit(mPointArray[i])
counter += 1
print "total points :" + str(counter)
mFnParticle.saveInitialState()
return OpenMaya.MStatus.kSuccess
def doIt(self, argList):
self.argumentParser(argList)
if self.sparse != None:
self.redoIt()
return OpenMaya.MStatus.kSuccess
def cmdCreator():
return OpenMayaMPx.asMPxPtr(pluginCommand())
def syntaxCreator():
syntax = OpenMaya.MSyntax()
syntax.addFlag(kHelpFlag, kHelpLongFlag)
syntax.addFlag(kSparseFlag, kSparseLongFlag, OpenMaya.MSyntax.kDouble)
return syntax
def initializePlugin(mObject):
mPlugin = OpenMayaMPx.MFnPlugin(mObject)
try:
mPlugin.registerCommand(commandName, cmdCreator, syntaxCreator)
except:
sys.stderr.write("Failed to register" + commandName)
def uninitializePlugin(mObject):
mPlugin = OpenMayaMPx.MFnPlugin(pluginCommand())
try:
mPlugin.deregisterCommand(commandName)
except:
sys.stderr.write("Failed to deregister" + commandName)
Because MStatus.MStatusCode is an enum, you can return its integer value in Python. The only issue is that because in C++ this is an enum, there is no guarantee that the values won't change/shift between releases. This enum has remained consistent since 2019, so there isn't much risk of this happening for MStatus.MStatusCode.
https://help.autodesk.com/view/MAYAUL/2019/ENU/?guid=__cpp_ref_class_m_status_html
https://help.autodesk.com/view/MAYAUL/2023/ENU/?guid=Maya_SDK_cpp_ref_class_m_status_html
Somewhere in the top of your file simply add the constants you intend to use:
MStatus_kSuccess = 0
MStatus_kFailure = 1
MStatus_kUnknownParameter = 5
Then return the constant instead in your functions:
if parserArguments.isFlagSet(kHelpFlag):
self.setResult(helpMessage)
return MStatus_kSuccess

Need Suggestion.

How to debug "NameError: global name 'X' is not defined" in Python? I am pretty much new in Python. I am using jupyter_notebook with Python 2.7 to execute code. I am facing following error.
My code:
logFile = "NASAlog.txt"
def parseLogs():
parsed_logs=(sc
.textFile(logFile)
.map(parseApacheLogLine)
.cache())
access_logs = (parsed_logs
.filter(lambda s: s[1] == 1)
.map(lambda s: s[0])
.cache())
failed_logs = (parsed_logs
.filter(lambda s: s[1] == 0)
.map(lambda s: s[0]))
failed_logs_count = failed_logs.count()
if failed_logs_count > 0:
print 'Number of invalid logline: %d' % failed_logs.count()
for line in failed_logs.take(20):
print 'Invalid logline: %s' % line
print 'Read %d lines, successfully parsed %d lines, failed to parse %d lines' % (parsed_logs.count(), access_logs.count(), failed_logs.count())
return parsed_logs, access_logs, failed_logs
parsed_logs, access_logs, failed_logs = parseLogs()
ERROR
> NameError Traceback (most recent call last)
> <ipython-input-18-b365aa793252> in <module>()
> 24 return parsed_logs, access_logs, failed_logs
> 25
> ---> 26 parsed_logs, access_logs, failed_logs = parseLogs()
>
> <ipython-input-18-b365aa793252> in parseLogs()
> 2
> 3 def parseLogs():
> ----> 4 parsed_logs=(sc
> 5 .textFile(logFile)
> 6 .map(parseApacheLogLine)
>
> NameError: global name 'sc' is not defined
The problem is that you did never define sc. Therefore python can't find it. (Makes sense, doesn't it?)
Now there are several possible reasons:
- python is case-sensitive. Did you somewhere define SC instead of sc? ... Or Sc instead of sc?
You defined sc in another function (-> you defined it in a function outside parseLogs()). If you only define it there the variable will be local and just be available to the code inside the function. Add the line global sc to the first line of your function to make it accessible everywhere in you whole code.
You simply did not define sc.

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.

Weird bug in python project

I'm working on a big project in Python, and I've run into a bizarre error I can't explain. In one of my classes, I have a private method being called during instantiation:
def _convertIndex(self, dimInd, dimName):
'''Private function that converts numbers to numbers and non-integers using
the subclass\'s convertIndex.'''
print dimInd, ' is dimInd'
try:
return int(dimName)
except:
if dimName == '*':
return 0
else:
print self.param.sets, ' is self.param.sets'
print type(self.param.sets), ' is the type of self.param.sets'
print self.param.sets[dimInd], ' is the param at dimind'
return self.param.sets[dimInd].value(dimName)
What it's printing out:
0 is dimInd
[<coremcs.SymbolicSet.SymbolicSet object at 0x10618ad90>] is self.param.sets
<type 'list'> is the type of self.param.sets
<SymbolicSet BAZ=['baz1', 'baz2', 'baz3', 'baz4']> is the param at dimind
======================================================================
ERROR: testParameterSet (GtapTest.TestGtapParameter)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/myuser/Documents/workspace/ilucmc/gtapmcs/test/GtapTest.py", line 116, in testParameterSet
pset = ParameterSet(prmFile, dstFile, GtapParameter)
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/ParameterSet.py", line 103, in __init__
self.distroDict, corrDefs = AbsBaseDistro.readFile(distFile, self.paramDict)
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/Distro.py", line 359, in readFile
distro = cls.parseDistro(param, target, distroType, args)
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/Distro.py", line 301, in parseDistro
return cls(param, target, distro, dim_names, argDict)
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/Distro.py", line 150, in __init__
self.dim_indxs = list(starmap(self._convertIndex, enumerate(dim_names))) # convert to numeric values and save in dim_indxs
File "/Users/myuser/Documents/workspace/ilucmc/coremcs/Distro.py", line 194, in _convertIndex
print self.param.sets[dimInd], ' is the param at dimind'
IndexError: list index out of range
Obviously this isn't the code for the whole class, but it represents something that I don't understand. The error is coming when I index into self.param.sets. Apparently, dimInd is out of range. the problem is, dimInd is 0, and self.param.sets is a list of length 1 (as shown from the print statements), so why can't I index into it?
EDIT: For what it's worth, the __init__ method looks like this:
'''
Stores a definitions of a distribution to be applied to a header variable.
See the file setup/gtap/DistroDoc.txt for the details.
'''
def __init__(self, param, target, distType, dim_names, argDict):
self.name = param.name
self.dim_names = dim_names
self.dim_indxs = []
self.target = target.lower() if target else None
self.distType = distType.lower() if distType else None
self.rv = None
self.argDict = {}
self.modifier = defaultdict(lambda: None)
self.param = param
# Separate args into modifiers and distribution arguments
for k, v in argDict.iteritems():
if k[0] == '_': # modifiers start with underscore
self.modifier[k] = v
else:
self.argDict[k] = v # distribution arguments do not have underscore
if self.target == 'index':
print dim_names
self.dim_indxs = list(starmap(self._convertIndex, enumerate(dim_names))) # convert to numeric values and save in dim_indxs
if distType == 'discrete':
entries = self.modifier['_entries']
if not entries:
raise DistributionSpecError("Not enough arguments given to discrete distribution.")
modDict = {k[1:]: float(v) for k, v in self.modifier.iteritems() if k[1:] in getOptionalArgs(DiscreteDist.__init__)}
self.rv = DiscreteDist(entries, **modDict)
return
sig = DistroGen.signature(distType, self.argDict.keys())
gen = DistroGen.generator(sig)
if gen is None:
raise DistributionSpecError("Unknown distribution signature %s" % str(sig))
self.rv = gen.makeRV(self.argDict) # generate a frozen RV with the specified arguments
self.isFactor = gen.isFactor

Categories

Resources