Commits

German Larrain committed 26094e0

ARS library: big cleanup of comments; incorrect docstrings wrapped in comments blocks

Comments (0)

Files changed (9)

ars/app/__init__.py

 #
 # @author: german
 
-# TODO: attribute the code sections that were copied from somewhere else (I don't think there are any here)
-
 import sys
 from abc import abstractmethod
 import math
 		# add the graphic objects
 		self.gAdapter.add_objects_list(self.sim.get_actors().values())
 		self.sim.update_actors()
-		#self.gAdapter.restartWindow()
-#		self.gAdapter.start_window(self.sim.on_idle, self.create_simulation)
 
 	@abstractmethod
 	def create_sim_objects(self):
 		self.key_press_functions.add('v', self.dec_joint_vel)
 		self.key_press_functions.add('g', self.inc_joint_pos)
 		self.key_press_functions.add('b', self.dec_joint_pos)
-		# TODO: add 'toggle use of QuickStep function'
 
 	def on_action_selection(self, key):
 		if self.PRINT_KEY_INFO:
 		add torque to an already selected joint
 		'''
 		print('add_torque has not been fully implemented')
-		#self.sim.get_joint('r1').add_torque(1000) # FIXME: use member or global variable
 	
 	def inc_joint_vel(self):
 		'''
 #===============================================================================
 
 	def read_filenames(self):
-		# TODO: see Ragdoll2.ars.RagdollPyOdeVtk
 		print('read_filenames has not been implemented')
 	
 	def open_files(self):
-		# TODO: see Ragdoll2.ars.RagdollPyOdeVtk
 		print('open_files has not been implemented')
 	
 	def close_files(self, files):
 		"""
 		if self._screenshot_recorder is None:
 			raise Exception('Screenshot recorder is not initialized')
-		#=======================================================================
-		# elif self._screenshot_recorder.image_getter is None:
-		#	print('screenshot_recorder.image_getter is None')
-		#	self._screenshot_recorder.set_input(self.gAdapter.renWin)
-		#	print('screenshot_recorder input was set')
-		#=======================================================================
 
 		try:
 			time = self.sim.sim_time
 		except Exception as e:
 			raise Exception('Could not record frame', e)
 
-		#=======================================================================
-		# try:
-		#	time = self.sim.sim_time
-		#	last_time = self._screenshot_recorder.last_write_time
-		#	period = self._screenshot_recorder.period
-		#	
-		#	if period is None:
-		#		self._screenshot_recorder.write(self.sim.num_frame)
-		#	else:
-		#		time_adjusted = time + self.sim.get_time_step()
-		#		if last_time is None:
-		#			last_time = 0.0
-		#			index = 0
-		#		elif time_adjusted - last_time >= period:
-		#			index = int(math.floor(time_adjusted / period))
-		#		else:
-		#			return False
-		#		self._screenshot_recorder.write(index, time)
-		# except Exception as e:
-		#	raise Exception('Could not record frame', e)
-		#=======================================================================
-
-# TODO: see if it is better that this is derived from dictionary or another builtin class
 class ActionMap:
 	def __init__(self):
 		self._map = {}
 
 from ars.utilities.mathematical import mult_by_scalar3
 
+#===============================================================================
+# GEOMETRY
+#===============================================================================
+
 X_AXIS = (1,0,0)
 Y_AXIS = (0,1,0)
 Z_AXIS = (0,0,1)
 OUTWARDS_AXIS = Z_AXIS
 
 
+#===============================================================================
+# COLORS
+#===============================================================================
+
 def convert_color(R_int, G_int, B_int):
 	return mult_by_scalar3((R_int,G_int,B_int), 1.0 / 256)
 
 # names according to W3C Recommendation - 4.4 Recognized color keyword names
 # http://www.w3.org/TR/SVG/types.html#ColorKeywords
 
-#===============================================================================
-# COLOR_RED = convert_color(255,0,0)
-# COLOR_LIME = convert_color(0,1.0,0)
-# COLOR_BLUE = convert_color(0,0,1.0)
-# COLOR_YELLOW = convert_color(1.0,1.0,0)
-# COLOR_YELLOW = (0.835,0.9725,0)
-#===============================================================================
-
 COLOR_BLACK = 		convert_color(0,0,0)
 COLOR_BLUE = 		convert_color(0,0,255)
 COLOR_BROWN = 		convert_color(165,42,42)

ars/graphics/__init__.py

 TIMER_PERIOD = 50 # milliseconds
 TIMER_EVENT = 'TimerEvent'
 KEY_PRESS_EVENT = 'KeyPressEvent'
-NULL_QUAT = (0, 0, 1, 0)
 EYE_3X3 = ((1,0,0),(0,1,0),(0,0,1))
 
 class Axes:
 		self.last_write_time = None
 		self.period = None
 	
-	#===========================================================================
-	# @abstractmethod
-	# def set_input(self):
-	#	raise Exception('abstract method')
-	#===========================================================================
-	
 	@abstractmethod
 	def write(self, index):
 		"""

ars/graphics/adapters.py

 		self.renWin.SetSize(*self._size)
 		self.renWin.SetWindowName(self._title)
 		
-		#=======================================================================
-		# self.ren.ResetCamera()
-		# self.ren.GetActiveCamera().SetPosition(self._cam_position)
-		# self.ren.GetActiveCamera().Zoom(self._zoom)
-		#=======================================================================
-		
 		camera = vtk.vtkCamera()
 		camera.SetPosition(self._cam_position)
 		camera.Zoom(self._zoom)
 		self.ren.SetActiveCamera(camera)
-		#self.ren.ResetCameraClippingRange()
-		
-		#=======================================================================
-		# if self._windowStarted == True:
-		#	#self.iren.ReInitialize()
-		#	pass
-		# else:
-		#	self.iren.Initialize()
-		#=======================================================================
-
-		#=======================================================================
-		# if self.iren.GetInitialized():
-		#	self.renWin.Finalize()
-		#	
-		# if not self._windowStarted:
-		#	self.iren.Initialize()
-		#=======================================================================
-		
-		# self.iren.Initialize() seems to be not necessary
-		
 		self.renWin.Render()
 		
-		#=======================================================================
-		# print(self.ren.GetActiveCamera().GetPosition())
-		# print(self.ren.GetActiveCamera().GetFocalPoint())
-		#=======================================================================
-		
-		#=======================================================================
-		# if not self._windowStarted:
-		#	# events
-		#	self.iren.AddObserver(gp.TIMER_EVENT, self._timer_callback)
-		#	timerId = self.iren.CreateRepeatingTimer(gp.TIMER_PERIOD)
-		#	self.iren.AddObserver(gp.KEY_PRESS_EVENT, self._key_press_callback)
-		#	
-		#	self._windowStarted = True
-		#	self.iren.Start()
-		#=======================================================================
-		
 		self.iren.AddObserver(gp.TIMER_EVENT, self._timer_callback)
 		timerId = self.iren.CreateRepeatingTimer(gp.TIMER_PERIOD)  #@UnusedVariable
 		self.iren.AddObserver(gp.KEY_PRESS_EVENT, self._key_press_callback)
 	
 	def restart_window(self):
 		# TODO: code according to start_window(), reset() and the desired behavior
-		#=======================================================================
-		# if self._windowStarted == True:
-		#	self.iren.Initialize()
-		#	self.renWin.Render()
-		#	self.iren.Start() 
-		#=======================================================================
 		raise Exception()
 
 	@staticmethod
 		# remove all actors
 		try:
 			self.ren.RemoveAllViewProps()
-			#self.iren.UnRegister(self.renWin)
 			self.iren.ExitCallback()
-			#self.renWin.Finalize()
 		except AttributeError:
 			pass
 		#self.restartWindow()
 		self.last_write_time = None
 		self.period = None
 	
-	#===========================================================================
-	# def set_input(self, render_window):
-	#	self.image_getter = vtk.vtkWindowToImageFilter()
-	#	self.image_getter.SetInput(render_window)
-	#	self.image_getter.Update()
-	#===========================================================================
-	
 	def write(self, index=1, time=None):
 		"""
 		Writes the current image displayed in the render window as a PNG file
 		'.png' extension.
 		"""
 		# TODO: see if the workaround (get renWin and create image_getter every time)
-		# was need because we used image_getter.SetInput instead of SetInputConnection
+		# was needed because we used image_getter.SetInput instead of SetInputConnection
 		render_window = self.gAdapter.renWin
 		image_getter = vtk.vtkWindowToImageFilter()
 		image_getter.SetInput(render_window)

ars/model/contrib/ragdoll.py

 #
 # @author: german
 
+# TODO:	attribute the code sections that were taken from somewhere else
 
 import ode
 
 		# cylinder length not including endcaps, make capsules overlap by half radius at joints
 		cyllen = mut.dist3(p1, p2) - radius
 
-		#body, geom = phs.create_capsule_body_and_geom(self.world, self.space, self.density, cyllen, radius)
 		body = phs.Capsule(self.world, self.space, cyllen, radius, density=self.density)
 		
 		# define body rotation automatically from body axis
 		body.set_rotation(rot)
 
 		self.bodies.append(body)
-		#self.geoms.append(geom)
 		self.totalMass += body.get_mass()
 
 		return body
 		joint.attach(body1.get_inner_object(), body2.get_inner_object())
 		joint.setAnchor(anchor)
 
-		'''
-		store the base orientation of the joint in the local coordinate system of the primary body
-		(because baseAxis and baseTwistUp may not be orthogonal, the nearest vector to baseTwistUp
-		but orthogonal to baseAxis is calculated and stored with the joint)
-		'''
+		#=======================================================================
+		# store the base orientation of the joint in the local coordinate system of the primary body
+		# (because baseAxis and baseTwistUp may not be orthogonal, the nearest vector to baseTwistUp
+		# but orthogonal to baseAxis is calculated and stored with the joint)
+		#=======================================================================
 		joint.baseAxis = mut.get_body_relative_vector(body1, baseAxis)
 		tempTwistUp = mut.get_body_relative_vector(body1, baseTwistUp)
 		baseSide = mut.norm3(mut.cross_product(tempTwistUp, joint.baseAxis))
 		joint.baseTwistUp = mut.norm3(mut.cross_product(joint.baseAxis, baseSide))
 
-		'''
-		store the base twist up vector (original version) in the
-		local coordinate system of the secondary body
-		'''
+		#=======================================================================
+		# store the base twist up vector (original version) in the
+		# local coordinate system of the secondary body
+		#=======================================================================
 		joint.baseTwistUp2 = mut.get_body_relative_vector(body2, baseTwistUp)
 
 		# store joint rotation limits and resistive force factors
 					j.getBody(1).addTorque(mut.mult_by_scalar3(flexAngVel,
 						-0.01 * j.flexForce))
 
-				'''
-				determine the base twist up vector for the current attached body by applying the
-				current joint flex to the fixed body's base twist up vector
-				'''
+				#===============================================================
+				# determine the base twist up vector for the current attached body by applying the
+				# current joint flex to the fixed body's base twist up vector
+				#===============================================================
 				baseTwistUp = mut.rotate3(j.getBody(0).getRotation(), j.baseTwistUp)
 				base2current = mut.calc_rotation_matrix(mut.norm3(mut.cross_product(baseAxis, currAxis)),
 					mut.acos_dot3(baseAxis, currAxis))

ars/model/simulator/__init__.py

 # Created on 2011.10.17
 #
 # @author: german
-# TODO: attribute the code sections that were copied from somewhere else
+
 # TODO: delete the calls body.setPosition() and body.setRotation() in the createXXX() methods
 
 import random, time
 			print(e)
 		
 		self.perform_sim_steps_per_frame()
-		# clear functions registered to be called
-		# in the steps of this past frame
+		# clear functions registered to be called in the steps of this past frame
 		self.all_frame_steps_callbacks = []
 				
 		if self._debug:	
 			except:
 				pass
 			
-			# call all functions registered to be called
-			# before each step of the next frame
+			# call all registered functions before each step of the next frame
 			try:
 				for callback_ in self.all_frame_steps_callbacks:
 					callback_()
 			# Simulation step
 			time_step = self.get_time_step()
 			
-			#===================================================================
-			# if WRITE_DATA_FILES:
-			#	self.writeDataFiles(self.dataFiles)
-			#===================================================================
-			
 			self._world.step(time_step)
 			self.sim_time += time_step
 			self.num_iter += 1
 		self._ragdoll.printMass()
 		
 		for rBody in self._ragdoll.bodies:
-			#rBodySize = (rBody.radius * 2, rBody.radius * 2, rBody.length + rBody.radius * 2)
 			actor = gp.Capsule(rBody.get_length(), rBody.get_radius(), rBody.get_position())
 			name = str(rBody)
 			self.add_object(SimulatedObject(name, rBody, actor))
 		body1 = obj1.get_body()
 		body2 = obj2.get_body()
 		f_joint = jo.Fixed(self._world, body1, body2)
-		#self._joints.add_joint(joint)
 		return self.add_joint(SimulatedJoint(joint=f_joint))
 		
 	def add_rotary_joint(self, name, obj1, obj2, anchor, axis):
 	def get_time_step(self):
 		return self._DT / self._STEPS_PF
 
-#===============================================================================
-#	 # see Ragdoll2.ars.RagdollPyOdeVtk
-#	def writeDataFiles(self, files):
-#		gu.writeTupleToFile(files[settingsFileRagdollHeadPosKey],
-#							gu.insertInTuple(self._ragdoll.head.getPosition(), 0, self.sim_time))
-#		gu.writeTupleToFile(files[settingsFileRagdollHeadVelKey],
-#							gu.insertInTuple(self._ragdoll.head.getLinearVel(), 0, self.sim_time))
-#		gu.writeTupleToFile(files[settingsFileRagdollHeadForceKey],
-#							gu.insertInTuple(self._ragdoll.head.getTorque(), 0, self.sim_time)) #TODO: replace torque with force
-#							# gu.insertInTuple(self._ragdoll.head.getForce(), 0, self.sim_time))
-# 
-#		gu.writeTupleToFile(files[settingsFileObstaclePosKey],
-#							gu.insertInTuple(self.bodies[0].getPosition(), 0, self.sim_time))
-#		gu.writeTupleToFile(files[settingsFileObstacleVelKey],
-#							gu.insertInTuple(self.bodies[0].getLinearVel(), 0, self.sim_time))
-#===============================================================================
-
 
 class SimulatedObject:
 	
 	def __init__(self, name, body=None, actor=None, geom=None):
 		if not name: # TODO: see if the SimulatedJoint constructor alternative is better
-			raise Exception('give a valid name') # TODO: choose a better class
+			raise Exception('give a valid name')
 		
 		self._name = name
 		self._body = body

ars/model/simulator/collision.py

 
 class Space:
 	def __init__(self):
-		self._inner_object = ode.SimpleSpace() # equivalent to ode.Space(space_type=0)
+		self._inner_object = ode.SimpleSpace() # same as ode.Space(space_type=0)
 		
 	def get_inner_object(self):
 		return self._inner_object

ars/model/simulator/physics.py

 
 # Created on 2011.08.09
+#
 # @author: german
-#
-# TODO: attribute the code sections that were copied from somewhere else
 
 from abc import ABCMeta, abstractmethod
 
 import ode
 
-#from ars.utilities import mathematical as mut
 from ars.model.geometry import shapes as shapes
 
 class Engine:
 			if density is not None:
 				raise Exception('Both mass and density arguments were given')
 		
-		# create a capsule geom for collision detection
-		#geom = ode.GeomCCylinder(space.get_inner_object(), radius, length)
-		#geom.setBody(body)
-		
 		self._length = length
 		self._radius = radius
 		
 			if density is not None:
 				raise Exception('Both mass and density arguments were given')
 		
-		#geom = ode.GeomCylinder(space.get_inner_object(), radius, length)
-		#geom.setBody(body)
-		
 		self._length = length
 		self._radius = radius
 	
 	def __init__(self, world, space, height, radius, mass=None, density=None):
 		raise Exception("Not available in ODE")
 
-def create_world(gravity = (0.0,-9.81,0.0), ERP = 0.8, CFM = 1E-10):
+def create_world(gravity=(0.0,-9.81,0.0), ERP=0.8, CFM=1E-10):
 	""" Create an ODE world object. """
 	world = ode.World()
 	world.setGravity(gravity)
 
 def create_plane_geom(space, normal, dist):
 	return ode.GeomPlane(space.get_inner_object(), normal, dist)
-
-if __name__ == '__main__':
-	print('this is physics.py')

ars/utilities/mathematical.py

 # Created on 2011.08.09
 #
 # @author: german
-#
-# TODO:	attribute the code sections that were copied from somewhere else
-#		create a test for calc_rotation_matrix
+
+# TODO:	attribute the code sections that were taken from somewhere else
+# TODO: create a test for calc_rotation_matrix
 
 '''
 Functions to perform operations over vectors and matrices; 
 
 from math import sqrt, pi, cos, sin, acos
 
-'''
-rotation directions are named by the third (z-axis) row of the 3x3 matrix, because ODE capsules
-are oriented along the Z-axis
-'''
+#===============================================================================
+# rotation directions are named by the third (z-axis) row of the 3x3 matrix, because ODE capsules
+# are oriented along the Z-axis
+#===============================================================================
+
 rightRot = (0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0)
 leftRot = (0.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 0.0)
 upRot = (1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0)
 bkwdAxis = (0.0, 0.0, 1.0)
 fwdAxis = (0.0, 0.0, -1.0)
 
-'''
-added to the original refactored code
-'''
+#===============================================================================
+# added to the original refactored code
+#===============================================================================
+
 def radians_to_degrees(radians_):
 	return math.degrees(radians_)
 
 def matrix3_multiply(matrix1, matrix2):
 	'''
 	returns the matrix multiplication of matrix1 and matrix2.
-	TODO: check objects are valid, or use exceptions to catch errors raised by numpy
 	'''
+	#TODO: check objects are valid, or use exceptions to catch errors raised by numpy
+	
 	import numpy as np
+	
 	a1 = np.array(matrix1)
 	a2 = np.array(matrix2)
 	result = np.dot(a1, a2)
+	
 	return matrix_as_3x3_tuples(tuple(result.flatten()))
 
 def matrix_as_tuple(matrix_):
 	'''
 	matrix_: nested tuples, e.g. ((1,0),(1,1),(2,5))
-	TODO: improve a lot
 	'''
+	#TODO: improve a lot
 	return gut.nested_iterable_to_tuple(matrix_)
 
 def matrix_as_3x3_tuples(tuple_9):
-	'''
-	TODO: improve a lot
-	'''
+	#TODO: improve a lot
+
 	matrix = None
 	if isinstance(tuple_9, tuple):
 		if len(tuple_9) == 9:
 	def get_rotation_matrix(self):
 		raise NotImplementedError()
 
-'''
-Original code, although modified
-'''
+#===============================================================================
+# Original code but formatted and some refactor
+#===============================================================================
 
 def sign(x):
 	"""Returns 1.0 if x is positive, -1.0 if x is negative or zero."""
 	"""
 	return rotate3(transpose3(body.get_rotation()), vector)
 
-
-'''
-TESTS
-'''
+#===============================================================================
+# TESTS
+#===============================================================================
 
 def _test_angular_conversions(angle_):
 	#x = 2.0/3*math.pi
 	print(t.get_long_tuple())	
 
 if __name__ == '__main__':
-	print('this is mathUtilities.py')
 	
 	_test_rot_matrix_to_hom_transform()
 	_test_angular_conversions(2.0/3*math.pi)
 	_test_angular_conversions(4.68*math.pi)
-	
-	'''
-	TODO: refactor
-	'''
+
 	radians_ = (2.0/3*math.pi, 2.0*math.pi, 1.0/4*math.pi)
 	degrees_ = (120, 360, 45)
 	print(vec3_radians_to_degrees(radians_))