index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
18,649
|
dylanbking97/big-fun-data
|
refs/heads/master
|
/setup.py
|
import pymongo
import pymongo_spark
on_time_dataframe = spark.read.format('com.databricks.spark.csv.options(header='true',treatEmptyValuesAsNulls='true',)/
.load('data/On_Time_On_Time_Performance_2015.csv.bz2'))
on_time_dataframe.registerTempTable("on_time_performance")
trimmed_cast_performance = spark.sql("""SELECT Year, Quarter, Month, DayofMonth, DayOfWeek, FlightDate, Carrier, TailNum, FlightNum,
Origin, OriginCityName, OriginState, Dest, DestCityName, DestState, DepTime, cast(DepDelay as float), cast(DepDelayMinutes as int),
cast(TaxiOut as float), cast(TaxiIn as float), WheelsOff, WheelsOn, ArrTime, cast(ArrDelay as float), cast(ArrDelayMinutes as float),
cast(Cancelled as int), cast(Diverted as int), cast(ActualElapsedTime as float), cast(AirTime as float), cast(Flights as int),
cast(Distance as float), cast(CarrierDelay as float), cast(WeatherDelay as float), cast(NASDelay as float), cast(SecurityDelay as float),
cast(LateAircraftDelay as float), CRSDepTime, CRSArrTime FROM on_time_performance""")
# Replace on_time_performance table with our new, trimmed table and show its columns
trimmed_cast_performance.registerTempTable("on_time_performance")
#trimmed_cast_performance.show()
trimmed_cast_performance.write.parquet("data/on_time_performance.parquet")
on_time_dataframe = spark.read.parquet('data/on_time_performance.parquet')
pymongo_spark.activate()
#convert each row to a dict
as_dict = on_time_dataframe.rdd.map(lambda row: row.asDict())
#This collection acts as a base table containing all information about the flights
as_dict.saveToMongoDB('mongodb://localhost:27017/agile_data_science.on_time_performance')
#Create an index that will speed up queries for getting all flights from one airport to another, on a given date
db.on_time_performance.ensureIndex({Origin: 1, Dest: 1, FlightDate: 1})
#Create an airplane entity, identifiable by its tail number
# Filter down to the fields we need to identify and link to a flight
flights = on_time_dataframe.rdd.map(lambda x:(x.Carrier, x.FlightDate, x.FlightNum, x.Origin, x.Dest, x.TailNum))
flights_per_airplane = flights.map(lambda nameTuple: (nameTuple[5], [nameTuple[0:5]]))\
.reduceByKey(lambda a, b: a + b)\
.map(lambda tuple:{'TailNum': tuple[0], 'Flights': sorted(tuple[1], key=lambda x: (x[1], x[2]))})
pymongo_spark.activate()
#This table contains a basic flight history for each airplane
flights_per_airplane.saveToMongoDB('mongodb://localhost:27017/agile_data_science.flights_per_airplane')
#Create an index for the quickly fetching all of the flights for a given airplane (identified by tail number)
db.flights_per_airplane.ensureIndex({"TailNum": 1})
# Get all unique tail numbers for each airline
on_time_dataframe.registerTempTable("on_time_performance")
carrier_airplane = spark.sql("SELECT DISTINCT Carrier, TailNum FROM on_time_performance")
# Now we need to store a sorted list of tail numbers for each carrier, along with a fleet count
airplanes_per_carrier = carrier_airplane.rdd.map(lambda nameTuple: (nameTuple[0], [nameTuple[1]]))\
.reduceByKey(lambda a, b: a + b).map(lambda tuple:
{'Carrier': tuple[0],'TailNumbers': sorted(filter(lambda x: x != '', tuple[1])),'FleetCount': len(tuple[1])})
#This collection contains the fleet of each airplane carrier
airplanes_per_carrier.saveToMongoDB('mongodb://localhost:27017/agile_data_science.airplanes_per_carrier')
|
{"/controller.py": ["/setup.py"]}
|
19,001
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/Boo.py
|
"""
Peek-A-Boo game inspired by the Boo game of Pablo Barros.
This version is coded using the cozmo_fsm package and illustrates
features such as repetitive polling, nested state machines, and a
completion transition that uses one completing source node to
terminate a second source (MoveHead) that doesn't complete.
"""
from cozmo_fsm import *
class WaitForPlayer(StateMachineProgram):
"""Wait for player's face to appear and remain visible for a little while."""
def start(self,event=None):
self.set_polling_interval(0.2)
self.faces_found = 0 # initialize before polling starts
super().start(event)
def poll(self):
if self.robot.world.visible_face_count() == 0: return
self.faces_found += 1
if self.faces_found > 3:
self.post_completion()
class WaitForHide(StateNode):
"""Wait for player's face to disappear and remain not visible for a little while."""
def start(self,event=None):
self.set_polling_interval(0.2)
self.faces_not_found = 0 # initialize before polling starts
super().start(event)
def poll(self):
if self.robot.world.visible_face_count() > 0: return
self.faces_not_found += 1
if self.faces_not_found > 2:
self.post_completion()
class HeadAndLiftGesture(StateNode):
"""Move head and lift simultaneously. Finish when head movement completes."""
def setup(self):
"""
launch: StateNode() =N=> {move_head, move_lift}
move_head: SetHeadAngle(cozmo.robot.MAX_HEAD_ANGLE)
move_lift: MoveLift(-3)
{move_head, move_lift} =C(1)=> ParentCompletes()
"""
# Code generated by genfsm on Mon Feb 17 03:10:20 2020:
launch = StateNode() .set_name("launch") .set_parent(self)
move_head = SetHeadAngle(cozmo.robot.MAX_HEAD_ANGLE) .set_name("move_head") .set_parent(self)
move_lift = MoveLift(-3) .set_name("move_lift") .set_parent(self)
parentcompletes1 = ParentCompletes() .set_name("parentcompletes1") .set_parent(self)
nulltrans1 = NullTrans() .set_name("nulltrans1")
nulltrans1 .add_sources(launch) .add_destinations(move_head,move_lift)
completiontrans1 = CompletionTrans(1) .set_name("completiontrans1")
completiontrans1 .add_sources(move_head,move_lift) .add_destinations(parentcompletes1)
return self
class Boo(StateNode):
def setup(self):
"""
launch: Say("Let's play")
=C=> SetHeadAngle(30)
=C=> player_appears
player_appears: WaitForPlayer()
=C=> AnimationNode('anim_freeplay_reacttoface_identified_01_head_angle_40')
=C=> SetHeadAngle(cozmo.robot.MIN_HEAD_ANGLE)
=C=> SetHeadAngle(cozmo.robot.MAX_HEAD_ANGLE)
=C=> player_hides
player_hides: WaitForHide()
=C=> AnimationNode('anim_hiking_observe_01')
=C=> HeadAndLiftGesture()
=C=> player_reappears
player_reappears: WaitForPlayer()
=C=> AnimationNode('anim_freeplay_reacttoface_like_01')
=C=> HeadAndLiftGesture()
=C=> Say("play again")
=C=> SetHeadAngle(30)
=C=> player_hides
"""
# Code generated by genfsm on Mon Feb 17 03:10:20 2020:
launch = Say("Let's play") .set_name("launch") .set_parent(self)
setheadangle1 = SetHeadAngle(30) .set_name("setheadangle1") .set_parent(self)
player_appears = WaitForPlayer() .set_name("player_appears") .set_parent(self)
animationnode1 = AnimationNode('anim_freeplay_reacttoface_identified_01_head_angle_40') .set_name("animationnode1") .set_parent(self)
setheadangle2 = SetHeadAngle(cozmo.robot.MIN_HEAD_ANGLE) .set_name("setheadangle2") .set_parent(self)
setheadangle3 = SetHeadAngle(cozmo.robot.MAX_HEAD_ANGLE) .set_name("setheadangle3") .set_parent(self)
player_hides = WaitForHide() .set_name("player_hides") .set_parent(self)
animationnode2 = AnimationNode('anim_hiking_observe_01') .set_name("animationnode2") .set_parent(self)
headandliftgesture1 = HeadAndLiftGesture() .set_name("headandliftgesture1") .set_parent(self)
player_reappears = WaitForPlayer() .set_name("player_reappears") .set_parent(self)
animationnode3 = AnimationNode('anim_freeplay_reacttoface_like_01') .set_name("animationnode3") .set_parent(self)
headandliftgesture2 = HeadAndLiftGesture() .set_name("headandliftgesture2") .set_parent(self)
say1 = Say("play again") .set_name("say1") .set_parent(self)
setheadangle4 = SetHeadAngle(30) .set_name("setheadangle4") .set_parent(self)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(launch) .add_destinations(setheadangle1)
completiontrans3 = CompletionTrans() .set_name("completiontrans3")
completiontrans3 .add_sources(setheadangle1) .add_destinations(player_appears)
completiontrans4 = CompletionTrans() .set_name("completiontrans4")
completiontrans4 .add_sources(player_appears) .add_destinations(animationnode1)
completiontrans5 = CompletionTrans() .set_name("completiontrans5")
completiontrans5 .add_sources(animationnode1) .add_destinations(setheadangle2)
completiontrans6 = CompletionTrans() .set_name("completiontrans6")
completiontrans6 .add_sources(setheadangle2) .add_destinations(setheadangle3)
completiontrans7 = CompletionTrans() .set_name("completiontrans7")
completiontrans7 .add_sources(setheadangle3) .add_destinations(player_hides)
completiontrans8 = CompletionTrans() .set_name("completiontrans8")
completiontrans8 .add_sources(player_hides) .add_destinations(animationnode2)
completiontrans9 = CompletionTrans() .set_name("completiontrans9")
completiontrans9 .add_sources(animationnode2) .add_destinations(headandliftgesture1)
completiontrans10 = CompletionTrans() .set_name("completiontrans10")
completiontrans10 .add_sources(headandliftgesture1) .add_destinations(player_reappears)
completiontrans11 = CompletionTrans() .set_name("completiontrans11")
completiontrans11 .add_sources(player_reappears) .add_destinations(animationnode3)
completiontrans12 = CompletionTrans() .set_name("completiontrans12")
completiontrans12 .add_sources(animationnode3) .add_destinations(headandliftgesture2)
completiontrans13 = CompletionTrans() .set_name("completiontrans13")
completiontrans13 .add_sources(headandliftgesture2) .add_destinations(say1)
completiontrans14 = CompletionTrans() .set_name("completiontrans14")
completiontrans14 .add_sources(say1) .add_destinations(setheadangle4)
completiontrans15 = CompletionTrans() .set_name("completiontrans15")
completiontrans15 .add_sources(setheadangle4) .add_destinations(player_hides)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,002
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/events.py
|
"""
The base Event class is imported from evbase.py.
All other events are defined here.
"""
import cozmo
from .evbase import Event
class CompletionEvent(Event):
"""Signals completion of a state node's action."""
pass
class SuccessEvent(Event):
"""Signals success of a state node's action."""
def __init__(self,details=None):
super().__init__()
self.details = details
class FailureEvent(Event):
"""Signals failure of a state node's action."""
def __init__(self,details=None):
super().__init__()
self.details = details
def __repr__(self):
if isinstance(self.details, cozmo.action.Action):
reason = self.details.failure_reason[0]
else:
reason = self.details
return '<%s for %s: %s>' % (self.__class__.__name__, self.source.name, reason)
class DataEvent(Event):
"""Signals a data item broadcasted by the node."""
def __init__(self,data):
super().__init__()
self.data = data
class TextMsgEvent(Event):
"""Signals a text message broadcasted to the state machine."""
def __init__(self,string,words=None,result=None):
super().__init__()
self.string = string
self.words = words or string.split(None)
self.result = result
class SpeechEvent(Event):
"""Results of speech recognition process."""
def __init__(self,string,words=None,result=None):
super().__init__()
self.string = string
self.words = words
self.result = result
class PilotEvent(Event):
"""Results of a pilot request."""
def __init__(self,status,**args):
super().__init__()
self.status = status
self.args = args
def __repr__(self):
try:
src_string = self.source.name
except:
src_string = repr(self.source)
return '<%s %s from %s>' % (self.__class__.__name__, self.status.__name__, src_string)
#________________ Cozmo-generated events ________________
class CozmoGeneratedEvent(Event):
def __init__(self,source,params):
super().__init__()
self.source = source
self.params = params
# Note regarding generator(): we're going to curry this function
# to supply EROUTER and EVENT_CLASS as the first two arguments.
def generator(EROUTER, EVENT_CLASS, cozmo_event, obj=None, **kwargs):
our_event = EVENT_CLASS(obj,kwargs)
EROUTER.post(our_event)
class TapEvent(CozmoGeneratedEvent):
cozmo_evt_type = cozmo.objects.EvtObjectTapped
class FaceEvent(CozmoGeneratedEvent):
cozmo_evt_type = cozmo.faces.EvtFaceAppeared
class ObservedMotionEvent(CozmoGeneratedEvent):
cozmo_evt_type = cozmo.camera.EvtRobotObservedMotion
def __repr__(self):
top = self.params['has_top_movement']
left = self.params['has_left_movement']
right = self.params['has_right_movement']
movement = ''
if top:
pos = self.params['top_img_pos']
movement = movement + ('' if (movement=='') else ' ') + \
('top:(%d,%d)' % (pos.x,pos.y))
if left:
pos = self.params['left_img_pos']
movement = movement + ('' if (movement=='') else ' ') + \
('left:(%d,%d)' % (pos.x,pos.y))
if right:
pos = self.params['right_img_pos']
movement = movement + ('' if (movement=='') else ' ') + \
('right:(%d,%d)' % (pos.x,pos.y))
if movement == '':
pos = self.params['img_pos']
movement = movement + ('' if (movement=='') else ' ') + \
('broad:(%d,%d)' % (pos.x,pos.y))
return '<%s %s>' % (self.__class__.__name__, movement)
class UnexpectedMovementEvent(CozmoGeneratedEvent):
cozmo_evt_type = cozmo.robot.EvtUnexpectedMovement
def __repr__(self):
side = self.params['movement_side']
# side.id == 0 means the movement_side is "unknown"
# Occurs when reaction triggers are disabled (as is normally the case).
side_string = ' '+side.name if side.id > 0 else ''
return '<%s %s%s>' % (self.__class__.__name__,
self.params['movement_type'].name,
side_string)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,003
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/CV_GoodFeatures.py
|
"""
CV_GoodFeatures demonstrates the Shi and Tomasi (1994) feature
extractor built in to OpenCV.
"""
import cv2
import numpy as np
from cozmo_fsm import *
class CV_GoodFeatures(StateMachineProgram):
def __init__(self):
super().__init__(aruco=False, cam_viewer=False, annotate_sdk=False)
def start(self):
self.colors = np.random.randint(0,255,(101,3),dtype=np.int)
dummy = numpy.array([[0]],dtype='uint8')
super().start()
cv2.namedWindow('features')
cv2.imshow('features',dummy)
cv2.createTrackbar('maxCorners','features',50,100,lambda self: None)
cv2.createTrackbar('qualityLevel','features',10,1000,lambda self: None)
cv2.createTrackbar('minDistance','features',5,50,lambda self: None)
def user_image(self,image,gray):
cv2.waitKey(1)
maxCorners = max(1,cv2.getTrackbarPos('maxCorners','features'))
quality = max(1,cv2.getTrackbarPos('qualityLevel','features'))
cv2.setTrackbarPos('qualityLevel', 'features', quality) # don't allow zero
minDist = max(1,cv2.getTrackbarPos('minDistance','features'))
cv2.setTrackbarPos('minDistance', 'features', minDist) # don't allow zero
qualityLevel = quality / 1000
corners = cv2.goodFeaturesToTrack(gray, maxCorners, qualityLevel, minDist)
(x,y,_) = image.shape
image = cv2.resize(image,(y*2,x*2))
i = 0
for corner in corners:
x,y = corner.ravel()
x = int(x*2); y = int(y*2)
color_index = (x+y) % self.colors.shape[0]
color = self.colors[color_index].tolist()
cv2.circle(image, (x, y), 4, color, -1)
i += 1
cv2.imshow('features',image)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,004
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/Greet.py
|
"""
The Greet demo illustrates the use of CompletionTrans and TimerTrans
transitions.
Behavior: Cozmo starts out by saying 'Greetings, human!'. After his
speech has completed, he waits 5 seconds, then says 'Bye-bye now'.
"""
from cozmo_fsm import *
class Greet(StateMachineProgram):
def setup(self):
"""
say: Say('Greetings, human!') =C=>
wait: StateNode() =T(5)=>
say2: Say('Bye-bye now.')
"""
# Code generated by genfsm on Mon Feb 17 03:12:53 2020:
say = Say('Greetings, human!') .set_name("say") .set_parent(self)
wait = StateNode() .set_name("wait") .set_parent(self)
say2 = Say('Bye-bye now.') .set_name("say2") .set_parent(self)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(say) .add_destinations(wait)
timertrans1 = TimerTrans(5) .set_name("timertrans1")
timertrans1 .add_sources(wait) .add_destinations(say2)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,005
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/CV_OpticalFlow.py
|
"""
CV_OpticalFlow demonstrates the Lucas and Kanade optical flow
algorithm built in to OpenCV.
"""
import cv2
import numpy as np
from cozmo_fsm import *
class CV_OpticalFlow(StateMachineProgram):
def __init__(self):
super().__init__(aruco=False, particle_filter=False, cam_viewer=False,
annotate_sdk = False)
def start(self):
self.feature_params = dict( maxCorners = 100,
qualityLevel = 0.3,
minDistance = 7,
blockSize = 7 )
self.lk_params = dict( winSize = (15,15),
maxLevel = 2,
criteria = (cv2.TERM_CRITERIA_EPS |
cv2.TERM_CRITERIA_COUNT,
10, 0.03) )
self.colors = np.random.randint(0, 255, (100,3), dtype=np.int)
self.prev_gray = None
self.good_new = None
self.mask = None
super().start()
cv2.namedWindow('OpticalFlow')
def user_image(self,image,gray):
cv2.waitKey(1)
if self.prev_gray is None:
self.prev_gray = gray
self.prev_feat = cv2.goodFeaturesToTrack(gray, mask=None,
**self.feature_params)
return
new_feat, st, err = \
cv2.calcOpticalFlowPyrLK(self.prev_gray, gray,
self.prev_feat, None, **self.lk_params)
if new_feat is None:
self.good_new = None
return
self.good_new = new_feat[st==1]
self.good_old = self.prev_feat[st==1]
self.prev_gray = gray
self.prev_feat = self.good_new.reshape(-1,1,2)
(x,y,_) = image.shape
image = cv2.resize(image,(y*2,x*2))
if self.mask is None:
self.mask = np.zeros_like(image)
for i,(new,old) in enumerate(zip(self.good_new, self.good_old)):
a,b = new.ravel()
c,d = old.ravel()
self.mask = cv2.line(self.mask, (a+a,b+b), (c+c,d+d),
self.colors[i].tolist(), 2)
cv2.circle(image,(a+a,b+b),5,self.colors[i].tolist(),-1)
image = cv2.add(image,self.mask)
cv2.imshow('OpticalFlow', image)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,006
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/trace.py
|
"""
Constants for defining tracing levels.
"""
class TRACE:
def __init__(self):
self._trace_level = 0
@property
def trace_level(self): return TRACE._trace_level
@trace_level.setter
def trace_level(self,val):
TRACE._trace_level = val
@property
def no_tracing(self): return 0
@property
def statenode_start(self): return 1
@property
def statenode_startstop(self): return 2
@property
def transition_fire(self): return 3
@property
def transition_startstop(self): return 4
@property
def listener_invocation(self): return 5
@property
def polling(self): return 6
@property
def await_satisfied(self): return 7
@property
def event_posted(self): return 8
@property
def task_cancel(self): return 9
TRACE = TRACE()
def tracefsm(level=None):
if level is not None:
type(TRACE).trace_level = level
else:
return TRACE.trace_level
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,007
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/pilot0.py
|
"""
To avoid circular dependencies between pilot.fsm, doorpass.fsm, and
path_planner.py, we put some pilot classes here so everyone can import
them.
"""
from .base import *
from .rrt import *
from .events import PilotEvent
class PilotCheckStart(StateNode):
"Fails if rrt planner indicates start_collides"
def start(self, event=None):
super().start(event)
(pose_x, pose_y, pose_theta) = self.robot.world.particle_filter.pose
start_node = RRTNode(x=pose_x, y=pose_y, q=pose_theta)
try:
self.robot.world.rrt.plan_path(start_node,start_node)
except StartCollides as e:
print('PilotCheckStart: Start collides!',e)
self.post_event(PilotEvent(StartCollides, args=e.args))
self.post_failure()
return
except Exception as e:
print('PilotCheckStart: Unexpected planner exception',e)
self.post_failure()
return
self.post_success()
class PilotCheckStartDetail(StateNode):
"Posts collision object if rrt planner indicates start_collides"
def start(self, event=None):
super().start(event)
(pose_x, pose_y, pose_theta) = self.robot.world.particle_filter.pose
start_node = RRTNode(x=pose_x, y=pose_y, q=pose_theta)
try:
self.robot.world.rrt.plan_path(start_node,start_node)
except StartCollides as e:
print('PilotCheckStartDetail: Start collides!',e)
self.post_event(PilotEvent(StartCollides, args=e.args))
self.post_data(e.args)
return
except Exception as e:
print('PilotCheckStartDetail: Unexpected planner exception',e)
self.post_failure()
return
self.post_success()
#---------------- Navigation Plan ----------------
class NavStep():
DRIVE = "drive"
DOORPASS = "doorpass"
BACKUP = "backup"
def __init__(self, type, param):
"""For DRIVE and BACKUP types, param is a list of RRTNode instances. The
reason we group these into a list instead of having one node per step is that
the DriveContinuous function is going to be interpolating over the entire sequence.
For a DOORPASS step the param is the door object."""
self.type = type
self.param = param
def __repr__(self):
if self.type == NavStep.DOORPASS:
pstring = self.param.id
elif self.type == NavStep.DRIVE:
psteps = [(round(node.x,1),round(node.y,1)) for node in self.param]
pstring = repr(psteps)
else: # NavStep.BACKUP and anything else
pstring = repr(self.param)
if len(pstring) > 40:
pstring = pstring[0:20] + ' ...' + pstring[-20:]
return '<NavStep %s %s>' % (self.type, pstring)
class NavPlan():
def __init__(self, steps=[]):
self.steps = steps
def __repr__(self):
steps = [(('doorpass(%s)' % s.param.id) if s.type == NavStep.DOORPASS else s.type) for s in self.steps]
return '<NavPlan %s>' % repr(steps)
def extract_path(self):
nodes = []
for step in self.steps:
if step.type in (NavStep.DRIVE, NavStep.BACKUP):
nodes += step.param
return nodes
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,008
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/evbase.py
|
"""
The Event Router and Event Listener
This file implements an event router scheme modeled after the
one in Tekkotsu.
"""
import functools
from multiprocessing import Queue
import cozmo
from .trace import TRACE
#________________ Event base class ________________
class Event:
"""Base class for all events."""
def __init__(self, source=None):
self.source = source
cozmo_evt_type = None
def generator(self,erouter,cozmo_evt): pass
def __repr__(self):
try:
src_string = self.source.name
except:
src_string = repr(self.source)
return '<%s from %s>' % (self.__class__.__name__, src_string)
#________________ Event Router ________________
class EventRouter:
"""An event router drives the state machine."""
def __init__(self):
# dispatch_table: event_class -> (source,listener)...
self.dispatch_table = dict()
# listener_registry: listener -> (event_class, source)...
self.listener_registry = dict()
# wildcard registry: true if listener is a wildcard (should run last)
self.wildcard_registry = dict()
# event generator objects
self.event_generators = dict()
# running processes
self.processes = dict() # id -> node
self.interprocess_queue = Queue()
def start(self):
self.clear()
self.poll_processes()
def clear(self):
self.dispatch_table.clear()
self.listener_registry.clear()
self.wildcard_registry.clear()
self.event_generators.clear()
self.processes.clear()
self.interprocess_queue.close()
self.interprocess_queue = Queue()
def add_listener(self, listener, event_class, source):
if not issubclass(event_class, Event):
raise TypeError('% is not an Event' % event_type)
source_dict = self.dispatch_table.get(event_class)
if source_dict is None:
source_dict = dict()
# start a cozmo event handler if this event type requires one
if event_class.cozmo_evt_type:
coztype = event_class.cozmo_evt_type
if not issubclass(coztype, cozmo.event.Event):
raise ValueError('%s cozmo_evt_type %s not a subclass of cozmo.event.Event' % (event_type, coztype))
world = self.robot.world
# supply the erouter and event type
gen = functools.partial(event_class.generator, self, event_class)
self.event_generators[event_class] = gen
world.add_event_handler(coztype,gen)
handlers = source_dict.get(source, [])
handlers.append(listener.handle_event)
source_dict[source] = handlers
self.dispatch_table[event_class] = source_dict
reg_entry = self.listener_registry.get(listener,[])
reg_entry.append((event_class,source))
self.listener_registry[listener] = reg_entry
# Transitions like =Hear('foo')=> must use None as the source
# value because they do the matching themselves instead of relying
# on the event router. So to distinguish a wildcard =Hear=>
# transition, which must be invoked last, from all the other Hear
# transitions, we must register it specially.
def add_wildcard_listener(self, listener, event_class, source):
self.add_listener(listener, event_class, source)
self.wildcard_registry[listener.handle_event] = True
def remove_listener(self, listener, event_class, source):
try:
del self.wildcard_registry[listener.handle_event]
except: pass
if not issubclass(event_class, Event):
raise TypeError('% is not an Event' % event_class)
source_dict = self.dispatch_table.get(event_class)
if source_dict is None: return
handlers = source_dict.get(source)
if handlers is None: return
try:
handlers.remove(listener.handle_event)
except: pass
if handlers == []:
del source_dict[source]
if len(source_dict) == 0: # no one listening for this event
del self.dispatch_table[event_class]
# remove the cozmo SDK event handler if there was one
if event_class.cozmo_evt_type:
coztype = event_class.cozmo_evt_type
world = self.robot.world
gen = self.event_generators[event_class]
world.remove_event_handler(coztype, gen)
del self.event_generators[event_class]
def remove_all_listener_entries(self, listener):
for event_class, source in self.listener_registry.get(listener,[]):
self.remove_listener(listener, event_class, source)
try:
del self.listener_registry[listener]
except: pass
def _get_listeners(self,event):
source_dict = self.dispatch_table.get(type(event), None)
if source_dict is None: # no listeners for this event type
return []
source_matches = source_dict.get(event.source, [])
match_handlers = []
# TapEvent can be wildcarded even though the source is never None
wildcard_matches = source_dict.get(None, []) if event.source is not None else []
wildcard_handlers = []
for handler in source_matches + wildcard_matches:
if self.wildcard_registry.get(handler,False) is True:
wildcard_handlers.append(handler)
else:
match_handlers.append(handler)
# wildcard handlers must come last in the list
return match_handlers + wildcard_handlers
def post(self,event):
if not isinstance(event,Event):
raise TypeError('%s is not an Event' % event)
listeners = self._get_listeners(event)
cnt = 0
for listener in listeners:
cnt += 1
if TRACE.trace_level >= TRACE.listener_invocation:
print('TRACE%d:' % TRACE.listener_invocation, listener.__self__, 'receiving', event)
self.robot.loop.call_soon(listener,event)
def add_process_node(self, node):
self.processes[id(node)] = node
def delete_process_node(self, node):
node_id = id(node)
if node_id in self.processes:
del self.processes[node_id]
# print('Deleted id',node_id,'for',node)
else:
print('*** ERROR in delete_process_node: node',node_id,'not in process dict!')
POLLING_INTERVAL = 0.1
def poll_processes(self):
while not self.interprocess_queue.empty():
(id,event) = self.interprocess_queue.get()
if id in self.processes:
node = self.processes[id]
event.source = node
print('Node %s returned %s' % (node,event))
self.post(event)
else:
print('*** ERROR in poll_processes: node',id,'not in process dict!', self.processes)
self.robot.loop.call_later(self.POLLING_INTERVAL, self.poll_processes)
#________________ Event Listener ________________
class EventListener:
"""Parent class for both StateNode and Transition."""
def __init__(self):
rep = object.__repr__(self)
self.name = rep[1+rep.rfind(' '):-1] # name defaults to hex address
self.running = False
if not hasattr(self,'polling_interval'):
self.polling_interval = None
self.poll_handle = None
self._robot = robot_for_loading
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.name)
def set_name(self,name):
if not isinstance(name,str):
raise ValueError('name must be a string, not %s' % name)
self.name = name
return self
def start(self):
self.running = True
if self.polling_interval:
self.poll_handle = \
self.robot.loop.call_later(self.polling_interval, self._next_poll)
else:
self.poll_handle = None
def stop(self):
if not self.running: return
self.running = False
if self.poll_handle: self.poll_handle.cancel()
self.robot.erouter.remove_all_listener_entries(self)
def handle_event(self, event):
pass
def set_polling_interval(self,interval):
if isinstance(interval, (int,float)):
self.polling_interval = interval
else:
raise TypeError('interval must be a number')
def _next_poll(self):
"""Called to schedule the next polling interval and then poll the node."""
# Schedule the next poll first because self.poll may cancel it.
if self.running and self.polling_interval:
self.poll_handle = \
self.robot.loop.call_later(self.polling_interval, self._next_poll)
self.poll()
def poll(self):
"""Dummy polling function in case sublass neglects to supply one."""
if TRACE.trace_level >= TRACE.polling:
print('TRACE%d: polling' % TRACE.polling, self)
print('%s has no poll() method' % self)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,009
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/perched.py
|
from numpy import matrix, array, ndarray, sqrt, arctan2, pi
import threading
from time import sleep
from .geometry import wrap_angle
try:
import cv2
import cv2.aruco as aruco
except: pass
# Known camera parameters
# Microsoft HD ( Calibrated to death )
microsoft_HD_webcam_cameraMatrix = matrix([[1148.00, -3, 641.0],
[0.000000, 1145.0, 371.0],
[0.000000, 0.000000, 1.000000]])
microsoft_HD_webcam_distCoeffs = array([0.211679, -0.179776, 0.041896, 0.040334, 0.000000])
class Cam():
def __init__(self,cap,x,y,z,phi, theta):
self.cap = cap
self.x = x
self.y = y
self.z = z
self.phi = phi
self.theta = theta
def __repr__(self):
return '<Cam (%.2f, %.2f, %.2f)> @ %.2f' % \
(self.x, self.y, self.z,self.phi*180/pi)
class PerchedCameraThread(threading.Thread):
def __init__(self, robot):
threading.Thread.__init__(self)
self.robot = robot
self.use_perched_cameras = False
self.perched_cameras = []
# Set camera parameters. (Current code assumes same parameters for all cameras connected to a computer.)
self.cameraMatrix = microsoft_HD_webcam_cameraMatrix
self.distCoeffs = microsoft_HD_webcam_distCoeffs
self.aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_250)
self.parameters = aruco.DetectorParameters_create()
# camera landmarks from local cameras
self.cameras = {}
# camera landamrks from network (sent from server)
self.camera_pool = {}
def run(self):
while(True):
if self.use_perched_cameras:
self.process_image()
# Computer overloaded if not given break
sleep(0.01)
else:
break
def start_perched_camera_thread(self,cameras=[]):
if not isinstance(cameras,list):
cameras = [cameras]
if self.robot.aruco_id == -1:
self.robot.aruco_id = int(input("Please enter the aruco id of the robot:"))
self.robot.world.server.camera_landmark_pool[self.robot.aruco_id]={}
self.use_perched_cameras=True
self.perched_cameras = []
for x in cameras:
cap = cv2.VideoCapture(x)
if cap.isOpened():
self.perched_cameras.append(cap)
else:
raise RuntimeError("Could not open camera %s." % repr(x))
for cap in self.perched_cameras:
# hack to set highest resolution
cap.set(3,4000)
cap.set(4,4000)
self.robot.world.particle_filter.sensor_model.use_perched_cameras = True
print("Particle filter now using perched cameras")
self.start()
def stop_perched_camera_thread(self):
self.use_perched_cameras=False
sleep(1)
for cap in self.perched_cameras:
cap.release()
self.robot.world.particle_filter.sensor_model.use_perched_cameras = False
print("Particle filter stopped using perched cameras")
def check_camera(self,camera):
cap = cv2.VideoCapture(camera)
for j in range(10):
# hack to clear buffer
for i in range(5):
cap.grab()
ret, frame = cap.read()
if not ret:
print('Failed to get camera frame from camera %s.' % camera )
return
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, self.aruco_dict, parameters=self.parameters)
gray = cv2.aruco.drawDetectedMarkers(gray, corners, ids)
cv2.imshow("Camera:"+str(camera),gray)
cv2.waitKey(1)
cap.release()
cv2.destroyAllWindows()
def rotationMatrixToEulerAngles(self, R) :
sy = sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
singular = sy < 1e-6
if not singular :
x = arctan2(R[2,1] , R[2,2])
y = arctan2(-R[2,0], sy)
z = arctan2(R[1,0], R[0,0])
else :
x = arctan2(-R[1,2], R[1,1])
y = arctan2(-R[2,0], sy)
z = 0
return array([x, y, z])
def process_image(self):
# Dict with key: aruco id with values as cameras that can see the marker
self.temp_cams = {} # Necessary, else self.cameras is empty most of the time
for cap in self.perched_cameras:
# Clearing Buffer by grabbing five frames
for i in range(5):
cap.grab()
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
corners, ids, rejectedImgPoints = aruco.detectMarkers(gray, self.aruco_dict, parameters=self.parameters)
if type(ids) is ndarray:
vecs = aruco.estimatePoseSingleMarkers(corners, 50, self.cameraMatrix, self.distCoeffs)
rvecs, tvecs = vecs[0], vecs[1]
for i in range(len(ids)):
rotationm, jcob = cv2.Rodrigues(rvecs[i])
# transform to robot coordinate frame
transformed = matrix(rotationm).T*(-matrix(tvecs[i]).T)
phi = self.rotationMatrixToEulerAngles(rotationm.T)
if ids[i][0] in self.temp_cams:
self.temp_cams[ids[i][0]][str(cap)]=Cam(str(cap),transformed[0][0,0],
transformed[1][0,0],transformed[2][0,0],wrap_angle(phi[2]-pi/2), wrap_angle(phi[0]+pi/2))
else:
self.temp_cams[ids[i][0]]={str(cap):Cam(str(cap),transformed[0][0,0],
transformed[1][0,0],transformed[2][0,0],wrap_angle(phi[2]-pi/2), wrap_angle(phi[0]+pi/2))}
self.cameras = self.temp_cams
# Only server clears the pool
if self.robot.world.is_server:
self.camera_pool = self.temp_cams
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,010
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/pickup.py
|
from cozmo.util import Pose
from cozmo.objects import LightCube
from .nodes import *
from .transitions import *
from .geometry import wrap_angle, line_equation, line_intersection
from .geometry import ORIENTATION_UPRIGHT, ORIENTATION_INVERTED, ORIENTATION_SIDEWAYS, ORIENTATION_TILTED
from .geometry import get_orientation_state, same_orientation, get_pattern_number
from .cozmo_kin import center_of_rotation_offset
from .pilot import PilotToPose, PilotCheckStart, ParentPilotEvent, InvalidPose, PilotFrustration
from .rrt import StartCollides, GoalCollides, MaxIterations
from .worldmap import LightCubeObj
from math import sin, cos, atan2, pi, sqrt
import copy
class GoToCube(StateNode):
def __init__(self, cube=None):
self.object = cube
super().__init__()
self.side_index = 0
self.try_number = 0
self.try_max = 3
self.roll_cube = False
self.roll_target = None
def start(self, event=None):
# self.object will normally be set up by the parent of this node
if isinstance(self.object, LightCube):
self.wmobject = self.object.wm_obj
elif isinstance(self.object, LightCubeObj):
self.wmobject = self.object
self.object = self.object.sdk_obj
else:
raise ValueError(self.object)
self.children['looker'].object = self.object
self.sides = []
self.side = None
self.side_index = 0
self.try_number = 0
self.try_max = 3
super().start(event)
if self.wmobject.pose_confidence < 0:
print('GoToCube: cube has invalid pose!', self.wmobject, self.object.pose)
self.post_event(PilotEvent(InvalidPose))
self.post_failure()
def pick_side(self, offset, use_world_map):
# If use_world_map is True, use the LightCubeObj pose.
# If False, use the LightCube's pose as determined by vision.
cube = self.object
if use_world_map:
wmobj = self.object.wm_obj
x = wmobj.x
y = wmobj.y
ang = wmobj.theta
orientation = wmobj.orientation
print('Pick side from', self.object.wm_obj)
else:
x = cube.pose.position.x
y = cube.pose.position.y
orientation, _, _, z = get_orientation_state(cube.pose.rotation.q0_q1_q2_q3)
if orientation == ORIENTATION_SIDEWAYS:
ang = wrap_angle(z)
else:
ang = cube.pose.rotation.angle_z.radians
(rx, ry, rtheta) = self.get_robot_cor(use_world_map=use_world_map)
dist = LightCubeObj.light_cube_size[0]/2 + offset
sideTop = [ (x + cos(ang)*dist), (y + sin(ang)*dist), wrap_angle(ang + pi) ]
sideBottom = [ (x - cos(ang)*dist), (y - sin(ang)*dist), wrap_angle(ang) ]
sideA = [ (x + sin(ang)*dist), (y - cos(ang)*dist), wrap_angle(ang + pi/2) ]
sideB = [ (x - sin(ang)*dist), (y + cos(ang)*dist), wrap_angle(ang - pi/2) ]
sides = (sideTop, sideBottom, sideA, sideB)
if orientation == ORIENTATION_SIDEWAYS:
if self.roll_cube:
# if the orientation is sideways, only two valid sides to roll cube to upright/inverted
if self.roll_target == ORIENTATION_UPRIGHT or self.roll_target == ORIENTATION_INVERTED:
self.try_max = 1
sorted_sides = (sideBottom, sideTop) if self.roll_target == ORIENTATION_UPRIGHT else (sideTop, sideBottom)
else:
sides_vertical = sorted((sideTop, sideBottom), key=lambda pt: ((pt[0]-rx)**2 + (pt[1]-ry)**2))
sides_horizontal = sorted((sideA, sideB), key=lambda pt: ((pt[0]-rx)**2 + (pt[1]-ry)**2))
sorted_sides = sides_vertical + sides_horizontal
else:
# if the orientation is sideways, only one valid side to pickup cube
self.try_max = 0
side = sideBottom
d = sqrt((side[0]-rx)**2 + (side[1]-ry)**2)
print(' side 0: %5.1f mm %5.1f , %5.1f @ %5.1f deg.' %
(d, side[0], side[1], side[2]*180/pi))
return side
else:
sorted_sides = sorted(sides, key=lambda pt: ((pt[0]-rx)**2 + (pt[1]-ry)**2))
for i in range(len(sorted_sides)):
side = sorted_sides[i]
d = sqrt((side[0]-rx)**2 + (side[1]-ry)**2)
print(' side %d: %5.1f mm %5.1f , %5.1f @ %5.1f deg.' %
(i, d, side[0], side[1], side[2]*180/pi))
print('Go to side %i' % self.side_index)
return sorted_sides[self.side_index]
def pick_another_side(self):
if self.try_number >= self.try_max:
# Have tried all sides, reset counter
print('Have tried all sides.')
self.try_number = 0
self.side_index = 0
self.try_max = 3
return False
else:
self.try_number += 1
self.side_index += 1
print('Haven\'t tried out all sides of cube. Going to try the side', self.side_index)
return True
def get_robot_pose(self, use_world_map):
if use_world_map:
rx = self.robot.world.particle_filter.pose[0]
ry = self.robot.world.particle_filter.pose[1]
rtheta = self.robot.world.particle_filter.pose[2]
else:
rx = self.robot.pose.position.x
ry = self.robot.pose.position.y
rtheta = self.robot.pose.rotation.angle_z.radians
return (rx, ry, rtheta)
def get_robot_cor(self, use_world_map):
"Get robot center of rotation and current heading"
(rx, ry, rtheta) = self.get_robot_pose(use_world_map=use_world_map)
cx = rx + center_of_rotation_offset*cos(rtheta)
cy = ry + center_of_rotation_offset*sin(rtheta)
return (cx, cy, rtheta)
def get_robot_line(self, use_world_map):
(rx, ry, rtheta) = self.get_robot_pose(use_world_map)
(cx, cy, ctheta) = self.get_robot_cor(use_world_map)
return line_equation((rx,ry), (cx,cy))
def get_cube_line(self, use_world_map):
if use_world_map:
ox = self.parent.wmobject.x
oy = self.parent.wmobject.y
else:
ox = self.parent.object.pose.position.x
oy = self.parent.object.pose.position.y
(sx, sy, stheta) = self.side
return line_equation((ox,oy), (sx,sy))
def measure_dockedness(self, side, use_world_map):
"""Returns distance and relative angle to specified docking pose."""
(rx, ry, rtheta) = self.get_robot_cor(use_world_map)
(ox, oy, otheta) = side
dist = sqrt((rx-ox)**2 + (ry-oy)**2)
relative_angle = abs(wrap_angle(rtheta-otheta) % (pi/2)) * (180/pi)
return (dist, relative_angle)
class PilotToSide(PilotToPose):
def __init__(self):
super().__init__(None, verbose=True)
def start(self, event=None):
cube = self.parent.object
(x, y, theta) = self.parent.pick_side(100, use_world_map=True)
self.target_pose = Pose(x, y, self.robot.pose.position.z,
angle_z=Angle(radians=wrap_angle(theta)))
(px,py,pq) = self.robot.world.particle_filter.pose
print('PilotToSide: planned path from (%.1f, %.1f) @ %.1f deg. to pickup point (%.1f, %.1f) @ %.1f deg.' %
(px, py, pq*180/pi,
self.target_pose.position.x, self.target_pose.position.y,
self.target_pose.rotation.angle_z.degrees))
super().start(event)
class ReportPosition(StateNode):
def __init__(self,id=None):
super().__init__()
self.id_string = id + ': ' if id else ''
def start(self,event=None):
super().start(event)
cube = self.parent.object
vis = 'visible' if cube.is_visible else 'not visible'
cx = cube.pose.position.x
cy = cube.pose.position.y
rx = self.robot.pose.position.x
ry = self.robot.pose.position.y
dx = cx - rx
dy = cy - ry
dist = sqrt(dx*dx + dy*dy)
bearing = wrap_angle(atan2(dy,dx) - self.robot.pose.rotation.angle_z.radians) * 180/pi
print('%scube %s at (%5.1f,%5.1f) robot at (%5.1f,%5.1f) dist=%5.1f rel. brg=%5.1f' %
(self.id_string, vis, cx, cy, rx, ry, dist, bearing))
class TurnToCube(Turn):
def __init__(self, check_vis=False):
self.check_vis = check_vis
super().__init__()
def start(self, event=None):
if self.running: return
cube = self.parent.object
if self.check_vis and not cube.is_visible:
print('** TurnToCube %s could not see the cube.' % self.name)
self.angle = None
super().start(event)
self.post_failure()
print('TurnToCube %s posted failure' % self.name)
else:
(sx, sy, _) = self.parent.pick_side(0, use_world_map=False)
(cx, cy, ctheta) = self.parent.get_robot_cor(False)
dx = sx - cx
dy = sy - cy
dist = sqrt(dx*dx + dy*dy)
self.angle = Angle(degrees = wrap_angle(atan2(dy,dx) - ctheta) * 180/pi)
if abs(self.angle.degrees) <= 2:
self.angle = degrees(0)
if abs(self.angle.degrees) > 60:
print('********>> BIG TURN in',self)
print('TurnToCube %s: cube at (%5.1f,%5.1f) robot cor at (%5.1f,%5.1f) dist=%5.1f turn angle=%5.1f' %
(self.name, sx, sy, cx, cy, dist, self.angle.degrees))
super().start(event)
class CheckAlmostDocked(StateNode):
# *** TODO: convert to iterate through all feasible sides
def start(self, event=None):
if self.running: return
super().start(event)
cube = self.parent.object
side = self.parent.pick_side(0, use_world_map=True)
self.parent.side = side
(dist, relative_angle) = self.parent.measure_dockedness(side,True)
max_distance_from_dock_point = 150 # millimeters
max_angle_from_dock_heading = 10 # degrees
max_angle_for_sideways = 135 # degrees
if isinstance(cube, LightCube):
orientation = cube.wm_obj.orientation
elif isinstance(cube, LightCubeObj):
orientation = cube.sdk_obj.orientation
# Re-calculate relative_angle for sideways cube
if orientation == ORIENTATION_SIDEWAYS:
(rx, ry, rtheta) = self.parent.get_robot_cor(True)
ctheta = side[2]
dtheta = (rtheta - ctheta) if (rtheta>ctheta) else (ctheta-rtheta)
relative_angle = abs(dtheta/pi*180)
# print('robot: %.1f deg; cube: %.1f deg; delta: %.1f deg.' %(rtheta/pi*180, ctheta/pi*180, relative_angle))
if dist < max_distance_from_dock_point:
if relative_angle < max_angle_from_dock_heading and cube.is_visible:
print('CheckAlmostDocked is satisfied. dist=%.1f mm angle=%.1f deg.' %
(dist, relative_angle))
self.post_completion()
else:
if orientation == ORIENTATION_SIDEWAYS:
if relative_angle < max_angle_for_sideways and cube.is_visible:
print('CheckAlmostDocked: bad angle. (dist=%.1f mm) angle=%.1f deg.' %
(dist, relative_angle))
self.post_success()
else:
print('CheckAlmostDocked: use the Pilot to path plan. orientation=%s. dist=%.1f mm. angle=%.1f deg.' %
(orientation, dist, relative_angle))
self.post_failure()
elif not cube.is_visible:
print('CheckAlmostDocked: cube not visible')
self.post_success()
else:
print('CheckAlmostDocked: bad angle. (dist=%.1f mm) angle=%.1f deg.' %
(dist, relative_angle))
self.post_success()
else:
print('CheckAlmostDocked: too far away. dist=%.1f mm. (angle=%.1f deg.)' %
(dist, relative_angle))
self.post_failure()
class ForwardToCube(Forward):
def __init__(self, offset):
self.offset = offset
super().__init__()
def start(self, event=None):
if self.running: return
cube = self.parent.object
dx = cube.pose.position.x - self.robot.pose.position.x
dy = cube.pose.position.y - self.robot.pose.position.y
dist = sqrt(dx*dx + dy*dy) - self.offset
if (dist < 0):
print('***** ForwardToCube %s negative distance: %.1f mm' % (self.name,dist))
self.distance = Distance(dist)
print('ForwardToCube %s: distance %.1f mm' % (self.name, self.distance.distance_mm))
super().start(event)
class ManualDock1(Forward):
def report(self,rx,ry,rtheta,sx,sy,stheta,intx,inty,int_brg):
print('ManualDock1: robot cor at %.1f , %.1f @ %.1f deg. side at %.1f , %.1f @ %.1f deg.' %
(rx, ry, 180*rtheta/pi, sx, sy, stheta*180/pi))
print(' int at %.1f , %.1f bearing=%.1f deg. dist=%.1f mm ' %
(intx,inty,int_brg*180/pi,self.distance.distance_mm))
def start(self,event=None):
rline = self.parent.get_robot_line(use_world_map=True)
cline = self.parent.get_cube_line(use_world_map=True)
(intx, inty) = line_intersection(rline, cline)
(rx, ry,rtheta) = self.parent.get_robot_cor(use_world_map=True)
# Is intersection point ahead of or behind us?
intersection_bearing = wrap_angle(atan2(inty-ry, intx-rx)-rtheta)
(sx, sy, stheta) = self.parent.side
if abs(intersection_bearing) > pi/2: # Intersection is behind us
print('ManualDock1: Intersection is behind us.')
dist = min(75, sqrt((rx-intx)**2 + (ry-inty)**2))
self.distance = distance_mm(-dist)
self.report(rx,ry,rtheta,sx,sy,stheta,intx,inty,intersection_bearing)
super().start(event)
return
else: # Intersection is ahead of us
dx = sx - intx
dy = sy - inty
dtheta = abs(wrap_angle(atan2(dy,dx) - stheta))
dist_to_side = sqrt(dx**2 + dy**2)
min_dist_to_side = 60 # mm from cor
max_dist_to_side = 120 # mm from cor
print('ManualDock1: Intersection ahead is %.1f mm from side and dtheta=%.1f deg.' %
(dist_to_side, dtheta*180/pi))
alignment_threshold = 5 # degrees
aligned = abs(wrap_angle(rtheta-stheta)) < alignment_threshold*pi/180
if ((dist_to_side >= min_dist_to_side) or aligned) and \
(dist_to_side <= max_dist_to_side) and \
(dtheta < pi/20): # make sure intersection is on near side of cube
# Intersection ahead is at an acceptable distance from the chosen side
print('ManualDock1: move forward to intersection.')
self.distance = distance_mm(sqrt((rx-intx)**2 + (ry-inty)**2))
self.report(rx,ry,rtheta,sx,sy,stheta,intx,inty,intersection_bearing)
super().start(event)
return
else:
# Intersection ahead is past the target, or too close or too far from it, so
# pick a new point on cline at a reasonable distance and turn to that
print('ManualDock: pick new intersection point')
good_dist = 70 # mmm from cor
tx = sx + good_dist * cos(stheta+pi)
ty = sy + good_dist * sin(stheta+pi)
turn_angle = wrap_angle(atan2(ty-ry,tx-rx)-rtheta)
min_turn_angle = 2 * pi/180
if abs(turn_angle) > min_turn_angle:
self.distance = distance_mm(0)
self.report(rx,ry,rtheta,sx,sy,stheta,intx,inty,intersection_bearing)
print('ManualDock1: turn to point at %.1f , %.1f turn_angle=%.1f deg.' %
(tx, ty, turn_angle*180/pi))
super().start(event)
self.post_data(Angle(radians=turn_angle))
return
else:
dist = sqrt((rx-tx)**2 + (ry-ty)**2)
self.distance = distance_mm(dist)
self.report(rx,ry,rtheta,sx,sy,stheta,intx,inty,intersection_bearing)
print('ManualDock1: Alignment is close enough.')
super().start(event)
return
class ManualDock2(Turn):
def start(self,event=None):
(rx,ry,rtheta) = self.parent.get_robot_cor(use_world_map=True)
(ox,oy,otheta) = self.parent.side
#bearing = atan2(oy-ry, ox-rx)
#turn_angle = wrap_angle(bearing-rtheta)
turn_angle = wrap_angle(otheta-rtheta)
self.angle = Angle(radians=turn_angle)
print('ManualDock2: otheta=%.1f deg. heading=%.1f deg turn_angle=%.1f deg.' %
(otheta*180/pi, rtheta*180/pi, turn_angle*180/pi))
super().start(event)
class InvalidatePose(StateNode):
def start(self,event=None):
super().start(event)
self.parent.wmobject.pose_confidence = -1
class ChooseAnotherSide(StateNode):
def __init__(self):
super().__init__()
def start(self, event=None):
super().start(event)
if self.parent.pick_another_side():
self.post_success()
else:
self.post_failure()
class CheckCubePoseValid(StateNode):
def __init__(self):
super().__init__()
def start(self, event=None):
super().start(event)
if isinstance(self.parent.object, LightCube):
cube_id = self.parent.object.wm_obj.id
elif isinstance(self.parent.object, LightCubeObj):
cube_id = self.parent.object.id
else:
raise ValueError(self.parent.object)
try:
wmobject = self.robot.world.world_map.objects[cube_id]
except: # worldmap was cleared just before we were called
self.post_failure()
return
if self.parent.robot.is_picked_up:
self.parent.robot.stop_all_motors()
print('CheckCubePoseValid: robot is picked up.')
self.post_failure()
elif wmobject.pose_confidence < 0:
print('CheckCubePoseValid %s: %s has invalid pose!' % (self.name, cube_id))
self.post_failure()
else:
#print('CheckCubePoseValid %s: valid pose for %s.' % (self.name, cube_id))
self.post_completion()
class ReadyToRoll(StateNode):
def __init__(self):
super().__init__()
def start(self, event=None):
super().start(event)
if self.parent.roll_cube:
print('get ready to roll')
self.post_success()
else:
self.post_failure()
def setup(self):
# # GoToCube machine
#
# droplift: SetLiftHeight(0)
# droplift =C=> after_drop
# droplift =F=> after_drop
#
# after_drop: StateNode() =N=> {looker, waitlift, monitor_cube_pose}
#
# looker: LookAtObject()
#
# waitlift: StateNode() =T(1)=> # allow time for vision to set up world map
# check_almost_docked
#
# monitor_cube_pose: self.CheckCubePoseValid()
# monitor_cube_pose =C=> StateNode() =T(1)=> monitor_cube_pose
# monitor_cube_pose =F=> ParentFails()
#
# check_almost_docked: self.CheckAlmostDocked() # sets up parent.side
# check_almost_docked =C=> turn_to_cube2 # we're good to dock right now
# check_almost_docked =S=> setup_manual_dock # we're close: skip the Pilot and set up dock manually
# check_almost_docked =F=> pilot_check_start # not close: use the Pilot to path plan
#
# setup_manual_dock: Forward(-10)
# setup_manual_dock =C=> manual_dock1
# setup_manual_dock =F=> failure
#
# manual_dock1: self.ManualDock1()
# manual_dock1 =D=> Turn() =C=> Print('turned. wait...') =N=> manual_dock1
# manual_dock1 =C=> Print('wait...') =N=> manual_dock2
# manual_dock1 =T(10)=> Print('Cannot manual dock from here') =N=> pilot_check_start # temporary
#
# manual_dock2: self.ManualDock2()
# manual_dock2 =C=> Print('wait...') =N=> turn_to_cube1
# manual_dock2 =F=> failure
#
# pilot_check_start: PilotCheckStart()
# pilot_check_start =S=> Print('Start collision check passed.') =N=> go_side
# # TODO: instead of blindly backing up, find the best direction to move.
# pilot_check_start =F=> Print('Backing up to escape start collision...') =N=> backup_for_escape
#
# backup_for_escape: Forward(-80)
# backup_for_escape =C=> pilot_check_start2
# backup_for_escape =F=> failure
#
# # Second chance to avoid StartCollides. There is no third chance.
# pilot_check_start2: PilotCheckStart()
# pilot_check_start2 =S=> Print('Start collision re-check passed.') =N=> go_side
# pilot_check_start2 =PILOT(StartCollides)=> check_start2_pilot: ParentPilotEvent() =N=> failure
# pilot_check_start2 =F=> failure
#
# go_side: self.PilotToSide()
# go_side =PILOT(GoalCollides)=> failure
# go_side =PILOT(MaxIterations)=> failure
# go_side =PILOT=> go_side_pilot: ParentPilotEvent() =N=> failure
# go_side =F=> failure
# go_side =C=> self.ReportPosition('go_side_deccel')
# =T(0.75)=> self.ReportPosition('go_side_stopped')
# =N=> turn_to_cube1
#
# turn_to_cube1: self.TurnToCube(check_vis=True) =C=>
# self.ReportPosition('turn_to_cube1_deccel')
# =T(0.75)=> self.ReportPosition('turn_to_cube1_stopped')
# =N=> Print('wait to approach...') =N=> approach
# turn_to_cube1 =F=> recover1
#
# recover1: Forward(-50)
# recover1 =C=> turn_to_cube2
# recover1 =F=> failure
#
# approach: self.ForwardToCube(60) =C=> StateNode() =T(0.75)=>
# self.ReportPosition('approach') =T(0.75)=>
# self.ReportPosition('approach') =N=> turn_to_cube_1a
#
# turn_to_cube_1a: self.TurnToCube(check_vis=False) =C=> Print('wait...') =N=> exit_to_roll
# turn_to_cube_1a =F=> failure
#
# approach =F=> failure
#
# exit_to_roll: self.ReadyToRoll()
# exit_to_roll =F=> forward_to_cube_1a
# exit_to_roll =S=> Forward(-5) =C=> SetLiftHeight(1) =C=> forward_to_cube_1a
#
# forward_to_cube_1a: self.ForwardToCube(15) =C=> success
#
# turn_to_cube2: self.TurnToCube(check_vis=True)
# turn_to_cube2 =F=> Print("TurnToCube2: Cube Lost") =N=> self.InvalidatePose() =N=> failure
# turn_to_cube2 =C=> forward_to_cube2
#
# forward_to_cube2: self.ForwardToCube(60)
# forward_to_cube2 =C=> turn_to_cube3
# forward_to_cube2 =F=> failure
#
# turn_to_cube3: self.TurnToCube(check_vis=False) # can't fail
# turn_to_cube3 =C=> exit_to_roll2
# turn_to_cube3 =F=> failure
#
# exit_to_roll2: self.ReadyToRoll()
# exit_to_roll2 =F=> forward_to_cube3
# exit_to_roll2 =S=> Forward(-5) =C=> SetLiftHeight(1) =C=> forward_to_cube3
#
# forward_to_cube3: self.ForwardToCube(20) =C=> success
#
# success: Print('GoToSide has succeeded.') =N=> ParentCompletes()
#
# failure: Print('GoToSide has failed.') =N=> check_cube_pose
#
# check_cube_pose: self.CheckCubePoseValid()
# check_cube_pose =C=> choose_another_side
# check_cube_pose =F=> ParentFails()
#
# choose_another_side: self.ChooseAnotherSide()
# choose_another_side =F=> ParentFails()
# choose_another_side =S=> droplift
# Code generated by genfsm on Sat Feb 25 01:50:19 2023:
droplift = SetLiftHeight(0) .set_name("droplift") .set_parent(self)
after_drop = StateNode() .set_name("after_drop") .set_parent(self)
looker = LookAtObject() .set_name("looker") .set_parent(self)
waitlift = StateNode() .set_name("waitlift") .set_parent(self)
monitor_cube_pose = self.CheckCubePoseValid() .set_name("monitor_cube_pose") .set_parent(self)
statenode1 = StateNode() .set_name("statenode1") .set_parent(self)
parentfails1 = ParentFails() .set_name("parentfails1") .set_parent(self)
check_almost_docked = self.CheckAlmostDocked() .set_name("check_almost_docked") .set_parent(self)
setup_manual_dock = Forward(-10) .set_name("setup_manual_dock") .set_parent(self)
manual_dock1 = self.ManualDock1() .set_name("manual_dock1") .set_parent(self)
turn1 = Turn() .set_name("turn1") .set_parent(self)
print1 = Print('turned. wait...') .set_name("print1") .set_parent(self)
print2 = Print('wait...') .set_name("print2") .set_parent(self)
print3 = Print('Cannot manual dock from here') .set_name("print3") .set_parent(self)
manual_dock2 = self.ManualDock2() .set_name("manual_dock2") .set_parent(self)
print4 = Print('wait...') .set_name("print4") .set_parent(self)
pilot_check_start = PilotCheckStart() .set_name("pilot_check_start") .set_parent(self)
print5 = Print('Start collision check passed.') .set_name("print5") .set_parent(self)
print6 = Print('Backing up to escape start collision...') .set_name("print6") .set_parent(self)
backup_for_escape = Forward(-80) .set_name("backup_for_escape") .set_parent(self)
pilot_check_start2 = PilotCheckStart() .set_name("pilot_check_start2") .set_parent(self)
print7 = Print('Start collision re-check passed.') .set_name("print7") .set_parent(self)
check_start2_pilot = ParentPilotEvent() .set_name("check_start2_pilot") .set_parent(self)
go_side = self.PilotToSide() .set_name("go_side") .set_parent(self)
go_side_pilot = ParentPilotEvent() .set_name("go_side_pilot") .set_parent(self)
reportposition1 = self.ReportPosition('go_side_deccel') .set_name("reportposition1") .set_parent(self)
reportposition2 = self.ReportPosition('go_side_stopped') .set_name("reportposition2") .set_parent(self)
turn_to_cube1 = self.TurnToCube(check_vis=True) .set_name("turn_to_cube1") .set_parent(self)
reportposition3 = self.ReportPosition('turn_to_cube1_deccel') .set_name("reportposition3") .set_parent(self)
reportposition4 = self.ReportPosition('turn_to_cube1_stopped') .set_name("reportposition4") .set_parent(self)
print8 = Print('wait to approach...') .set_name("print8") .set_parent(self)
recover1 = Forward(-50) .set_name("recover1") .set_parent(self)
approach = self.ForwardToCube(60) .set_name("approach") .set_parent(self)
statenode2 = StateNode() .set_name("statenode2") .set_parent(self)
reportposition5 = self.ReportPosition('approach') .set_name("reportposition5") .set_parent(self)
reportposition6 = self.ReportPosition('approach') .set_name("reportposition6") .set_parent(self)
turn_to_cube_1a = self.TurnToCube(check_vis=False) .set_name("turn_to_cube_1a") .set_parent(self)
print9 = Print('wait...') .set_name("print9") .set_parent(self)
exit_to_roll = self.ReadyToRoll() .set_name("exit_to_roll") .set_parent(self)
forward1 = Forward(-5) .set_name("forward1") .set_parent(self)
setliftheight1 = SetLiftHeight(1) .set_name("setliftheight1") .set_parent(self)
forward_to_cube_1a = self.ForwardToCube(15) .set_name("forward_to_cube_1a") .set_parent(self)
turn_to_cube2 = self.TurnToCube(check_vis=True) .set_name("turn_to_cube2") .set_parent(self)
print10 = Print("TurnToCube2: Cube Lost") .set_name("print10") .set_parent(self)
invalidatepose1 = self.InvalidatePose() .set_name("invalidatepose1") .set_parent(self)
forward_to_cube2 = self.ForwardToCube(60) .set_name("forward_to_cube2") .set_parent(self)
turn_to_cube3 = self.TurnToCube(check_vis=False) .set_name("turn_to_cube3") .set_parent(self)
exit_to_roll2 = self.ReadyToRoll() .set_name("exit_to_roll2") .set_parent(self)
forward2 = Forward(-5) .set_name("forward2") .set_parent(self)
setliftheight2 = SetLiftHeight(1) .set_name("setliftheight2") .set_parent(self)
forward_to_cube3 = self.ForwardToCube(20) .set_name("forward_to_cube3") .set_parent(self)
success = Print('GoToSide has succeeded.') .set_name("success") .set_parent(self)
parentcompletes1 = ParentCompletes() .set_name("parentcompletes1") .set_parent(self)
failure = Print('GoToSide has failed.') .set_name("failure") .set_parent(self)
check_cube_pose = self.CheckCubePoseValid() .set_name("check_cube_pose") .set_parent(self)
parentfails2 = ParentFails() .set_name("parentfails2") .set_parent(self)
choose_another_side = self.ChooseAnotherSide() .set_name("choose_another_side") .set_parent(self)
parentfails3 = ParentFails() .set_name("parentfails3") .set_parent(self)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(droplift) .add_destinations(after_drop)
failuretrans1 = FailureTrans() .set_name("failuretrans1")
failuretrans1 .add_sources(droplift) .add_destinations(after_drop)
nulltrans1 = NullTrans() .set_name("nulltrans1")
nulltrans1 .add_sources(after_drop) .add_destinations(looker,waitlift,monitor_cube_pose)
timertrans1 = TimerTrans(1) .set_name("timertrans1")
timertrans1 .add_sources(waitlift) .add_destinations(check_almost_docked)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(monitor_cube_pose) .add_destinations(statenode1)
timertrans2 = TimerTrans(1) .set_name("timertrans2")
timertrans2 .add_sources(statenode1) .add_destinations(monitor_cube_pose)
failuretrans2 = FailureTrans() .set_name("failuretrans2")
failuretrans2 .add_sources(monitor_cube_pose) .add_destinations(parentfails1)
completiontrans3 = CompletionTrans() .set_name("completiontrans3")
completiontrans3 .add_sources(check_almost_docked) .add_destinations(turn_to_cube2)
successtrans1 = SuccessTrans() .set_name("successtrans1")
successtrans1 .add_sources(check_almost_docked) .add_destinations(setup_manual_dock)
failuretrans3 = FailureTrans() .set_name("failuretrans3")
failuretrans3 .add_sources(check_almost_docked) .add_destinations(pilot_check_start)
completiontrans4 = CompletionTrans() .set_name("completiontrans4")
completiontrans4 .add_sources(setup_manual_dock) .add_destinations(manual_dock1)
failuretrans4 = FailureTrans() .set_name("failuretrans4")
failuretrans4 .add_sources(setup_manual_dock) .add_destinations(failure)
datatrans1 = DataTrans() .set_name("datatrans1")
datatrans1 .add_sources(manual_dock1) .add_destinations(turn1)
completiontrans5 = CompletionTrans() .set_name("completiontrans5")
completiontrans5 .add_sources(turn1) .add_destinations(print1)
nulltrans2 = NullTrans() .set_name("nulltrans2")
nulltrans2 .add_sources(print1) .add_destinations(manual_dock1)
completiontrans6 = CompletionTrans() .set_name("completiontrans6")
completiontrans6 .add_sources(manual_dock1) .add_destinations(print2)
nulltrans3 = NullTrans() .set_name("nulltrans3")
nulltrans3 .add_sources(print2) .add_destinations(manual_dock2)
timertrans3 = TimerTrans(10) .set_name("timertrans3")
timertrans3 .add_sources(manual_dock1) .add_destinations(print3)
nulltrans4 = NullTrans() .set_name("nulltrans4")
nulltrans4 .add_sources(print3) .add_destinations(pilot_check_start)
completiontrans7 = CompletionTrans() .set_name("completiontrans7")
completiontrans7 .add_sources(manual_dock2) .add_destinations(print4)
nulltrans5 = NullTrans() .set_name("nulltrans5")
nulltrans5 .add_sources(print4) .add_destinations(turn_to_cube1)
failuretrans5 = FailureTrans() .set_name("failuretrans5")
failuretrans5 .add_sources(manual_dock2) .add_destinations(failure)
successtrans2 = SuccessTrans() .set_name("successtrans2")
successtrans2 .add_sources(pilot_check_start) .add_destinations(print5)
nulltrans6 = NullTrans() .set_name("nulltrans6")
nulltrans6 .add_sources(print5) .add_destinations(go_side)
failuretrans6 = FailureTrans() .set_name("failuretrans6")
failuretrans6 .add_sources(pilot_check_start) .add_destinations(print6)
nulltrans7 = NullTrans() .set_name("nulltrans7")
nulltrans7 .add_sources(print6) .add_destinations(backup_for_escape)
completiontrans8 = CompletionTrans() .set_name("completiontrans8")
completiontrans8 .add_sources(backup_for_escape) .add_destinations(pilot_check_start2)
failuretrans7 = FailureTrans() .set_name("failuretrans7")
failuretrans7 .add_sources(backup_for_escape) .add_destinations(failure)
successtrans3 = SuccessTrans() .set_name("successtrans3")
successtrans3 .add_sources(pilot_check_start2) .add_destinations(print7)
nulltrans8 = NullTrans() .set_name("nulltrans8")
nulltrans8 .add_sources(print7) .add_destinations(go_side)
pilottrans1 = PilotTrans(StartCollides) .set_name("pilottrans1")
pilottrans1 .add_sources(pilot_check_start2) .add_destinations(check_start2_pilot)
nulltrans9 = NullTrans() .set_name("nulltrans9")
nulltrans9 .add_sources(check_start2_pilot) .add_destinations(failure)
failuretrans8 = FailureTrans() .set_name("failuretrans8")
failuretrans8 .add_sources(pilot_check_start2) .add_destinations(failure)
pilottrans2 = PilotTrans(GoalCollides) .set_name("pilottrans2")
pilottrans2 .add_sources(go_side) .add_destinations(failure)
pilottrans3 = PilotTrans(MaxIterations) .set_name("pilottrans3")
pilottrans3 .add_sources(go_side) .add_destinations(failure)
pilottrans4 = PilotTrans() .set_name("pilottrans4")
pilottrans4 .add_sources(go_side) .add_destinations(go_side_pilot)
nulltrans10 = NullTrans() .set_name("nulltrans10")
nulltrans10 .add_sources(go_side_pilot) .add_destinations(failure)
failuretrans9 = FailureTrans() .set_name("failuretrans9")
failuretrans9 .add_sources(go_side) .add_destinations(failure)
completiontrans9 = CompletionTrans() .set_name("completiontrans9")
completiontrans9 .add_sources(go_side) .add_destinations(reportposition1)
timertrans4 = TimerTrans(0.75) .set_name("timertrans4")
timertrans4 .add_sources(reportposition1) .add_destinations(reportposition2)
nulltrans11 = NullTrans() .set_name("nulltrans11")
nulltrans11 .add_sources(reportposition2) .add_destinations(turn_to_cube1)
completiontrans10 = CompletionTrans() .set_name("completiontrans10")
completiontrans10 .add_sources(turn_to_cube1) .add_destinations(reportposition3)
timertrans5 = TimerTrans(0.75) .set_name("timertrans5")
timertrans5 .add_sources(reportposition3) .add_destinations(reportposition4)
nulltrans12 = NullTrans() .set_name("nulltrans12")
nulltrans12 .add_sources(reportposition4) .add_destinations(print8)
nulltrans13 = NullTrans() .set_name("nulltrans13")
nulltrans13 .add_sources(print8) .add_destinations(approach)
failuretrans10 = FailureTrans() .set_name("failuretrans10")
failuretrans10 .add_sources(turn_to_cube1) .add_destinations(recover1)
completiontrans11 = CompletionTrans() .set_name("completiontrans11")
completiontrans11 .add_sources(recover1) .add_destinations(turn_to_cube2)
failuretrans11 = FailureTrans() .set_name("failuretrans11")
failuretrans11 .add_sources(recover1) .add_destinations(failure)
completiontrans12 = CompletionTrans() .set_name("completiontrans12")
completiontrans12 .add_sources(approach) .add_destinations(statenode2)
timertrans6 = TimerTrans(0.75) .set_name("timertrans6")
timertrans6 .add_sources(statenode2) .add_destinations(reportposition5)
timertrans7 = TimerTrans(0.75) .set_name("timertrans7")
timertrans7 .add_sources(reportposition5) .add_destinations(reportposition6)
nulltrans14 = NullTrans() .set_name("nulltrans14")
nulltrans14 .add_sources(reportposition6) .add_destinations(turn_to_cube_1a)
completiontrans13 = CompletionTrans() .set_name("completiontrans13")
completiontrans13 .add_sources(turn_to_cube_1a) .add_destinations(print9)
nulltrans15 = NullTrans() .set_name("nulltrans15")
nulltrans15 .add_sources(print9) .add_destinations(exit_to_roll)
failuretrans12 = FailureTrans() .set_name("failuretrans12")
failuretrans12 .add_sources(turn_to_cube_1a) .add_destinations(failure)
failuretrans13 = FailureTrans() .set_name("failuretrans13")
failuretrans13 .add_sources(approach) .add_destinations(failure)
failuretrans14 = FailureTrans() .set_name("failuretrans14")
failuretrans14 .add_sources(exit_to_roll) .add_destinations(forward_to_cube_1a)
successtrans4 = SuccessTrans() .set_name("successtrans4")
successtrans4 .add_sources(exit_to_roll) .add_destinations(forward1)
completiontrans14 = CompletionTrans() .set_name("completiontrans14")
completiontrans14 .add_sources(forward1) .add_destinations(setliftheight1)
completiontrans15 = CompletionTrans() .set_name("completiontrans15")
completiontrans15 .add_sources(setliftheight1) .add_destinations(forward_to_cube_1a)
completiontrans16 = CompletionTrans() .set_name("completiontrans16")
completiontrans16 .add_sources(forward_to_cube_1a) .add_destinations(success)
failuretrans15 = FailureTrans() .set_name("failuretrans15")
failuretrans15 .add_sources(turn_to_cube2) .add_destinations(print10)
nulltrans16 = NullTrans() .set_name("nulltrans16")
nulltrans16 .add_sources(print10) .add_destinations(invalidatepose1)
nulltrans17 = NullTrans() .set_name("nulltrans17")
nulltrans17 .add_sources(invalidatepose1) .add_destinations(failure)
completiontrans17 = CompletionTrans() .set_name("completiontrans17")
completiontrans17 .add_sources(turn_to_cube2) .add_destinations(forward_to_cube2)
completiontrans18 = CompletionTrans() .set_name("completiontrans18")
completiontrans18 .add_sources(forward_to_cube2) .add_destinations(turn_to_cube3)
failuretrans16 = FailureTrans() .set_name("failuretrans16")
failuretrans16 .add_sources(forward_to_cube2) .add_destinations(failure)
completiontrans19 = CompletionTrans() .set_name("completiontrans19")
completiontrans19 .add_sources(turn_to_cube3) .add_destinations(exit_to_roll2)
failuretrans17 = FailureTrans() .set_name("failuretrans17")
failuretrans17 .add_sources(turn_to_cube3) .add_destinations(failure)
failuretrans18 = FailureTrans() .set_name("failuretrans18")
failuretrans18 .add_sources(exit_to_roll2) .add_destinations(forward_to_cube3)
successtrans5 = SuccessTrans() .set_name("successtrans5")
successtrans5 .add_sources(exit_to_roll2) .add_destinations(forward2)
completiontrans20 = CompletionTrans() .set_name("completiontrans20")
completiontrans20 .add_sources(forward2) .add_destinations(setliftheight2)
completiontrans21 = CompletionTrans() .set_name("completiontrans21")
completiontrans21 .add_sources(setliftheight2) .add_destinations(forward_to_cube3)
completiontrans22 = CompletionTrans() .set_name("completiontrans22")
completiontrans22 .add_sources(forward_to_cube3) .add_destinations(success)
nulltrans18 = NullTrans() .set_name("nulltrans18")
nulltrans18 .add_sources(success) .add_destinations(parentcompletes1)
nulltrans19 = NullTrans() .set_name("nulltrans19")
nulltrans19 .add_sources(failure) .add_destinations(check_cube_pose)
completiontrans23 = CompletionTrans() .set_name("completiontrans23")
completiontrans23 .add_sources(check_cube_pose) .add_destinations(choose_another_side)
failuretrans19 = FailureTrans() .set_name("failuretrans19")
failuretrans19 .add_sources(check_cube_pose) .add_destinations(parentfails2)
failuretrans20 = FailureTrans() .set_name("failuretrans20")
failuretrans20 .add_sources(choose_another_side) .add_destinations(parentfails3)
successtrans6 = SuccessTrans() .set_name("successtrans6")
successtrans6 .add_sources(choose_another_side) .add_destinations(droplift)
return self
class SetCarrying(StateNode):
def __init__(self,objparam=None):
self.objparam = objparam
self.object = None
super().__init__()
def start(self, event=None):
if self.objparam is not None:
self.object = self.objparam
else:
self.object = self.parent.object
if isinstance(self.object, LightCube):
self.wmobject = self.object.wm_obj
elif isinstance(self.object, LightCubeObj):
self.wmobject = self.object
self.object = self.object.sdk_obj
else:
raise ValueError(self.object)
self.robot.carrying = self.wmobject
self.robot.fetching = None
self.wmobject.update_from_sdk = False
self.wmobject.pose_confidence = +1
super().start(event)
self.post_completion()
class SetNotCarrying(StateNode):
def start(self,event=None):
self.robot.carrying = None
self.robot.fetching = None
super().start(event)
self.post_completion()
class CheckCarrying(StateNode):
def start(self, event=None):
super().start(event)
if self.robot.carrying:
self.post_success()
else:
self.post_failure()
class SetFetching(StateNode):
"Prevents pose invalidation if we bump the cube while trying to pick it up."
def __init__(self,objparam=None):
self.objparam = objparam
self.object = None
super().__init__()
def start(self, event=None):
super().start(event)
if self.objparam is not None:
self.object = self.objparam
else:
self.object = self.parent.object
if isinstance(self.object, LightCube):
try:
self.wmobject = self.object.wm_obj
except:
self.wmobject = None
elif isinstance(self.object, LightCubeObj):
self.wmobject = self.object
self.object = self.object.sdk_obj
else:
raise ValueError(self.object)
if self.wmobject:
self.robot.fetching = self.wmobject
self.post_completion()
else:
self.post_failure()
class SetNotFetching(StateNode):
def start(self,event=None):
super().start(event)
self.robot.fetching = None
self.post_completion()
class PickUpCube(StateNode):
"""Pick up a cube using our own dock and verify routines.
Set self.object to indicate the cube to be picked up."""
class VerifyPickup(StateNode):
def probe_column(self, im, col, row_start, row_end):
"""
Probe one column of the image, looking for the top horizontal
black bar of the cube marker. This bar should be 23-32 pixels
thick. Use adaptive thresholding by sorting the pixels and
finding the darkest ones to set the black threshold.
"""
pixels = [float(im[r,col,0]) for r in range(row_start,row_end)]
#print('Column ',col,':',sep='')
#[print('%4d' % i,end='') for i in pixels]
pixels.sort()
npix = len(pixels)
bindex = 1
bsum = pixels[0]
bmax = pixels[0]
bcnt = 1
windex = npix-2
wsum = pixels[npix-1]
wmin = pixels[npix-1]
wcnt = 1
while bindex < windex:
if abs(bmax-pixels[bindex]) < abs(wmin-pixels[windex]):
i = bindex
bindex += 1
else:
i = windex
windex -= 1
bmean = bsum / bcnt
wmean = wsum / wcnt
val = pixels[i]
if abs(val-bmean) < abs(val-wmean):
bsum += val
bcnt += 1
bmax = max(bmax,val)
else:
wsum += val
wcnt +=1
wmin = min(wmin,val)
black_thresh = bmax
index = row_start
nrows = im.shape[0]
black_run_length = 0
# initial white run
while index < nrows and im[index,col,0] > black_thresh:
index += 1
if index == nrows: return -1
while index < nrows and im[index,col,0] <= black_thresh:
black_run_length += 1
index +=1
if index >= nrows-5:
retval = -1
else:
retval = black_run_length
#print(' col=%3d wmin=%5.1f wmean=%5.1f bmean=%5.1f black_thresh=%5.1f run_length=%d' %
# (col, wmin, wmean, bmean, black_thresh, black_run_length))
return retval
def start(self,event=None):
super().start(event)
im = np.array(self.robot.world.latest_image.raw_image)
min_length = 20
max_length = 32
bad_runs = 0
print('Verifying pickup. hangle=%4.1f deg. langle=%4.1f deg. lheight=%4.1f mm' %
(self.robot.head_angle.degrees, self.robot.lift_angle.degrees,
self.robot.lift_height.distance_mm))
columns = (100, 110, 120, 200, 210, 220) # avoid the screw in the center
for col in columns: # range(100,220,20):
run_length = self.probe_column(im, col, 8, 100)
if run_length < min_length or run_length > max_length:
bad_runs += 1
print(' Number of bad_runs:', bad_runs)
if bad_runs < 2:
self.post_success()
else:
self.post_failure()
# end of class VerifyPickup
# PickUpCube methods
def __init__(self, cube=None):
self.cube = cube
super().__init__()
def picked_up_handler(self):
print("PickUpCube aborting because robot was picked up.")
self.post_failure()
def start(self, event=None):
if isinstance(self.cube, LightCube):
self.object = self.cube
try:
self.wmobject = self.object.wm_obj
except:
self.wmobject = None
elif isinstance(self.cube, LightCubeObj):
self.wmobject = self.cube
self.object = self.cube.sdk_obj
elif isinstance(self.object, LightCube):
try:
self.wmobject = self.object.wm_obj
except:
self.wmobject = None
elif isinstance(self.object, LightCubeObj):
self.wmobject = self.object
self.object = self.object.sdk_obj
else:
raise ValueError(self.object)
super().start(event)
if not (self.object.pose and self.object.pose.is_valid and
self.wmobject and not self.wmobject.pose_confidence < 0):
print('PickUpCube: cube has invalid pose!', self.object, self.object.pose)
self.post_event(PilotEvent(InvalidPose))
self.post_failure()
return
self.children['goto_cube'].object = self.object
print('Picking up',self.wmobject)
def setup(self):
# # PickUpCube machine
#
# fetch: SetFetching() =C=> check_carry
#
# check_carry: CheckCarrying()
# check_carry =S=> DropObject() =C=> goto_cube
# check_carry =F=> goto_cube
#
# goto_cube: GoToCube()
# goto_cube =C=> AbortHeadAction() =T(0.1) => # clear head track
# {raise_lift, raise_head}
# goto_cube =PILOT=> goto_cube_pilot: ParentPilotEvent() =N=> pilot_frustrated
# goto_cube =F=> pilot_frustrated
#
# raise_lift: SetLiftHeight(0.4)
#
# raise_head: SetHeadAngle(5)
# raise_head =C=> wait_head: AbortHeadAction() =C=> StateNode() =T(0.2)=> raise_head2
# raise_head =F=> wait_head
# raise_head2: SetHeadAngle(0, num_retries=2)
# raise_head2 =F=> verify
#
# {raise_lift, raise_head2} =C=> verify
#
# verify: self.VerifyPickup()
# verify =S=> set_carrying
# verify =F=> StateNode() =T(0.5)=> verify2
#
# verify2: self.VerifyPickup()
# verify2 =S=> set_carrying
# verify2 =F=> StateNode() =T(0.2)=> frustrated # Time delay before animation
#
# # verify3 is dead code
# verify3: self.VerifyPickup()
# verify3 =S=> set_carrying
# verify3 =F=> frustrated
#
# set_carrying: SetCarrying() =N=> StateNode() =T(0.2)=> satisfied # Time delay before animation
#
# satisfied: AnimationTriggerNode(trigger=cozmo.anim.Triggers.ReactToBlockPickupSuccess,
# ignore_body_track=True,
# ignore_head_track=True,
# ignore_lift_track=True)
# satisfied =C=> {final_raise, drop_head}
# satisfied =F=> StopAllMotors() =T(1)=> {final_raise, drop_head} # in case of tracks locked error
#
# final_raise: SetLiftHeight(1.0)
# drop_head: SetHeadAngle(0)
#
# {final_raise, drop_head} =C=> ParentCompletes()
#
# frustrated: AnimationTriggerNode(trigger=cozmo.anim.Triggers.FrustratedByFailure,
# ignore_body_track=True,
# ignore_head_track=True,
# ignore_lift_track=True) =C=> missed_cube
# frustrated =F=> StopAllMotors() =T(1)=> missed_cube
#
# missed_cube: SetNotCarrying() =C=> Forward(-5) =C=> {drop_lift, drop_head_low}
#
# drop_lift: SetLiftHeight(0)
# drop_lift =C=> backupmore
# drop_lift =F=> backupmore
#
# backupmore: Forward(-5)
#
# drop_head_low: SetHeadAngle(-20)
#
# {backupmore, drop_head_low} =C=> fail
#
# pilot_frustrated: PilotFrustration() =C=> fail
#
# fail: SetNotFetching() =C=> ParentFails()
#
# Code generated by genfsm on Sat Feb 25 01:50:19 2023:
fetch = SetFetching() .set_name("fetch") .set_parent(self)
check_carry = CheckCarrying() .set_name("check_carry") .set_parent(self)
dropobject1 = DropObject() .set_name("dropobject1") .set_parent(self)
goto_cube = GoToCube() .set_name("goto_cube") .set_parent(self)
abortheadaction1 = AbortHeadAction() .set_name("abortheadaction1") .set_parent(self)
goto_cube_pilot = ParentPilotEvent() .set_name("goto_cube_pilot") .set_parent(self)
raise_lift = SetLiftHeight(0.4) .set_name("raise_lift") .set_parent(self)
raise_head = SetHeadAngle(5) .set_name("raise_head") .set_parent(self)
wait_head = AbortHeadAction() .set_name("wait_head") .set_parent(self)
statenode3 = StateNode() .set_name("statenode3") .set_parent(self)
raise_head2 = SetHeadAngle(0, num_retries=2) .set_name("raise_head2") .set_parent(self)
verify = self.VerifyPickup() .set_name("verify") .set_parent(self)
statenode4 = StateNode() .set_name("statenode4") .set_parent(self)
verify2 = self.VerifyPickup() .set_name("verify2") .set_parent(self)
statenode5 = StateNode() .set_name("statenode5") .set_parent(self)
verify3 = self.VerifyPickup() .set_name("verify3") .set_parent(self)
set_carrying = SetCarrying() .set_name("set_carrying") .set_parent(self)
statenode6 = StateNode() .set_name("statenode6") .set_parent(self)
satisfied = AnimationTriggerNode(trigger=cozmo.anim.Triggers.ReactToBlockPickupSuccess,
ignore_body_track=True,
ignore_head_track=True,
ignore_lift_track=True) .set_name("satisfied") .set_parent(self)
stopallmotors1 = StopAllMotors() .set_name("stopallmotors1") .set_parent(self)
final_raise = SetLiftHeight(1.0) .set_name("final_raise") .set_parent(self)
drop_head = SetHeadAngle(0) .set_name("drop_head") .set_parent(self)
parentcompletes2 = ParentCompletes() .set_name("parentcompletes2") .set_parent(self)
frustrated = AnimationTriggerNode(trigger=cozmo.anim.Triggers.FrustratedByFailure,
ignore_body_track=True,
ignore_head_track=True,
ignore_lift_track=True) .set_name("frustrated") .set_parent(self)
stopallmotors2 = StopAllMotors() .set_name("stopallmotors2") .set_parent(self)
missed_cube = SetNotCarrying() .set_name("missed_cube") .set_parent(self)
forward3 = Forward(-5) .set_name("forward3") .set_parent(self)
drop_lift = SetLiftHeight(0) .set_name("drop_lift") .set_parent(self)
backupmore = Forward(-5) .set_name("backupmore") .set_parent(self)
drop_head_low = SetHeadAngle(-20) .set_name("drop_head_low") .set_parent(self)
pilot_frustrated = PilotFrustration() .set_name("pilot_frustrated") .set_parent(self)
fail = SetNotFetching() .set_name("fail") .set_parent(self)
parentfails4 = ParentFails() .set_name("parentfails4") .set_parent(self)
completiontrans24 = CompletionTrans() .set_name("completiontrans24")
completiontrans24 .add_sources(fetch) .add_destinations(check_carry)
successtrans7 = SuccessTrans() .set_name("successtrans7")
successtrans7 .add_sources(check_carry) .add_destinations(dropobject1)
completiontrans25 = CompletionTrans() .set_name("completiontrans25")
completiontrans25 .add_sources(dropobject1) .add_destinations(goto_cube)
failuretrans21 = FailureTrans() .set_name("failuretrans21")
failuretrans21 .add_sources(check_carry) .add_destinations(goto_cube)
completiontrans26 = CompletionTrans() .set_name("completiontrans26")
completiontrans26 .add_sources(goto_cube) .add_destinations(abortheadaction1)
timertrans8 = TimerTrans(0.1) .set_name("timertrans8")
timertrans8 .add_sources(abortheadaction1) .add_destinations(raise_lift,raise_head)
pilottrans5 = PilotTrans() .set_name("pilottrans5")
pilottrans5 .add_sources(goto_cube) .add_destinations(goto_cube_pilot)
nulltrans20 = NullTrans() .set_name("nulltrans20")
nulltrans20 .add_sources(goto_cube_pilot) .add_destinations(pilot_frustrated)
failuretrans22 = FailureTrans() .set_name("failuretrans22")
failuretrans22 .add_sources(goto_cube) .add_destinations(pilot_frustrated)
completiontrans27 = CompletionTrans() .set_name("completiontrans27")
completiontrans27 .add_sources(raise_head) .add_destinations(wait_head)
completiontrans28 = CompletionTrans() .set_name("completiontrans28")
completiontrans28 .add_sources(wait_head) .add_destinations(statenode3)
timertrans9 = TimerTrans(0.2) .set_name("timertrans9")
timertrans9 .add_sources(statenode3) .add_destinations(raise_head2)
failuretrans23 = FailureTrans() .set_name("failuretrans23")
failuretrans23 .add_sources(raise_head) .add_destinations(wait_head)
failuretrans24 = FailureTrans() .set_name("failuretrans24")
failuretrans24 .add_sources(raise_head2) .add_destinations(verify)
completiontrans29 = CompletionTrans() .set_name("completiontrans29")
completiontrans29 .add_sources(raise_lift,raise_head2) .add_destinations(verify)
successtrans8 = SuccessTrans() .set_name("successtrans8")
successtrans8 .add_sources(verify) .add_destinations(set_carrying)
failuretrans25 = FailureTrans() .set_name("failuretrans25")
failuretrans25 .add_sources(verify) .add_destinations(statenode4)
timertrans10 = TimerTrans(0.5) .set_name("timertrans10")
timertrans10 .add_sources(statenode4) .add_destinations(verify2)
successtrans9 = SuccessTrans() .set_name("successtrans9")
successtrans9 .add_sources(verify2) .add_destinations(set_carrying)
failuretrans26 = FailureTrans() .set_name("failuretrans26")
failuretrans26 .add_sources(verify2) .add_destinations(statenode5)
timertrans11 = TimerTrans(0.2) .set_name("timertrans11")
timertrans11 .add_sources(statenode5) .add_destinations(frustrated)
successtrans10 = SuccessTrans() .set_name("successtrans10")
successtrans10 .add_sources(verify3) .add_destinations(set_carrying)
failuretrans27 = FailureTrans() .set_name("failuretrans27")
failuretrans27 .add_sources(verify3) .add_destinations(frustrated)
nulltrans21 = NullTrans() .set_name("nulltrans21")
nulltrans21 .add_sources(set_carrying) .add_destinations(statenode6)
timertrans12 = TimerTrans(0.2) .set_name("timertrans12")
timertrans12 .add_sources(statenode6) .add_destinations(satisfied)
completiontrans30 = CompletionTrans() .set_name("completiontrans30")
completiontrans30 .add_sources(satisfied) .add_destinations(final_raise,drop_head)
failuretrans28 = FailureTrans() .set_name("failuretrans28")
failuretrans28 .add_sources(satisfied) .add_destinations(stopallmotors1)
timertrans13 = TimerTrans(1) .set_name("timertrans13")
timertrans13 .add_sources(stopallmotors1) .add_destinations(final_raise,drop_head)
completiontrans31 = CompletionTrans() .set_name("completiontrans31")
completiontrans31 .add_sources(final_raise,drop_head) .add_destinations(parentcompletes2)
completiontrans32 = CompletionTrans() .set_name("completiontrans32")
completiontrans32 .add_sources(frustrated) .add_destinations(missed_cube)
failuretrans29 = FailureTrans() .set_name("failuretrans29")
failuretrans29 .add_sources(frustrated) .add_destinations(stopallmotors2)
timertrans14 = TimerTrans(1) .set_name("timertrans14")
timertrans14 .add_sources(stopallmotors2) .add_destinations(missed_cube)
completiontrans33 = CompletionTrans() .set_name("completiontrans33")
completiontrans33 .add_sources(missed_cube) .add_destinations(forward3)
completiontrans34 = CompletionTrans() .set_name("completiontrans34")
completiontrans34 .add_sources(forward3) .add_destinations(drop_lift,drop_head_low)
completiontrans35 = CompletionTrans() .set_name("completiontrans35")
completiontrans35 .add_sources(drop_lift) .add_destinations(backupmore)
failuretrans30 = FailureTrans() .set_name("failuretrans30")
failuretrans30 .add_sources(drop_lift) .add_destinations(backupmore)
completiontrans36 = CompletionTrans() .set_name("completiontrans36")
completiontrans36 .add_sources(backupmore,drop_head_low) .add_destinations(fail)
completiontrans37 = CompletionTrans() .set_name("completiontrans37")
completiontrans37 .add_sources(pilot_frustrated) .add_destinations(fail)
completiontrans38 = CompletionTrans() .set_name("completiontrans38")
completiontrans38 .add_sources(fail) .add_destinations(parentfails4)
return self
class DropObject(StateNode):
class SetObject(StateNode):
def start(self,event=None):
super().start(event)
self.parent.object = self.robot.carrying
class CheckCubeVisible(StateNode):
def start(self,event=None):
super().start(event)
for cube in self.robot.world.light_cubes.values():
if cube and cube.is_visible:
self.post_completion()
return
self.post_failure()
def setup(self):
# # DropObject machine
#
# SetLiftHeight(0) =C=> check_carrying
#
# check_carrying: CheckCarrying()
# check_carrying =F=> {backup, lookdown}
# check_carrying =S=> self.SetObject() =N=>
# SetNotCarrying() =N=> SetFetching() =N=> {backup, lookdown}
#
# backup: Forward(-15)
#
# # Robots differ on head angle alignment, so try a shallow angle,
# # and if we don't see the cube, try a steeper one.
# lookdown: SetHeadAngle(-12)
# lookdown =F=> head_angle_wait # Shouldn't fail, but just in case
#
# {backup, lookdown} =C=> head_angle_wait
#
# head_angle_wait: StateNode() =T(0.5)=> check_visible
#
# check_visible: self.CheckCubeVisible()
# check_visible =C=> wrap_up
# check_visible =F=> lookdown2
#
# # Try a lower head angle, but keep going even if we don't see the object
# lookdown2: SetHeadAngle(-20)
# lookdown2 =F=> wrap_up # Shouldn't fail, but just in case
# lookdown2 =T(0.5)=> wrap_up
#
# wrap_up: SetNotFetching() =N=> ParentCompletes()
# Code generated by genfsm on Sat Feb 25 01:50:19 2023:
setliftheight3 = SetLiftHeight(0) .set_name("setliftheight3") .set_parent(self)
check_carrying = CheckCarrying() .set_name("check_carrying") .set_parent(self)
setobject1 = self.SetObject() .set_name("setobject1") .set_parent(self)
setnotcarrying1 = SetNotCarrying() .set_name("setnotcarrying1") .set_parent(self)
setfetching1 = SetFetching() .set_name("setfetching1") .set_parent(self)
backup = Forward(-15) .set_name("backup") .set_parent(self)
lookdown = SetHeadAngle(-12) .set_name("lookdown") .set_parent(self)
head_angle_wait = StateNode() .set_name("head_angle_wait") .set_parent(self)
check_visible = self.CheckCubeVisible() .set_name("check_visible") .set_parent(self)
lookdown2 = SetHeadAngle(-20) .set_name("lookdown2") .set_parent(self)
wrap_up = SetNotFetching() .set_name("wrap_up") .set_parent(self)
parentcompletes3 = ParentCompletes() .set_name("parentcompletes3") .set_parent(self)
completiontrans39 = CompletionTrans() .set_name("completiontrans39")
completiontrans39 .add_sources(setliftheight3) .add_destinations(check_carrying)
failuretrans31 = FailureTrans() .set_name("failuretrans31")
failuretrans31 .add_sources(check_carrying) .add_destinations(backup,lookdown)
successtrans11 = SuccessTrans() .set_name("successtrans11")
successtrans11 .add_sources(check_carrying) .add_destinations(setobject1)
nulltrans22 = NullTrans() .set_name("nulltrans22")
nulltrans22 .add_sources(setobject1) .add_destinations(setnotcarrying1)
nulltrans23 = NullTrans() .set_name("nulltrans23")
nulltrans23 .add_sources(setnotcarrying1) .add_destinations(setfetching1)
nulltrans24 = NullTrans() .set_name("nulltrans24")
nulltrans24 .add_sources(setfetching1) .add_destinations(backup,lookdown)
failuretrans32 = FailureTrans() .set_name("failuretrans32")
failuretrans32 .add_sources(lookdown) .add_destinations(head_angle_wait)
completiontrans40 = CompletionTrans() .set_name("completiontrans40")
completiontrans40 .add_sources(backup,lookdown) .add_destinations(head_angle_wait)
timertrans15 = TimerTrans(0.5) .set_name("timertrans15")
timertrans15 .add_sources(head_angle_wait) .add_destinations(check_visible)
completiontrans41 = CompletionTrans() .set_name("completiontrans41")
completiontrans41 .add_sources(check_visible) .add_destinations(wrap_up)
failuretrans33 = FailureTrans() .set_name("failuretrans33")
failuretrans33 .add_sources(check_visible) .add_destinations(lookdown2)
failuretrans34 = FailureTrans() .set_name("failuretrans34")
failuretrans34 .add_sources(lookdown2) .add_destinations(wrap_up)
timertrans16 = TimerTrans(0.5) .set_name("timertrans16")
timertrans16 .add_sources(lookdown2) .add_destinations(wrap_up)
nulltrans25 = NullTrans() .set_name("nulltrans25")
nulltrans25 .add_sources(wrap_up) .add_destinations(parentcompletes3)
return self
class PivotCube(StateNode):
def __init__(self):
super().__init__()
def start(self, event=None):
super().start(event)
def setup(self):
# put_arm: SetLiftHeight(0.68)
# put_arm =C=> {drop, back}
# put_arm =F=> ParentFails()
#
# drop: SetLiftHeight(0.28)
# back: Forward(-60)
#
# drop =F=> ParentFails()
# back =F=> ParentFails()
#
# {drop, back} =C=> reset
# {drop, back} =F=> ParentFails()
#
# reset: SetLiftHeight(0)
# reset =C=> Forward(-10) =C=> ParentCompletes()
# reset =F=> ParentFails()
# Code generated by genfsm on Sat Feb 25 01:50:19 2023:
put_arm = SetLiftHeight(0.68) .set_name("put_arm") .set_parent(self)
parentfails5 = ParentFails() .set_name("parentfails5") .set_parent(self)
drop = SetLiftHeight(0.28) .set_name("drop") .set_parent(self)
back = Forward(-60) .set_name("back") .set_parent(self)
parentfails6 = ParentFails() .set_name("parentfails6") .set_parent(self)
parentfails7 = ParentFails() .set_name("parentfails7") .set_parent(self)
parentfails8 = ParentFails() .set_name("parentfails8") .set_parent(self)
reset = SetLiftHeight(0) .set_name("reset") .set_parent(self)
forward4 = Forward(-10) .set_name("forward4") .set_parent(self)
parentcompletes4 = ParentCompletes() .set_name("parentcompletes4") .set_parent(self)
parentfails9 = ParentFails() .set_name("parentfails9") .set_parent(self)
completiontrans42 = CompletionTrans() .set_name("completiontrans42")
completiontrans42 .add_sources(put_arm) .add_destinations(drop,back)
failuretrans35 = FailureTrans() .set_name("failuretrans35")
failuretrans35 .add_sources(put_arm) .add_destinations(parentfails5)
failuretrans36 = FailureTrans() .set_name("failuretrans36")
failuretrans36 .add_sources(drop) .add_destinations(parentfails6)
failuretrans37 = FailureTrans() .set_name("failuretrans37")
failuretrans37 .add_sources(back) .add_destinations(parentfails7)
completiontrans43 = CompletionTrans() .set_name("completiontrans43")
completiontrans43 .add_sources(drop,back) .add_destinations(reset)
failuretrans38 = FailureTrans() .set_name("failuretrans38")
failuretrans38 .add_sources(drop,back) .add_destinations(parentfails8)
completiontrans44 = CompletionTrans() .set_name("completiontrans44")
completiontrans44 .add_sources(reset) .add_destinations(forward4)
completiontrans45 = CompletionTrans() .set_name("completiontrans45")
completiontrans45 .add_sources(forward4) .add_destinations(parentcompletes4)
failuretrans39 = FailureTrans() .set_name("failuretrans39")
failuretrans39 .add_sources(reset) .add_destinations(parentfails9)
return self
class RollingCube(StateNode):
def __init__(self, object=None, orientation=None, old_object=None):
super().__init__()
self.object = object
self.target_orientation = orientation
self.old_object = old_object
self.try_roll_number = 0
def start(self, event=None):
if isinstance(self.object, LightCube):
try:
self.wmobject = self.object.wm_obj
except:
self.wmobject = None
elif isinstance(self.object, LightCubeObj):
self.wmobject = self.object
self.object = self.object.sdk_obj
else:
raise ValueError(self.object)
self.children['looker'].object = self.object
self.children['goto_cube'].object = self.object
self.children['goto_cube'].roll_cube = True
self.children['goto_cube'].roll_target = self.target_orientation
self.children['roll1'].object = self.object
self.children['roll2'].object = self.object
self.children['roll3'].object = self.object
super().start(event)
if (not self.wmobject) or self.wmobject.pose_confidence < 0:
print('RollingCube: cube has invalid pose!', self.object, self.object.pose)
self.post_event(PilotEvent(InvalidPose))
self.post_failure()
def try_again(self):
if self.try_roll_number > 2:
self.try_roll_number = 0
print('Reach max trying number.')
return False
else:
self.try_roll_number += 1
print('try again', self.try_roll_number)
return True
class CheckOrientation(StateNode):
def start(self,event=None):
self.parent.orientation, _, _, _ = get_orientation_state(self.parent.object.pose.rotation.q0_q1_q2_q3)
super().start(event)
if self.parent.target_orientation == self.parent.orientation != None:
print('rolled it successfully to', self.parent.target_orientation)
self.post_success()
elif not self.parent.target_orientation:
if not self.parent.old_object or self.parent.old_object.wm_obj.id != self.parent.object.wm_obj.id:
self.parent.old_object = copy.copy(self.parent.object)
self.post_completion()
elif same_orientation(self.parent.old_object, self.parent.object):
print('failed: still the same orientation')
self.post_failure()
else:
self.parent.old_object = copy.copy(self.parent.object)
print('rolled it successfully')
self.post_success()
else:
if not self.parent.old_object:
self.parent.old_object = copy.copy(self.parent.object)
self.post_completion()
else:
print('failed: orientation is not', self.parent.target_orientation)
self.post_failure()
class CheckCubePoseValidOnce(StateNode):
def __init__(self, check_vis=False, reset=False):
self.check_vis = check_vis
self.reset = reset
super().__init__()
def start(self, event=None):
super().start(event)
if isinstance(self.parent.object, LightCube):
cube_id = self.parent.object.wm_obj.id
elif isinstance(self.parent.object, LightCubeObj):
cube_id = self.parent.object.id
else:
raise ValueError(self.parent.object)
if 'Cube' not in str(cube_id):
cube_id = 'Cube-' + str(cube_id)
wmobject = self.robot.world.world_map.objects[cube_id]
if self.check_vis and not self.parent.object.is_visible:
if self.reset:
self.parent.wmobject.pose_confidence = -1
print('CheckCubePoseValidOnce: %s has invalid pose!' % cube_id)
self.post_failure()
elif self.parent.wmobject.pose_confidence < 0:
print('pose_confidence', self.parent.wmobject.pose_confidence)
self.post_failure()
else:
self.post_completion()
class CheckCounts(StateNode):
def start(self,event=None):
SIDEWAYS_FRONT = 'front'
SIDEWAYS_BACK = 'back'
SIDEWAYS_SIDE = 'side'
super().start(event)
if not self.parent.target_orientation:
print('no target_orientation')
self.post_data(1)
elif self.parent.orientation == ORIENTATION_UPRIGHT or self.parent.orientation == ORIENTATION_INVERTED:
if self.parent.target_orientation == ORIENTATION_SIDEWAYS:
self.post_data(1)
elif self.parent.orientation == self.parent.target_orientation:
self.post_data(3)
else:
self.post_data(2)
else: # ORIENTATION_SIDEWAYS
x, y, z = self.parent.object.pose.rotation.euler_angles
robot_angle = self.robot.pose.rotation.angle_z.radians
pattern = get_pattern_number(self.parent.object.pose.rotation.euler_angles)
if pattern == 1:
cube_rotate_angle = wrap_angle(x - pi/2)
new_robot_angle = wrap_angle(robot_angle + cube_rotate_angle)
elif pattern == 2:
cube_rotate_angle = wrap_angle(y + pi)
new_robot_angle = wrap_angle(robot_angle + cube_rotate_angle)
elif pattern == 3:
cube_rotate_angle = wrap_angle(- (x + pi/2))
new_robot_angle = wrap_angle(robot_angle + cube_rotate_angle)
elif pattern == 4:
cube_rotate_angle = y
new_robot_angle = wrap_angle(robot_angle + cube_rotate_angle)
else:
print('Unrecognized pattern.')
cube_rotate_angle = 0
new_robot_angle = 0
possible_angles = [-pi, -pi/2, 0, pi/2, pi]
facing_side = None
new_robot_angle = min(possible_angles, key=lambda val:abs(val-new_robot_angle))
if new_robot_angle == 0:
facing_side = SIDEWAYS_FRONT
elif abs(new_robot_angle) == pi:
facing_side = SIDEWAYS_BACK
else:
facing_side = SIDEWAYS_SIDE
# print('new_robot_angle: %.2f' % new_robot_angle)
print('Robot is facing', facing_side)
if facing_side == SIDEWAYS_SIDE: # left/right
if self.parent.target_orientation == ORIENTATION_SIDEWAYS:
self.post_data(1)
else:
self.post_data(0)
elif facing_side == SIDEWAYS_FRONT: # front
if self.parent.target_orientation == ORIENTATION_INVERTED:
self.post_data(1)
elif self.parent.target_orientation == ORIENTATION_SIDEWAYS:
self.post_data(2)
else:
self.post_data(3)
elif facing_side == SIDEWAYS_BACK: # back
if self.parent.target_orientation == ORIENTATION_UPRIGHT:
self.post_data(1)
elif self.parent.target_orientation == ORIENTATION_SIDEWAYS:
self.post_data(2)
else:
self.post_data(3)
class TryAgain(StateNode):
def __init__(self):
super().__init__()
def start(self, event=None):
super().start(event)
if self.parent.try_again():
self.post_failure()
else:
self.post_success()
class ForwardToCube(Forward):
def __init__(self, offset):
self.offset = offset
super().__init__()
def start(self, event=None):
if self.running: return
cube = self.parent.object
dx = cube.pose.position.x - self.robot.pose.position.x
dy = cube.pose.position.y - self.robot.pose.position.y
dist = sqrt(dx*dx + dy*dy) - self.offset
if (dist < 0):
print('***** ForwardToCube %s negative distance: %.1f mm' % (self.name,dist))
self.distance = Distance(dist)
print('ForwardToCube %s: distance %.1f mm' % (self.name, self.distance.distance_mm))
super().start(event)
def setup(self):
# # RollingCube machine
#
# start: SetFetching() =C=> {looker, check_cube_pose}
#
# looker: LookAtObject()
#
# check_cube_pose: self.CheckCubePoseValidOnce(check_vis=False)
# check_cube_pose =C=> check_orientation
# check_cube_pose =F=> fail
#
# check_orientation: self.CheckOrientation()
# check_orientation =C=> goto_cube
# check_orientation =S=> StateNode() =T(0.5)=> satisfied
# check_orientation =F=> StateNode() =T(0.5)=> frustrated
#
# satisfied: AnimationTriggerNode(trigger=cozmo.anim.Triggers.RollBlockSuccess,
# ignore_body_track=True,
# ignore_head_track=True,
# ignore_lift_track=True)
#
# satisfied =C=> ParentCompletes()
# satisfied =F=> StopAllMotors() =T(1)=> ParentCompletes()
#
# frustrated: AnimationTriggerNode(trigger=cozmo.anim.Triggers.FrustratedByFailure,
# ignore_body_track=True,
# ignore_head_track=True,
# ignore_lift_track=True)
# frustrated =C=> goto_cube
# frustrated =F=> StopAllMotors() =T(1)=> goto_cube
#
# goto_cube: GoToCube()
# goto_cube =F=> Print('goto_cube has failed.') =N=> try_again
# goto_cube =C=> Print('goto_cube has succeeded.') =N=> decide_roll_counts
#
# decide_roll_counts: self.CheckCounts()
# decide_roll_counts =D(0)=> Print('No way to achieve from this side') =C=> check_cube_pose_valid
# decide_roll_counts =D(1)=> Print('Roll once') =C=> roll1
# decide_roll_counts =D(2)=> Print('Roll twice') =C=> roll2
# decide_roll_counts =D(3)=> Print('Roll thrice') =C=> roll3
#
# check_cube_pose_valid: self.CheckCubePoseValidOnce(check_vis=True)
# check_cube_pose_valid =C=> check_orientation
# check_cube_pose_valid =F=> setup_check_again
#
# setup_check_again: Forward(-30)
# setup_check_again =C=> Print('backing up...') =T(1)=> check_cube_pose_valid2
# setup_check_again =F=> try_again
#
# check_cube_pose_valid2:self.CheckCubePoseValidOnce(check_vis=True, reset=True)
# check_cube_pose_valid2 =C=> check_orientation
# check_cube_pose_valid2 =F=> try_again
#
# roll1: PivotCube()
# roll1 =C=> Forward(-30) =C=> Print('Checking the new orientation...') =T(1)=> check_cube_pose_valid
# roll1 =F=> try_again
#
# roll2: PivotCube()
# roll2 =C=> SetLiftHeight(1) =C=> self.ForwardToCube(15) =C=> roll1
# roll2 =F=> try_again
#
# roll3: PivotCube()
# roll3 =C=> SetLiftHeight(1) =C=> self.ForwardToCube(15) =C=> roll2
# roll3 =F=> try_again
#
# try_again: self.TryAgain()
# try_again =S=> check_cube_pose_valid
# try_again =F=> fail
#
# fail: SetNotFetching() =C=> ParentFails()
# Code generated by genfsm on Sat Feb 25 01:50:19 2023:
start = SetFetching() .set_name("start") .set_parent(self)
looker = LookAtObject() .set_name("looker") .set_parent(self)
check_cube_pose = self.CheckCubePoseValidOnce(check_vis=False) .set_name("check_cube_pose") .set_parent(self)
check_orientation = self.CheckOrientation() .set_name("check_orientation") .set_parent(self)
statenode7 = StateNode() .set_name("statenode7") .set_parent(self)
statenode8 = StateNode() .set_name("statenode8") .set_parent(self)
satisfied = AnimationTriggerNode(trigger=cozmo.anim.Triggers.RollBlockSuccess,
ignore_body_track=True,
ignore_head_track=True,
ignore_lift_track=True) .set_name("satisfied") .set_parent(self)
parentcompletes5 = ParentCompletes() .set_name("parentcompletes5") .set_parent(self)
stopallmotors3 = StopAllMotors() .set_name("stopallmotors3") .set_parent(self)
parentcompletes6 = ParentCompletes() .set_name("parentcompletes6") .set_parent(self)
frustrated = AnimationTriggerNode(trigger=cozmo.anim.Triggers.FrustratedByFailure,
ignore_body_track=True,
ignore_head_track=True,
ignore_lift_track=True) .set_name("frustrated") .set_parent(self)
stopallmotors4 = StopAllMotors() .set_name("stopallmotors4") .set_parent(self)
goto_cube = GoToCube() .set_name("goto_cube") .set_parent(self)
print11 = Print('goto_cube has failed.') .set_name("print11") .set_parent(self)
print12 = Print('goto_cube has succeeded.') .set_name("print12") .set_parent(self)
decide_roll_counts = self.CheckCounts() .set_name("decide_roll_counts") .set_parent(self)
print13 = Print('No way to achieve from this side') .set_name("print13") .set_parent(self)
print14 = Print('Roll once') .set_name("print14") .set_parent(self)
print15 = Print('Roll twice') .set_name("print15") .set_parent(self)
print16 = Print('Roll thrice') .set_name("print16") .set_parent(self)
check_cube_pose_valid = self.CheckCubePoseValidOnce(check_vis=True) .set_name("check_cube_pose_valid") .set_parent(self)
setup_check_again = Forward(-30) .set_name("setup_check_again") .set_parent(self)
print17 = Print('backing up...') .set_name("print17") .set_parent(self)
check_cube_pose_valid2 = self.CheckCubePoseValidOnce(check_vis=True, reset=True) .set_name("check_cube_pose_valid2") .set_parent(self)
roll1 = PivotCube() .set_name("roll1") .set_parent(self)
forward5 = Forward(-30) .set_name("forward5") .set_parent(self)
print18 = Print('Checking the new orientation...') .set_name("print18") .set_parent(self)
roll2 = PivotCube() .set_name("roll2") .set_parent(self)
setliftheight4 = SetLiftHeight(1) .set_name("setliftheight4") .set_parent(self)
forwardtocube1 = self.ForwardToCube(15) .set_name("forwardtocube1") .set_parent(self)
roll3 = PivotCube() .set_name("roll3") .set_parent(self)
setliftheight5 = SetLiftHeight(1) .set_name("setliftheight5") .set_parent(self)
forwardtocube2 = self.ForwardToCube(15) .set_name("forwardtocube2") .set_parent(self)
try_again = self.TryAgain() .set_name("try_again") .set_parent(self)
fail = SetNotFetching() .set_name("fail") .set_parent(self)
parentfails10 = ParentFails() .set_name("parentfails10") .set_parent(self)
completiontrans46 = CompletionTrans() .set_name("completiontrans46")
completiontrans46 .add_sources(start) .add_destinations(looker,check_cube_pose)
completiontrans47 = CompletionTrans() .set_name("completiontrans47")
completiontrans47 .add_sources(check_cube_pose) .add_destinations(check_orientation)
failuretrans40 = FailureTrans() .set_name("failuretrans40")
failuretrans40 .add_sources(check_cube_pose) .add_destinations(fail)
completiontrans48 = CompletionTrans() .set_name("completiontrans48")
completiontrans48 .add_sources(check_orientation) .add_destinations(goto_cube)
successtrans12 = SuccessTrans() .set_name("successtrans12")
successtrans12 .add_sources(check_orientation) .add_destinations(statenode7)
timertrans17 = TimerTrans(0.5) .set_name("timertrans17")
timertrans17 .add_sources(statenode7) .add_destinations(satisfied)
failuretrans41 = FailureTrans() .set_name("failuretrans41")
failuretrans41 .add_sources(check_orientation) .add_destinations(statenode8)
timertrans18 = TimerTrans(0.5) .set_name("timertrans18")
timertrans18 .add_sources(statenode8) .add_destinations(frustrated)
completiontrans49 = CompletionTrans() .set_name("completiontrans49")
completiontrans49 .add_sources(satisfied) .add_destinations(parentcompletes5)
failuretrans42 = FailureTrans() .set_name("failuretrans42")
failuretrans42 .add_sources(satisfied) .add_destinations(stopallmotors3)
timertrans19 = TimerTrans(1) .set_name("timertrans19")
timertrans19 .add_sources(stopallmotors3) .add_destinations(parentcompletes6)
completiontrans50 = CompletionTrans() .set_name("completiontrans50")
completiontrans50 .add_sources(frustrated) .add_destinations(goto_cube)
failuretrans43 = FailureTrans() .set_name("failuretrans43")
failuretrans43 .add_sources(frustrated) .add_destinations(stopallmotors4)
timertrans20 = TimerTrans(1) .set_name("timertrans20")
timertrans20 .add_sources(stopallmotors4) .add_destinations(goto_cube)
failuretrans44 = FailureTrans() .set_name("failuretrans44")
failuretrans44 .add_sources(goto_cube) .add_destinations(print11)
nulltrans26 = NullTrans() .set_name("nulltrans26")
nulltrans26 .add_sources(print11) .add_destinations(try_again)
completiontrans51 = CompletionTrans() .set_name("completiontrans51")
completiontrans51 .add_sources(goto_cube) .add_destinations(print12)
nulltrans27 = NullTrans() .set_name("nulltrans27")
nulltrans27 .add_sources(print12) .add_destinations(decide_roll_counts)
datatrans2 = DataTrans(0) .set_name("datatrans2")
datatrans2 .add_sources(decide_roll_counts) .add_destinations(print13)
completiontrans52 = CompletionTrans() .set_name("completiontrans52")
completiontrans52 .add_sources(print13) .add_destinations(check_cube_pose_valid)
datatrans3 = DataTrans(1) .set_name("datatrans3")
datatrans3 .add_sources(decide_roll_counts) .add_destinations(print14)
completiontrans53 = CompletionTrans() .set_name("completiontrans53")
completiontrans53 .add_sources(print14) .add_destinations(roll1)
datatrans4 = DataTrans(2) .set_name("datatrans4")
datatrans4 .add_sources(decide_roll_counts) .add_destinations(print15)
completiontrans54 = CompletionTrans() .set_name("completiontrans54")
completiontrans54 .add_sources(print15) .add_destinations(roll2)
datatrans5 = DataTrans(3) .set_name("datatrans5")
datatrans5 .add_sources(decide_roll_counts) .add_destinations(print16)
completiontrans55 = CompletionTrans() .set_name("completiontrans55")
completiontrans55 .add_sources(print16) .add_destinations(roll3)
completiontrans56 = CompletionTrans() .set_name("completiontrans56")
completiontrans56 .add_sources(check_cube_pose_valid) .add_destinations(check_orientation)
failuretrans45 = FailureTrans() .set_name("failuretrans45")
failuretrans45 .add_sources(check_cube_pose_valid) .add_destinations(setup_check_again)
completiontrans57 = CompletionTrans() .set_name("completiontrans57")
completiontrans57 .add_sources(setup_check_again) .add_destinations(print17)
timertrans21 = TimerTrans(1) .set_name("timertrans21")
timertrans21 .add_sources(print17) .add_destinations(check_cube_pose_valid2)
failuretrans46 = FailureTrans() .set_name("failuretrans46")
failuretrans46 .add_sources(setup_check_again) .add_destinations(try_again)
completiontrans58 = CompletionTrans() .set_name("completiontrans58")
completiontrans58 .add_sources(check_cube_pose_valid2) .add_destinations(check_orientation)
failuretrans47 = FailureTrans() .set_name("failuretrans47")
failuretrans47 .add_sources(check_cube_pose_valid2) .add_destinations(try_again)
completiontrans59 = CompletionTrans() .set_name("completiontrans59")
completiontrans59 .add_sources(roll1) .add_destinations(forward5)
completiontrans60 = CompletionTrans() .set_name("completiontrans60")
completiontrans60 .add_sources(forward5) .add_destinations(print18)
timertrans22 = TimerTrans(1) .set_name("timertrans22")
timertrans22 .add_sources(print18) .add_destinations(check_cube_pose_valid)
failuretrans48 = FailureTrans() .set_name("failuretrans48")
failuretrans48 .add_sources(roll1) .add_destinations(try_again)
completiontrans61 = CompletionTrans() .set_name("completiontrans61")
completiontrans61 .add_sources(roll2) .add_destinations(setliftheight4)
completiontrans62 = CompletionTrans() .set_name("completiontrans62")
completiontrans62 .add_sources(setliftheight4) .add_destinations(forwardtocube1)
completiontrans63 = CompletionTrans() .set_name("completiontrans63")
completiontrans63 .add_sources(forwardtocube1) .add_destinations(roll1)
failuretrans49 = FailureTrans() .set_name("failuretrans49")
failuretrans49 .add_sources(roll2) .add_destinations(try_again)
completiontrans64 = CompletionTrans() .set_name("completiontrans64")
completiontrans64 .add_sources(roll3) .add_destinations(setliftheight5)
completiontrans65 = CompletionTrans() .set_name("completiontrans65")
completiontrans65 .add_sources(setliftheight5) .add_destinations(forwardtocube2)
completiontrans66 = CompletionTrans() .set_name("completiontrans66")
completiontrans66 .add_sources(forwardtocube2) .add_destinations(roll2)
failuretrans50 = FailureTrans() .set_name("failuretrans50")
failuretrans50 .add_sources(roll3) .add_destinations(try_again)
successtrans13 = SuccessTrans() .set_name("successtrans13")
successtrans13 .add_sources(try_again) .add_destinations(check_cube_pose_valid)
failuretrans51 = FailureTrans() .set_name("failuretrans51")
failuretrans51 .add_sources(try_again) .add_destinations(fail)
completiontrans67 = CompletionTrans() .set_name("completiontrans67")
completiontrans67 .add_sources(fail) .add_destinations(parentfails10)
return self
"""
class PickUpCubeForeign(StateNode):
# *** THIS IS OLD CODE AND NEEDS TO BE UPDATED ***
def __init__(self, cube_id=None):
self.object_id = cube_id
super().__init__()
def start(self, event=None):
# self.object will be set up by the parent of this node
self.object = self.robot.world.light_cubes[self.object_id]
self.foreign_cube_id = 'LightCubeForeignObj-'+str(self.object_id)
super().start(event)
def pick_side(self, dist, use_world_map):
# NOTE: This code is only correct for upright cubes
cube = self.foreign_cube_id
wobj = self.robot.world.world_map.objects[cube]
x = wobj.x
y = wobj.y
ang = wobj.theta
rx = self.robot.world.particle_filter.pose[0]
ry = self.robot.world.particle_filter.pose[1]
side1 = (x + cos(ang) * dist, y + sin(ang) * dist, ang + pi)
side2 = (x - cos(ang) * dist, y - sin(ang) * dist, ang)
side3 = (x + sin(ang) * dist, y - cos(ang) * dist, ang + pi/2)
side4 = (x - sin(ang) * dist, y + cos(ang) * dist, ang - pi/2)
sides = [side1, side2, side3, side4]
sorted_sides = sorted(sides, key=lambda pt: (pt[0]-rx)**2 + (pt[1]-ry)**2)
return sorted_sides[0]
class GoToSide(WallPilotToPose):
def __init__(self):
super().__init__(None)
def start(self, event=None):
cube = self.parent.foreign_cube_id
print('Selected cube',self.robot.world.world_map.objects[cube])
(x, y, theta) = self.parent.pick_side(200, True)
self.target_pose = Pose(x, y, self.robot.pose.position.z,
angle_z=Angle(radians = wrap_angle(theta)))
print('pickup.GoToSide: traveling to (%.1f, %.1f) @ %.1f deg.' %
(self.target_pose.position.x, self.target_pose.position.y,
self.target_pose.rotation.angle_z.degrees))
super().start(event)
class Pick(PickUpCube):
def __init__(self):
super().__init__(None)
def start(self, event=None):
self.object = self.parent.object
super().start(event)
#setup{ # PickUpCube machine
goto_cube: self.GoToSide() =C=> one
one: self.Pick() =C=> end
end: Say('Done') =C=> ParentCompletes()
}
"""
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,011
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/CV_Hough.py
|
"""
CV_Hough demonstrates OpenCV's HoughLines and probabilistic HoughLinesP
primitives. The 'edges' window displays the results of a Canny edge operator
that is the input to the Hough transform. The 'Hough' window shows the
output of HoughLines with the given settings of the r and theta tolerances
and minimum bin count (threshold). The 'HoughP' window shows the output of
HoughLinesP using the r and theta values from the Hough window, plus the
minLineLength and maxLineGap parameters and its own bin count threshold.
"""
import cv2
import numpy as np
from cozmo_fsm import *
class CV_Hough(StateMachineProgram):
def __init__(self):
super().__init__(aruco=False, particle_filter=False, cam_viewer=False,
force_annotation=True, annotate_sdk=False)
def start(self):
cv2.namedWindow('gray')
cv2.namedWindow('edges')
cv2.namedWindow('Hough')
cv2.namedWindow('HoughP')
dummy = numpy.array([[0]], dtype='uint8')
cv2.imshow('gray',dummy)
cv2.imshow('edges',dummy)
cv2.imshow('Hough',dummy)
cv2.imshow('HoughP',dummy)
self.h_lines = None
self.p_lines = None
cv2.createTrackbar('thresh1','edges',0,255,lambda self: None)
cv2.createTrackbar('thresh2','edges',0,255,lambda self: None)
cv2.setTrackbarPos('thresh1','edges',50)
cv2.setTrackbarPos('thresh2','edges',150)
cv2.createTrackbar('r_tol','Hough',1,10,lambda self: None)
cv2.createTrackbar('deg_tol','Hough',1,18,lambda self: None)
cv2.createTrackbar('h_thresh','Hough',1,250,lambda self: None)
cv2.createTrackbar('h_main','Hough',0,1,lambda self: None)
cv2.setTrackbarPos('r_tol','Hough',2)
cv2.setTrackbarPos('deg_tol','Hough',2)
cv2.setTrackbarPos('h_thresh','Hough',120)
cv2.setTrackbarPos('h_main','Hough',0)
cv2.createTrackbar('minLineLength','HoughP',1,80,lambda self: None)
cv2.createTrackbar('maxLineGap','HoughP',1,50,lambda self: None)
cv2.createTrackbar('p_thresh','HoughP',1,250,lambda self: None)
cv2.setTrackbarPos('minLineLength','HoughP',40)
cv2.setTrackbarPos('maxLineGap','HoughP',20)
cv2.setTrackbarPos('p_thresh','HoughP',20)
cv2.createTrackbar('p_main','HoughP',0,1,lambda self: None)
cv2.setTrackbarPos('p_main','HoughP',0)
super().start()
def user_image(self,image,gray):
self.gray = gray
# Canny edge detector
self.thresh1 = cv2.getTrackbarPos('thresh1','edges')
self.thresh2 = cv2.getTrackbarPos('thresh2','edges')
self.edges = cv2.Canny(gray, self.thresh1, self.thresh2, apertureSize=3)
# regular Hough
self.r_tol = max(0.1, cv2.getTrackbarPos('r_tol','Hough'))
self.deg_tol = max(0.1, cv2.getTrackbarPos('deg_tol','Hough'))
self.h_thresh = cv2.getTrackbarPos('h_thresh','Hough')
self.h_lines = cv2.HoughLines(self.edges, self.r_tol,
self.deg_tol/180.*np.pi,
self.h_thresh)
# probabilistic Hough
self.p_thresh = cv2.getTrackbarPos('p_thresh','HoughP')
self.minLineLength = cv2.getTrackbarPos('minLineLength','HoughP')
self.maxLineGap = cv2.getTrackbarPos('maxLineGap','HoughP')
self.p_lines = cv2.HoughLinesP(self.edges, self.r_tol, self.deg_tol/180.*np.pi,
self.p_thresh, None,
self.minLineLength, self.maxLineGap)
def user_annotate(self,image):
cv2.imshow('gray',self.gray)
cv2.imshow('edges',self.edges)
if self.h_lines is not None:
hough_image = cv2.cvtColor(self.edges,cv2.COLOR_GRAY2BGR)
h_main = cv2.getTrackbarPos('h_main','Hough')
for line in self.h_lines:
rho, theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*a)
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*a)
cv2.line(hough_image,(x1,y1),(x2,y2),(0,255,0),1)
if h_main:
cv2.line(image,(2*x1,2*y1),(2*x2,2*y2),(0,255,0),2)
cv2.imshow('Hough',hough_image)
if self.p_lines is not None:
houghp_image = cv2.cvtColor(self.edges,cv2.COLOR_GRAY2BGR)
p_main = cv2.getTrackbarPos('p_main','HoughP')
for line in self.p_lines:
x1,y1,x2,y2 = line[0]
cv2.line(houghp_image,(x1,y1),(x2,y2),(255,0,0),1)
if p_main:
cv2.line(image,(2*x1,2*y1),(2*x2,2*y2),(255,0,0),2)
cv2.imshow('HoughP',houghp_image)
cv2.waitKey(1)
return image
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,012
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/worldmap_viewer.py
|
"""
OpenGL world viewer for cozmo_fsm world map.
"""
from math import sin, cos, atan2, pi, radians
import time
import array
import numpy as np
import platform as pf
try:
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
pass
from . import opengl
from . import geometry
from . import worldmap
import cozmo
from cozmo.nav_memory_map import NodeContentTypes
WINDOW = None
EXCEPTION_COUNTER = 0
DISPLAY_ENABLED = True
help_text = """
World viewer keyboard commands:
a Translate gazepoint left
d Translate gazepoint right
w Translate gazepoint forward
s Translate gazepoint backward
< Zoom in
> Zoom out
page-up Translate gazepoint up
page-down Translate gazepoint down
left-arrow Orbit camera left
right-arrow Orbit camera right
up-arrow Orbit camera upward
down-arrow Orbit camera downward
m Toggle memory map
x Toggle axes
z Reset to initial view
v Toggle display of viewing parameters
# Disable/enable automatic redisplay
h Print help
"""
help_text_mac = """
World viewer keyboard commands:
option + a Translate gazepoint left
option + d Translate gazepoint right
option + w Translate gazepoint forward
option + s Translate gazepoint backward
option + < Zoom in
option + > Zoom out
fn + up-arrow Translate gazepoint up
fn + down-arrow Translate gazepoint down
left-arrow Orbit camera left
right-arrow Orbit camera right
up-arrow Orbit camera upward
down-arrow Orbit camera downward
option + m Toggle memory map
option + x Toggle axes
option + z Reset to initial view
option + v Toggle display of viewing parameters
# Disable/enable automatic redisplay
option + h Print help
"""
cube_vertices = array.array('f', [ \
-0.5, -0.5, +0.5, \
-0.5, +0.5, +0.5, \
+0.5, +0.5, +0.5, \
+0.5, -0.5, +0.5, \
-0.5, -0.5, -0.5, \
-0.5, +0.5, -0.5, \
+0.5, +0.5, -0.5, \
+0.5, -0.5, -0.5 \
])
camera_vertices = array.array('f', [ \
-0.5, 0, 0, \
-0.5, 0, 0, \
+0.5, +0.5, +0.5, \
+0.5, -0.5, +0.5, \
-0.5, 0, 0, \
-0.5, 0, 0, \
+0.5, +0.5, -0.5, \
+0.5, -0.5, -0.5 \
])
cube_colors_0 = array.array('f', [ \
0.6, 0.6, 0.0, \
0.6, 0.6, 0.0, \
0.0, 0.0, 0.7, \
0.0, 0.0, 0.7, \
0.7, 0.0, 0.0, \
0.7, 0.0, 0.0, \
0.0, 0.7, 0.0, \
0.0, 0.7, 0.0, \
])
cube_colors_1 = array.array('f', [x/0.7 for x in cube_colors_0])
cube_colors_2 = array.array('f', \
[0.8, 0.8, 0.0, \
0.8, 0.8, 0.0, \
0.0, 0.8, 0.8, \
0.0, 0.8, 0.8, \
0.8, 0.0, 0.8, \
0.8, 0.0, 0.8, \
0.9, 0.9, 0.9, \
0.9, 0.9, 0.9 ])
color_black = (0., 0., 0.)
color_white = (1., 1., 1.)
color_red = (1., 0., 0.)
color_green = (0., 1., 0.)
color_light_green = (0., 0.5, 0.)
color_blue = (0., 0., 1.0)
color_cyan = (0., 1.0, 1.0)
color_yellow = (0.8, 0.8, 0.)
color_orange = (1., 0.5, .063)
color_gray = (0.5, 0.5, 0.5)
color_light_gray = (0.65, 0.65, 0.65)
cube_cIndices = array.array('B', \
[0, 3, 2, 1, \
2, 3, 7, 6, \
0, 4, 7, 3, \
1, 2, 6, 5, \
4, 5, 6, 7, \
0, 1, 5, 4 ])
light_cube_size_mm = 44.3
robot_body_size_mm = ( 70, 56, 30)
robot_body_offset_mm = (-30, 0, 15)
robot_head_size_mm = ( 36, 39.4, 36)
robot_head_offset_mm = ( 20, 0, 36)
lift_size_mm = ( 10, 50, 30)
lift_arm_spacing_mm = 52
lift_arm_len_mm = 66
lift_arm_diam_mm = 10
charger_bed_size_mm = (104, 98, 10 )
charger_back_size_mm = ( 5, 90, 35 )
wscale = 0.02 # millimeters to graphics window coordinates
axis_length = 100
axis_width = 1
print_camera = False
initial_fixation_point = [100, -25, 0]
initial_camera_rotation = [0, 40, 270]
initial_camera_distance = 500
fixation_point = initial_fixation_point.copy()
camera_rotation = initial_camera_rotation.copy()
camera_distance = initial_camera_distance
camera_loc = (0., 0., 0.) # will be recomputed by display()
class WorldMapViewer():
def __init__(self, robot, width=512, height=512,
windowName = "Cozmo's World",
bgcolor = (0,0,0)):
self.robot = robot
self.width = width
self.height = height
self.aspect = self.width/self.height
self.windowName = windowName
self.bgcolor = bgcolor
self.translation = [0., 0.] # Translation in mm
self.scale = 1
self.show_axes = True
self.show_memory_map = False
def make_cube(self, size=(1,1,1), highlight=False, color=None, alpha=1.0, body=True, edges=True):
"""Make a cube centered on the origin"""
glEnableClientState(GL_VERTEX_ARRAY)
if color is None:
glEnableClientState(GL_COLOR_ARRAY)
if highlight:
glColorPointer(3, GL_FLOAT, 0, cube_colors_1.tobytes())
else:
glColorPointer(3, GL_FLOAT, 0, cube_colors_0.tobytes())
else:
if not highlight:
s = 0.5 # scale down the brightness
color = (color[0]*s, color[1]*s, color[2]*s)
glColor4f(*color,alpha)
verts = cube_vertices * 1; # copy the array
for i in range(0,24,3):
verts[i ] *= size[0]
verts[i+1] *= size[1]
verts[i+2] *= size[2]
if body:
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
glVertexPointer(3, GL_FLOAT, 0, verts.tobytes())
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cube_cIndices.tobytes())
if edges:
# begin wireframe
for i in range(0,24): verts[i] *= 1.02
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
glVertexPointer(3, GL_FLOAT, 0, verts.tobytes())
glDisableClientState(GL_COLOR_ARRAY)
if body:
if highlight:
glColor4f(*color_white,1)
else:
glColor4f(*color_black,1)
else:
if highlight:
glColor4f(*color,1)
else:
s = 0.7 # scale down the brightness if necessary
glColor4f(color[0]*s, color[1]*s, color[2]*s, 1)
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cube_cIndices.tobytes())
# end wireframe
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_VERTEX_ARRAY)
def make_light_cube(self,cube_obj):
global gl_lists
lcube = cube_obj.sdk_obj
cube_number = lcube.cube_id
pos = (cube_obj.x, cube_obj.y, cube_obj.z)
color = (None, color_red, color_green, color_blue)[cube_number]
valid_pose = (lcube.pose.is_valid and cube_obj.pose_confidence >= 0) or \
self.robot.carrying is cube_obj
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslatef(*pos)
s = light_cube_size_mm
glTranslatef(0,0,4) # keep cube from projecting through the floor
if valid_pose:
t = geometry.quat2rot(*lcube.pose.rotation.q0_q1_q2_q3)
else:
t = geometry.aboutZ(cube_obj.theta)
t = t.transpose() # Transpose the matrix for sending to OpenGL
rotmat = array.array('f',t.flatten()).tobytes()
glMultMatrixf(rotmat)
if valid_pose:
# make solid cube and highlight if visible
self.make_cube((s,s,s), highlight=lcube.is_visible, color=color)
glRotatef(-90, 0., 0., 1.)
glTranslatef(-s/4, -s/4, s/2+0.5)
glScalef(0.25, 0.2, 0.25)
glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, ord(ascii(cube_number)))
else:
# make wireframe cube if coords no longer comparable
pass # self.make_cube((s,s,s), body=False, highlight=True, color=color)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_custom_cube(self,custom_obj,obst):
global gl_lists
c = glGenLists(1)
glNewList(c, GL_COMPILE)
pos = (obst.x, obst.y, obst.z)
size = obst.size
orient = obst.theta
glPushMatrix()
glTranslatef(pos[0], pos[1], max(pos[2],5))
# Transpose the pose rotation matrix for sending to OpenCV
if isinstance(custom_obj, cozmo.objects.CustomObject):
t = geometry.quat2rot(*custom_obj.pose.rotation.q0_q1_q2_q3).transpose()
else:
t = geometry.identity()
rotmat = array.array('f',t.flatten()).tobytes()
glMultMatrixf(rotmat)
comparable = True # obj.pose.origin_id == 0 or obj.pose.is_comparable(self.robot.pose)
obj_color = color_orange
highlight = custom_obj.is_visible
if comparable:
self.make_cube(size, highlight=highlight, color=obj_color)
else:
self.make_cube(size, body=False, highlight=False, color=obj_color)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_cylinder(self,radius=10,height=25, highlight=True, color=None):
if color is None:
color = (1,1,1)
if len(color) == 3:
color = (*color, 1)
if not highlight:
s = 0.5
color = (color*s, color*s, color*s, color[3])
glColor4f(*color)
quadric = gluNewQuadric()
gluQuadricOrientation(quadric, GLU_OUTSIDE)
gluCylinder(quadric, radius, radius, height, 30, 20)
glTranslatef(0, 0, height)
gluDisk(quadric, 0, radius, 30, 1)
# Draw the outline circles
if highlight:
color = (1, 1, 1, 1)
else:
color = (0, 0, 0, 1)
r = radius + 0.1
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
glColor4f(*color)
glBegin(GL_LINE_LOOP)
num_slices = 36
for i in range(num_slices):
theta = i * (360/num_slices) * (pi/180)
glVertex3f(r * cos(theta), r*sin(theta), 0.)
glEnd()
glTranslatef(0, 0, -height)
glBegin(GL_LINE_LOOP)
for i in range(num_slices):
theta = i * (360/num_slices) * (pi/180)
glVertex3f(r * cos(theta), r*sin(theta), 0.)
glEnd()
def make_chip(self,chip):
global gl_lists
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslatef(chip.x, chip.y, chip.z)
self.make_cylinder(chip.radius, chip.thickness,
color=(0,0.8,0), highlight=True)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_face(self,face):
global gl_lists
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslatef(face.x, face.y, face.z)
if face.is_visible:
color = (0.0, 1.0, 0.0, 0.9)
else:
color = (0.0, 0.5, 0.0, 0.7)
glColor4f(*color)
quadric = gluNewQuadric()
gluQuadricOrientation(quadric, GLU_OUTSIDE)
glScalef(1.0, 1.0, 2.0)
gluSphere(quadric, 100, 20, 10)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_wall(self,wall_obj):
global gl_lists
wall_spec = worldmap.wall_marker_dict[wall_obj.id]
half_length = wall_obj.length / 2
half_height = wall_obj.height / 2
door_height = wall_obj.door_height
wall_thickness = 4.0
widths = []
last_x = -half_length
edges = [ [0, -half_length, door_height/2, 1.] ]
for (center,width) in wall_spec.doorways:
left_edge = center - width/2 - half_length
edges.append([0., left_edge, door_height/2, 1.])
widths.append(left_edge - last_x)
right_edge = center + width/2 - half_length
edges.append([0., right_edge, door_height/2, 1.])
last_x = right_edge
edges.append([0., half_length, door_height/2, 1.])
widths.append(half_length-last_x)
edges = np.array(edges).T
edges = geometry.aboutZ(wall_obj.theta).dot(edges)
edges = geometry.translate(wall_obj.x,wall_obj.y).dot(edges)
c = glGenLists(1)
glNewList(c, GL_COMPILE)
if wall_obj.is_foreign:
color = color_white
else:
color = color_yellow
for i in range(0,len(widths)):
center = edges[:, 2*i : 2*i+2].mean(1).reshape(4,1)
dimensions=(wall_thickness, widths[i], wall_obj.door_height)
glPushMatrix()
glTranslatef(*center.flatten()[0:3])
glRotatef(wall_obj.theta*180/pi, 0, 0, 1)
self.make_cube(size=dimensions, color=color, highlight=True)
glPopMatrix()
# Make the transom
glPushMatrix()
transom_height = wall_obj.height - wall_obj.door_height
z = wall_obj.door_height + transom_height/2
glTranslatef(wall_obj.x, wall_obj.y, z)
glRotatef(wall_obj.theta*180/pi, 0, 0, 1)
self.make_cube(size=(wall_thickness, wall_obj.length, transom_height),
edges=False, color=color, highlight=True)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_doorway(self,doorway):
global gl_lists
wall = doorway.wall
spec = wall.doorways[doorway.index]
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslatef(doorway.x, doorway.y, wall.door_height/2)
glRotatef(doorway.theta*180/pi, 0, 0, 1)
self.make_cube(size=(1, spec[1]-10, wall.door_height-10), edges=False,
color=color_cyan, alpha=0.2, highlight=True)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_floor(self):
global gl_lists
floor_size = (2000, 2000, 1)
blip = floor_size[2]
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslatef(0., 0., -blip)
self.make_cube(floor_size, highlight=None, color=color_gray)
glTranslatef(0., 0., 2.*blip)
glColor4f(*color_light_gray,1)
for x in range(-floor_size[0]//2, floor_size[0]//2+1, 100):
glBegin(GL_LINES)
glVertex3f(x, floor_size[1]//2, 0)
glVertex3f(x, -floor_size[1]//2, 0)
glEnd()
for y in range(-floor_size[1]//2, floor_size[1]//2+1, 100):
glBegin(GL_LINES)
glVertex3f( floor_size[0]/2, y, 0)
glVertex3f(-floor_size[0]/2, y, 0)
glEnd()
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_charger(self):
charger = self.robot.world.charger
if (not charger) or (not charger.pose) or not charger.pose.is_valid: return None
comparable = charger.pose.is_comparable(self.robot.pose)
highlight = charger.is_visible or (self.robot.is_on_charger and comparable)
global gl_lists
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
p = charger.pose.position.x_y_z
glTranslatef(*p)
glRotatef(charger.pose.rotation.angle_z.degrees, 0, 0, 1)
glTranslatef(charger_bed_size_mm[0]/2,
0,
charger_bed_size_mm[2]/2)
glRotatef(180, 0, 0, 1) # charger "front" is opposite robot "front"
if comparable:
self.make_cube(charger_bed_size_mm, highlight=highlight)
else:
self.make_cube(charger_bed_size_mm, body=False, \
highlight=False, color=color_white)
glTranslatef(
(charger_back_size_mm[0]-charger_bed_size_mm[0])/2,
0,
charger_back_size_mm[2]/2)
if comparable:
self.make_cube(charger_back_size_mm, highlight=highlight)
else:
self.make_cube(charger_back_size_mm, body=False, \
highlight=True, color=color_white)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_custom_marker(self,marker):
self.make_aruco_marker(marker)
def make_aruco_marker(self,marker):
global gl_lists
marker_number = marker.marker_number
s = light_cube_size_mm
pos = (marker.x, marker.y, marker.z)
color = (color_red, color_green, color_blue)[marker_number%3]
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslatef(*pos)
glRotatef(marker.theta*180/pi+180, 0., 0., 1.)
highlight = marker.is_visible
marker_thickness = 5 # must be thicker than wall
self.make_cube((marker_thickness,s,s), color=color, highlight=highlight)
glRotatef(-90, 0., 0., 1.)
glRotatef(90, 1., 0., 0.)
length = len(ascii(marker_number)) + 0.5
glTranslatef(-s/4*length, -s/4, marker_thickness)
glScalef(0.25, 0.2, 0.25)
glutStrokeString(GLUT_STROKE_MONO_ROMAN, c_char_p(bytes(ascii(marker_number),'utf8')))
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_foreign_cube(self,cube_obj):
global gl_lists
cube_number = cube_obj.id
pos = (cube_obj.x, cube_obj.y, cube_obj.z)
color = color_white
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslatef(*pos)
# Transpose the matrix for sending to OpenCV
s = light_cube_size_mm
self.make_cube((s,s,s), color=color)
glRotatef(-90, 0., 0., 1.)
glTranslatef(-s/4, -s/4, s/2+0.5)
glScalef(0.25, 0.2, 0.25)
glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, ord(ascii(cube_number)))
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_eye(self,size=(1,1,1), highlight=False, color=None, body=True, edges=True):
glEnableClientState(GL_VERTEX_ARRAY)
if color is None:
glEnableClientState(GL_COLOR_ARRAY)
if highlight:
glColorPointer(3, GL_FLOAT, 0, cube_colors_1.tobytes())
else:
glColorPointer(3, GL_FLOAT, 0, cube_colors_0.tobytes())
else:
if not highlight:
s = 0.5 # scale down the brightness if necessary
color = (color[0]*s, color[1]*s, color[2]*s)
glColor4f(*color,1)
verts = camera_vertices* 1; # copy the array
for i in range(0,24,3):
verts[i ] *= size[0]
verts[i+1] *= size[1]
verts[i+2] *= size[2]
if body:
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
glVertexPointer(3, GL_FLOAT, 0, verts.tobytes())
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cube_cIndices.tobytes())
if edges:
# begin wireframe
for i in range(0,24): verts[i] *= 1.02
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
glVertexPointer(3, GL_FLOAT, 0, verts.tobytes())
glDisableClientState(GL_COLOR_ARRAY)
if body:
if highlight:
glColor4f(*color_white,1)
else:
glColor4f(*color_black,1)
else:
if highlight:
glColor4f(*color,1)
else:
s = 0.7 # scale down the brightness if necessary
glColor4f(color[0]*s, color[1]*s, color[2]*s, 1)
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cube_cIndices.tobytes())
# end wireframe
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_VERTEX_ARRAY)
def make_camera(self,cameraobj):
global gl_lists, cap, aruco_dict, parameters, F
camera_number = cameraobj.id
pos = (cameraobj.x, cameraobj.y, cameraobj.z)
color = (color_orange, color_red, color_green, color_blue)[camera_number%4]
valid_pose = (cameraobj.x, cameraobj.y, cameraobj.z)
angle = cameraobj.theta
phi = cameraobj.phi
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslatef(*pos)
# Transpose the matrix for sending to OpenCV
t = geometry.quat2rot(cos(phi/2),0,0,sin(phi/2)).transpose()
rotmat = array.array('f',t.flatten()).tobytes()
glMultMatrixf(rotmat)
t = geometry.quat2rot( cos(-angle/2 + pi/4) ,0 ,sin(-angle/2 + pi/4) ,0 ).transpose()
rotmat = array.array('f',t.flatten()).tobytes()
glMultMatrixf(rotmat)
s = light_cube_size_mm
self.make_eye((s,s,s), color=color)
glRotatef(-90, 0., 0., 1.)
glTranslatef(-s/4, -s/4, s/2+0.5)
glScalef(0.25, 0.2, 0.25)
glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, ord(ascii(camera_number%4)))
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_foreign_robot(self,obj):
global gl_lists
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
# Draw the body
p = (obj.x, obj.y, obj.z)
color = (color_orange, color_red, color_green, color_blue)[obj.camera_id%4]
glTranslatef(*p)
glTranslatef(*robot_body_offset_mm)
glRotatef(obj.theta*180/pi, 0, 0, 1)
self.make_cube(robot_body_size_mm, color=color_white)
# Draw the head
glPushMatrix()
glTranslatef(*robot_head_offset_mm)
glRotatef(-self.robot.head_angle.degrees, 0, 1, 0)
self.make_cube(robot_head_size_mm, color=color_white)
glTranslatef(*( 0, 0, 36))
glScalef(0.25, 0.2, 0.25)
glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, ord(ascii(obj.cozmo_id%9)))
glPopMatrix()
# Draw the lift
glTranslatef(-robot_body_offset_mm[0], -robot_body_offset_mm[1], -robot_body_offset_mm[2])
glPushMatrix()
self.robot.kine.get_pose()
lift_tran = self.robot.kine.joint_to_base('lift_attach')
lift_pt = geometry.point(0, 0, 0)
lift_point = self.tran_to_tuple(lift_tran.dot(lift_pt))
glTranslatef(*lift_point)
self.make_cube(lift_size_mm, color=color)
glPopMatrix()
# Draw the lift arms
glPushMatrix()
lift_pt = geometry.point(0, 0, lift_arm_spacing_mm / 2)
lift_point = self.tran_to_tuple(lift_tran.dot(lift_pt))
shoulder_tran = self.robot.kine.joint_to_base('shoulder')
shoulder_pt = geometry.point(0, 0, lift_arm_spacing_mm / 2)
shoulder_point = self.tran_to_tuple(shoulder_tran.dot(shoulder_pt));
arm_point = ((shoulder_point[0] + lift_point[0]) / 2,
(shoulder_point[1] + lift_point[1]) / 2,
(shoulder_point[2] + lift_point[2]) / 2)
arm_angle = atan2(lift_point[2] - shoulder_point[2],
lift_point[0] - shoulder_point[0])
glTranslatef(*arm_point)
glRotatef(-(180 * arm_angle / pi), 0, 1, 0)
self.make_cube((lift_arm_len_mm, lift_arm_diam_mm, lift_arm_diam_mm), color=color_white)
glTranslatef(0, lift_arm_spacing_mm, 0)
self.make_cube((lift_arm_len_mm, lift_arm_diam_mm, lift_arm_diam_mm), color=color_white)
glPopMatrix()
glPopMatrix()
glEndList()
gl_lists.append(c)
@staticmethod
def tran_to_tuple(tran):
return (tran[0][0], tran[1][0], tran[2][0])
def make_cozmo_robot(self):
global gl_lists
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
# Draw the body
cur_pose = self.robot.world.particle_filter.pose
p = (cur_pose[0], cur_pose[1], self.robot.pose.position.z)
glTranslatef(*p)
glTranslatef(*robot_body_offset_mm)
glRotatef(cur_pose[2]*180/pi, 0, 0, 1)
self.make_cube(robot_body_size_mm, highlight=self.robot.is_on_charger)
# Draw the head
glPushMatrix()
glTranslatef(*robot_head_offset_mm)
glRotatef(-self.robot.head_angle.degrees, 0, 1, 0)
self.make_cube(robot_head_size_mm, highlight=self.robot.is_on_charger)
glPopMatrix()
# Draw the lift
glTranslatef(-robot_body_offset_mm[0], -robot_body_offset_mm[1], -robot_body_offset_mm[2])
glPushMatrix()
self.robot.kine.get_pose()
lift_tran = self.robot.kine.joint_to_base('lift_attach')
lift_pt = geometry.point(0, 0, 0)
lift_point = self.tran_to_tuple(lift_tran.dot(lift_pt))
glTranslatef(*lift_point)
self.make_cube(lift_size_mm, highlight=self.robot.is_on_charger)
glPopMatrix()
# Draw the lift arms
glPushMatrix()
lift_pt = geometry.point(0, 0, lift_arm_spacing_mm / 2)
lift_point = self.tran_to_tuple(lift_tran.dot(lift_pt))
shoulder_tran = self.robot.kine.joint_to_base('shoulder')
shoulder_pt = geometry.point(0, 0, lift_arm_spacing_mm / 2)
shoulder_point = self.tran_to_tuple(shoulder_tran.dot(shoulder_pt));
arm_point = ((shoulder_point[0] + lift_point[0]) / 2,
(shoulder_point[1] + lift_point[1]) / 2,
(shoulder_point[2] + lift_point[2]) / 2)
arm_angle = atan2(lift_point[2] - shoulder_point[2],
lift_point[0] - shoulder_point[0])
glTranslatef(*arm_point)
glRotatef(-(180 * arm_angle / pi), 0, 1, 0)
self.make_cube((lift_arm_len_mm, lift_arm_diam_mm, lift_arm_diam_mm),
highlight=self.robot.is_on_charger)
glTranslatef(0, lift_arm_spacing_mm, 0)
self.make_cube((lift_arm_len_mm, lift_arm_diam_mm, lift_arm_diam_mm),
highlight=self.robot.is_on_charger)
glPopMatrix()
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_axes(self):
global gl_lists
if not self.show_axes: return None
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
len = axis_length
w = axis_width
glTranslatef(len/2., 0., 0.)
self.make_cube((len,w,w), highlight=True, color=color_red, edges=False)
glPopMatrix()
glPushMatrix()
glTranslatef(0., len/2., 0.)
self.make_cube((w,len,w), highlight=True, color=color_green, edges=False)
glPopMatrix()
glPushMatrix()
glTranslatef(0., 0., len/2.)
self.make_cube((w,w,len), highlight=True, color=color_blue, edges=False)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_gazepoint(self):
global gl_lists
c = glGenLists(1)
glNewList(c, GL_COMPILE)
glPushMatrix()
glTranslate(fixation_point[0], fixation_point[1], fixation_point[2])
s = 3.
self.make_cube((s,s,s), highlight=True, color=(1.0, 0.9, 0.1), edges=False)
glPopMatrix()
glEndList()
gl_lists.append(c)
def make_objects(self):
if self.robot.use_shared_map:
items = tuple(self.robot.world.world_map.shared_objects.items())
else:
items = tuple(self.robot.world.world_map.objects.items())
for (key,obj) in items:
if isinstance(obj, worldmap.LightCubeObj):
self.make_light_cube(obj)
elif isinstance(obj, worldmap.CustomCubeObj):
self.make_custom_cube(key,obj)
elif isinstance(obj, worldmap.WallObj):
self.make_wall(obj)
elif isinstance(obj, worldmap.DoorwayObj):
pass # doorways must come last, due to transparency
elif isinstance(obj, worldmap.ChipObj):
self.make_chip(obj)
elif isinstance(obj, worldmap.FaceObj):
self.make_face(obj)
elif isinstance(obj, worldmap.CameraObj):
self.make_camera(obj)
elif isinstance(obj, worldmap.RobotForeignObj):
self.make_foreign_robot(obj)
elif isinstance(obj, worldmap.LightCubeForeignObj):
self.make_foreign_cube(obj)
elif isinstance(obj, worldmap.CustomMarkerObj):
self.make_custom_marker(obj)
elif isinstance(obj, worldmap.ArucoMarkerObj):
self.make_aruco_marker(obj)
# Make the doorways last, so transparency works correctly
for (key,obj) in items:
if isinstance(obj, worldmap.DoorwayObj):
self.make_doorway(obj)
def make_memory(self):
global gl_lists
quadtree = self.robot.world.nav_memory_map
if quadtree and self.show_memory_map:
c = glGenLists(1)
glNewList(c, GL_COMPILE)
self.memory_tree_crawl(quadtree.root_node, 0)
glEndList()
gl_lists.append(c)
def memory_tree_crawl(self, node, depth):
if node.content == NodeContentTypes.ClearOfObstacle:
obj_color = color_green
elif node.content == NodeContentTypes.ClearOfCliff:
obj_color = color_light_green
elif node.content == NodeContentTypes.ObstacleCube:
obj_color = color_orange
elif node.content == NodeContentTypes.ObstacleCharger:
obj_color = color_blue
elif node.content == NodeContentTypes.VisionBorder:
obj_color = color_cyan
elif node.content == NodeContentTypes.Cliff:
obj_color = color_red
else:
obj_color = color_light_gray
glPushMatrix()
p = (node.center.x, node.center.y, depth)
glTranslatef(*p)
obj_size = (node.size, node.size, 1)
self.make_cube(obj_size, highlight=False, color=obj_color)
glPopMatrix()
if node.children is not None:
for child in node.children:
self.memory_tree_crawl(child,depth+1)
def make_shapes(self):
global gl_lists
gl_lists = []
self.make_axes()
self.make_gazepoint()
self.make_charger()
self.make_cozmo_robot()
self.make_memory()
self.make_floor()
self.make_objects() # walls, light cubes, custom cubes, and chips
def del_shapes(self):
global gl_lists
for id in gl_lists:
glDeleteLists(id,1)
# ================ Window Setup ================
def window_creator(self):
global WINDOW
WINDOW = opengl.create_window(bytes(self.windowName,'utf-8'), (self.width,self.height))
glutDisplayFunc(self.display)
glutReshapeFunc(self.reshape)
glutKeyboardFunc(self.keyPressed)
glutSpecialFunc(self.specialKeyPressed)
glViewport(0,0,self.width,self.height)
glClearColor(*self.bgcolor, 0)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)
# Enable transparency for doorways: see
# https://www.opengl.org/archives/resources/faq/technical/transparency.htm
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
def start(self): # Displays in background
self.robot.world.request_nav_memory_map(1)
if not WINDOW:
opengl.init()
opengl.CREATION_QUEUE.append(self.window_creator)
if pf.system() == 'Darwin':
print("Type 'option' + 'h' in the world map window for help.")
else:
print("Type 'h' in the world map window for help.")
def display(self):
global DISPLAY_ENABLED, EXCEPTION_COUNTER
if not DISPLAY_ENABLED: return
global gl_lists
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
field_of_view = 50 # degrees
near_clip = 5
far_clip = 600 # 20.0
gluPerspective(field_of_view, self.aspect, near_clip, far_clip)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
wscale = 0.1
rotmat = array.array('f',[
wscale, 0, 0, 0,
0, wscale, 0, 0,
0, 0, wscale, 0,
0, 0, 0, 1]).tobytes()
glMultMatrixf(rotmat)
# Model transformation switches to robot coordinates: z is up, x forward, y left.
# View transformation moves the camera, keeping it pointed at the fixation point.
# Keyboard commands: translations move the fixation point, rotations orbit the camera.
pitch = camera_rotation[1]
yaw = camera_rotation[2]
global camera_loc
camera_loc = [
camera_distance * cos(radians(yaw)) + fixation_point[0],
camera_distance * sin(radians(yaw)) + fixation_point[1],
camera_distance * sin(radians(pitch)) + fixation_point[2]
]
gluLookAt(*camera_loc, *fixation_point, 0.0, 0.0, 1.0)
try:
self.make_shapes()
for id in gl_lists:
glCallList(id)
glutSwapBuffers()
self.del_shapes()
except Exception as e:
print('Worldmap viewer exception:',e)
EXCEPTION_COUNTER += 1
if EXCEPTION_COUNTER >= 2:
print('\n\nworldmap_viewer: Too many errors. Stopping redisplay.')
DISPLAY_ENABLED = False
else:
raise
def keyPressed(self, key, x, y):
global DISPLAY_ENABLED, EXCEPTION_COUNTER
if ord(key) == 27:
print("Use 'exit' to quit.")
#return
global fixation_point, camera_rotation, camera_distance, print_camera
heading = atan2(camera_loc[1]-fixation_point[1], camera_loc[0]-fixation_point[0])*180/pi
translate_step = 5
if key == b'a':
fixation_point[0] -= translate_step * cos(radians(heading+90))
fixation_point[1] -= translate_step * sin(radians(heading+90))
elif key == b'd':
fixation_point[0] += translate_step * cos(radians(heading+90))
fixation_point[1] += translate_step * sin(radians(heading+90))
elif key == b'w':
fixation_point[0] -= translate_step * cos(radians(heading))
fixation_point[1] -= translate_step * sin(radians(heading))
elif key == b's':
fixation_point[0] += translate_step * cos(radians(heading))
fixation_point[1] += translate_step * sin(radians(heading))
elif key == b'>':
camera_distance += translate_step
elif key == b'<':
camera_distance -= translate_step
elif key == b'j':
camera_rotation[2] -= 2.5
elif key == b'l':
camera_rotation[2] += 2.5
elif key == b'k':
camera_rotation[1] -= 2.5
elif key == b'i':
camera_rotation[1] += 2.5
elif key == b'x':
self.show_axes = not self.show_axes
elif key == b'm':
self.show_memory_map = not self.show_memory_map
elif key == b'h':
if pf.system() == 'Darwin':
print(help_text_mac)
else:
print(help_text)
elif key == b'v':
print_camera = not print_camera
if not print_camera:
print("Halted viewing parameters display. Press 'v' again to resume.")
elif key == b'z':
fixation_point = initial_fixation_point.copy()
camera_rotation = initial_camera_rotation.copy()
camera_distance = initial_camera_distance
elif key == b'#':
DISPLAY_ENABLED = not DISPLAY_ENABLED
if DISPLAY_ENABLED:
EXCEPTION_COUNTER = 0
print('Worldmap viewer redisplay %sabled.' %
'en' if DISPLAY_ENABLED else 'dis')
if print_camera:
pitch = camera_rotation[1]
yaw = camera_rotation[2]
print('pitch=%5.1f yaw=%5.1f dist=%f' % (pitch,yaw,camera_distance),
' gazepointt[%5.1f %5.1f %5.1f]' %
(fixation_point[0], fixation_point[1], fixation_point[2]),
' camera[%5.1f %5.1f %5.1f]' % (camera_loc[0], camera_loc[1], camera_loc[2]))
self.display()
def specialKeyPressed(self, key, x, y):
global fixation_point, camera_rotation, camera_distance
heading = -camera_rotation[1]
if key == GLUT_KEY_LEFT:
camera_rotation[2] = (camera_rotation[2] - 2.5) % 360
elif key == GLUT_KEY_RIGHT:
camera_rotation[2] = (camera_rotation[2] + 2.5) % 360
elif key == GLUT_KEY_UP:
camera_rotation[1] = (camera_rotation[1] + 90 + 2.5) % 180 - 90
elif key == GLUT_KEY_DOWN:
camera_rotation[1] = (camera_rotation[1] + 90 - 2.5) % 180 - 90
elif key == GLUT_KEY_PAGE_UP:
fixation_point[2] += 1
elif key == GLUT_KEY_PAGE_DOWN:
fixation_point[2] -= 1
self.display()
def reshape(self, width, height):
self.width = width
self.height = height
self.aspect = self.width/self.height
glViewport(0, 0, width, height)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,013
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/PF_Cube.py
|
from cozmo_fsm import *
from cozmo.util import degrees, Pose
class PF_Cube(StateMachineProgram):
def __init__(self):
landmarks = {
cube1 : Pose( 55, 160, 0, angle_z=degrees(90)),
cube2 : Pose(160, 55, 0, angle_z=degrees( 0)),
cube3 : Pose(160, -55, 0, angle_z=degrees( 0))
}
pf = ParticleFilter(robot,
landmarks = landmarks,
sensor_model = CubeSensorModel(robot))
super().__init__(particle_filter=pf, particle_viewer=True)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,014
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/sim_robot.py
|
"""
Create a dummy robot and world so we can use cozmo-tools
classes without having to connect to a real robot.
"""
import asyncio
try:
import cv2
ARUCO_DICT_4x4_100 = cv2.aruco.DICT_4X4_100
except:
ARUCO_DICT_4x4_100 = None
import cozmo
from cozmo.util import Distance, Angle, Pose
from .cozmo_kin import CozmoKinematics
from .evbase import EventRouter
from .aruco import Aruco
from .particle import SLAMParticleFilter
from .rrt import RRT, RRTNode
from .worldmap import WorldMap
class SimWorld():
def __init__(self):
self.path_viewer = None
self.particle_viewer = None
self.worldmap_viewer = None
class SimServer():
def __init__(self):
self.started = False
class SimRobot():
def __init__(self, run_in_cloud=False):
robot = self
robot.loop = asyncio.get_event_loop()
if not run_in_cloud:
robot.erouter = EventRouter()
robot.erouter.robot = robot
robot.erouter.start()
robot.head_angle = Angle(radians=0)
robot.shoulder_angle = Angle(radians=0)
robot.lift_height = Distance(distance_mm=0)
robot.pose = Pose(0,0,0,angle_z=Angle(degrees=0))
robot.camera = None
robot.carrying = None
robot.world = SimWorld()
robot.world.aruco = Aruco(robot, ARUCO_DICT_4x4_100)
robot.world.light_cubes = dict()
robot.world._faces = dict()
robot.world.charger = None
robot.world.server = SimServer()
robot.world.path_viewer = None
robot.world.particle_filter = SLAMParticleFilter(robot)
robot.kine = CozmoKinematics(robot) # depends on particle filter
robot.world.rrt = RRT(robot) # depends on kine
robot.world.world_map = WorldMap(robot)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,015
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/TapSpeak.py
|
"""
The TapSpeak demo shows Cozmo responding to cube tap events. A
TapTrans transition is used to set up a handler for taps. The
example also illustrates how the TapTrans transition does wildcard
matching if not given an argument. By passing a cube as an argument
to the TapTrans constructor can use it to look for taps on a
specific cube.
Behavior: Cozmo starts out by saying 'Tap a cube'. Then, every time
a cube is tapped, Cozmo says the cube name and goes back to
listening for more tap events.
"""
from cozmo_fsm import *
from cozmo_fsm import *
class SayCube(Say):
"""Say the name of a cube."""
def start(self, event=None, \
cube_names = ['paperclip', 'anglepoise lamp', 'deli slicer']):
cube_number = next(k for k,v in self.robot.world.light_cubes.items() \
if v == event.source)
self.text = cube_names[cube_number-1]
super().start(event)
class TapSpeak(StateMachineProgram):
def setup(self):
"""
intro: Say('Tap a cube.') =C=> wait
wait: StateNode() =Tap()=> speak
speak: SayCube() =C=> wait
"""
# Code generated by genfsm on Mon Feb 17 03:16:53 2020:
intro = Say('Tap a cube.') .set_name("intro") .set_parent(self)
wait = StateNode() .set_name("wait") .set_parent(self)
speak = SayCube() .set_name("speak") .set_parent(self)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(intro) .add_destinations(wait)
taptrans1 = TapTrans() .set_name("taptrans1")
taptrans1 .add_sources(wait) .add_destinations(speak)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(speak) .add_destinations(wait)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,016
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/particle.py
|
"""
Particle filter localization.
"""
import math, array, random
from math import pi, sqrt, sin, cos, atan2, exp
import numpy as np
try: import cv2
except: pass
import cozmo
from cozmo.util import Pose
from .geometry import wrap_angle, wrap_selected_angles, tprint, rotation_matrix_to_euler_angles
from .aruco import ArucoMarker
from .cozmo_kin import center_of_rotation_offset
from .worldmap import WorldObject, WallObj, wall_marker_dict, ArucoMarkerObj
from .perched import Cam
class Particle():
def __init__(self, index=-1):
self.x = 0
self.y = 0
self.theta = 0
self.log_weight = 0
self.weight = 1
self.index = index
def __repr__(self):
return '<Particle %d: (%.2f, %.2f) %.1f deg. log_wt=%f>' % \
(self.index, self.x, self.y, self.theta*80/pi, self.log_weight)
#================ Particle Initializers ================
class ParticleInitializer():
def __init__(self):
self.pf = None # must be filled in after creation
class RandomWithinRadius(ParticleInitializer):
""" Normally distribute particles within a radius, with random heading. """
def __init__(self,radius=200):
super().__init__()
self.radius = radius
def initialize(self, robot):
for p in self.pf.particles:
qangle = random.random()*2*pi
r = random.gauss(0, self.radius/2) + self.radius/1.5
p.x = r * cos(qangle)
p.y = r * sin(qangle)
p.theta = random.random()*2*pi
p.log_weight = 0.0
p.weight = 1.0
self.pf.pose = (0, 0, 0)
self.pf.motion_model.old_pose = robot.pose
class RobotPosition(ParticleInitializer):
""" Initialize all particles to the robot's current position or a constant;
the motion model will jitter them. """
def __init__(self, x=None, y=None, theta=None):
super().__init__()
self.x = x
self.y = y
self.theta = theta
def initialize(self, robot):
if self.x is None:
x = robot.pose.position.x
y = robot.pose.position.y
theta = robot.pose.rotation.angle_z.radians
else:
x = self.x
y = self.y
theta = self.theta
for p in self.pf.particles:
p.x = x
p.y = y
p.theta = theta
p.log_weight = 0.0
p.weight = 1.0
self.pf.pose = (x, y, theta)
self.pf.motion_model.old_pose = robot.pose
#================ Motion Model ================
class MotionModel():
def __init__(self, robot):
self.robot = robot
class DefaultMotionModel(MotionModel):
def __init__(self, robot, sigma_trans=0.1, sigma_rot=0.01):
super().__init__(robot)
self.sigma_trans = sigma_trans
self.sigma_rot = sigma_rot
self.old_pose = robot.pose
def move(self, particles):
old_pose = self.old_pose
new_pose = self.robot.pose
self.old_pose = new_pose
if not new_pose.is_comparable(old_pose):
return # can't path integrate if the robot switched reference frames
old_xyz = old_pose.position.x_y_z
new_xyz = new_pose.position.x_y_z
old_hdg = old_pose.rotation.angle_z.radians
new_hdg = new_pose.rotation.angle_z.radians
turn_angle = wrap_angle(new_hdg - old_hdg)
cor = center_of_rotation_offset
old_rx = old_xyz[0] + cor * cos(old_hdg)
old_ry = old_xyz[1] + cor * sin(old_hdg)
new_rx = new_xyz[0] + cor * cos(new_hdg)
new_ry = new_xyz[1] + cor * sin(new_hdg)
dist = sqrt((new_rx-old_rx)**2 + (new_ry-old_ry)**2)
# Did we drive forward, or was it backward?
fwd_xy = (old_xyz[0] + dist * cos(old_hdg+turn_angle/2),
old_xyz[1] + dist * sin(old_hdg+turn_angle/2))
rev_xy = (old_xyz[0] - dist * cos(old_hdg+turn_angle/2),
old_xyz[1] - dist * sin(old_hdg+turn_angle/2))
fwd_dx = fwd_xy[0] - new_xyz[0]
fwd_dy = fwd_xy[1] - new_xyz[1]
rev_dx = rev_xy[0] - new_xyz[0]
rev_dy = rev_xy[1] - new_xyz[1]
if (fwd_dx*fwd_dx + fwd_dy*fwd_dy) > (rev_dx*rev_dx + rev_dy*rev_dy):
dist = - dist # we drove backward
rot_var = 0 if abs(turn_angle) < 0.001 else self.sigma_rot
for p in particles:
pdist = dist * (1 + random.gauss(0, self.sigma_trans))
pturn = random.gauss(turn_angle, rot_var)
# Correct for the center of rotation being behind the base frame
# (xc,yc) is the center of rotation
xc = p.x + cor * cos(p.theta)
yc = p.y + cor * sin(p.theta)
# Make half the turn, translate, then complete the turn
p.theta = p.theta + pturn/2
p.x = xc + cos(p.theta) * pdist
p.y = yc + sin(p.theta) * pdist
p.theta = wrap_angle(p.theta + pturn/2)
# Move from center of rotation back to (rotated) base frame
p.x = p.x - cor * cos(p.theta)
p.y = p.y - cor * sin(p.theta)
#================ Sensor Model ================
class SensorModel():
def __init__(self, robot, landmarks=None):
self.robot = robot
if landmarks is None:
landmarks = dict()
self.set_landmarks(landmarks)
self.last_evaluate_pose = robot.pose
def set_landmarks(self,landmarks):
self.landmarks = landmarks
def compute_robot_motion(self):
# How much did we move since last evaluation?
if self.robot.pose.is_comparable(self.last_evaluate_pose):
dx = self.robot.pose.position.x - self.last_evaluate_pose.position.x
dy = self.robot.pose.position.y - self.last_evaluate_pose.position.y
dist = sqrt(dx*dx + dy*dy)
turn_angle = wrap_angle(self.robot.pose.rotation.angle_z.radians -
self.last_evaluate_pose.rotation.angle_z.radians)
else:
dist = 0
turn_angle = 0
print('** Robot origin_id changed from', self.last_evaluate_pose.origin_id,
'to', self.robot.pose.origin_id)
self.last_evaluate_pose = self.robot.pose
return (dist,turn_angle)
class ArucoDistanceSensorModel(SensorModel):
"""Sensor model using only landmark distances."""
def __init__(self, robot, landmarks=None, distance_variance=100):
if landmarks is None:
landmarks = dict()
super().__init__(robot,landmarks)
self.distance_variance = distance_variance
def evaluate(self,particles,force=False):
# Returns true if particles were evaluated.
# Called with force=True from particle_viewer to force evaluation.
# Only evaluate if the robot moved enough for evaluation to be worthwhile.
(dist,turn_angle) = self.compute_robot_motion()
if (not force) and (dist < 5) and abs(turn_angle) < math.radians(5):
return False
self.last_evaluate_pose = self.robot.pose
# Cache seen_marker_objects because vision is in another thread.
seen_marker_objects = self.robot.world.aruco.seen_marker_objects
# Process each seen marker:
for (id, marker) in seen_marker_objects.items():
if marker.id_string in self.landmarks:
sensor_dist = marker.camera_distance
landmark_spec = self.landmarks[marker.id_string]
lm_x = landmark_spec.position.x
lm_y = landmark_spec.position.y
for p in particles:
dx = lm_x - p.x
dy = lm_y - p.y
predicted_dist = sqrt(dx*dx + dy*dy)
error = sensor_dist - predicted_dist
p.log_weight -= (error*error)/self.distance_variance
return True
class ArucoBearingSensorModel(SensorModel):
"""Sensor model using only landmark bearings."""
def __init__(self, robot, landmarks=None, bearing_variance=0.1):
if landmarks is None:
landmarks = dict()
super().__init__(robot,landmarks)
self.bearing_variance = bearing_variance
def evaluate(self,particles,force=False):
# Returns true if particles were evaluated.
# Called with force=True from particle_viewer to force evaluation.
# Only evaluate if the robot moved enough for evaluation to be worthwhile.
(dist,turn_angle) = self.compute_robot_motion()
if not force and dist < 5 and abs(turn_angle) < math.radians(5):
return False
self.last_evaluate_pose = self.robot.pose
# Cache seen_marker_objects because vision is in another thread.
seen_marker_objects = self.robot.world.aruco.seen_marker_objects
# Process each seen marker:
for id in seen_marker_objects:
marker_id = 'Aruco-' + str(id)
if marker_id in self.landmarks:
sensor_coords = seen_marker_objects[id].camera_coords
sensor_bearing = atan2(sensor_coords[0], sensor_coords[2])
landmark_spec = self.landmarks[marker_id]
lm_x = landmark_spec.position.x
lm_y = landmark_spec.position.y
for p in particles:
dx = lm_x - p.x
dy = lm_y - p.y
predicted_bearing = wrap_angle(atan2(dy,dx) - p.theta)
error = wrap_angle(sensor_bearing - predicted_bearing)
p.log_weight -= (error * error) / self.bearing_variance
return True
class ArucoCombinedSensorModel(SensorModel):
"""Sensor model using combined distance and bearing information."""
def __init__(self, robot, landmarks=None, distance_variance=200):
if landmarks is None:
landmarks = dict()
super().__init__(robot,landmarks)
self.distance_variance = distance_variance
def evaluate(self,particles,force=False):
# Returns true if particles were evaluated.
# Called with force=True from particle_viewer to force evaluation.
# Don't evaluate if robot is still moving; ArUco info will be bad.
if self.robot.is_moving:
return False
# Only evaluate if the robot moved enough for evaluation to be worthwhile.
(dist,turn_angle) = self.compute_robot_motion()
if not force and dist < 5 and abs(turn_angle) < math.radians(5):
return False
self.last_evaluate_pose = self.robot.pose
# Cache seen_marker_objects because vision is in another thread.
seen_marker_objects = self.robot.world.aruco.seen_marker_objects
# Process each seen marker:
for id in seen_marker_objects:
marker_id = 'Aruco-' + str(id)
if marker_id in self.landmarks:
sensor_dist = seen_marker_objects[id].camera_distance
sensor_coords = seen_marker_objects[id].camera_coords
sensor_bearing = atan2(sensor_coords[0], sensor_coords[2])
landmark_spec = self.landmarks[marker_id]
lm_x = landmark_spec.position.x
lm_y = landmark_spec.position.y
for p in particles:
# Use sensed bearing and distance to get particle's
# estimate of landmark position on the world map.
predicted_pos_x = p.x + sensor_dist * cos(p.theta + sensor_bearing)
predicted_pos_y = p.y + sensor_dist * sin(p.theta + sensor_bearing)
dx = lm_x - predicted_pos_x
dy = lm_y - predicted_pos_y
error_sq = dx*dx + dy*dy
p.log_weight -= error_sq / self.distance_variance
return True
class CubeOrientSensorModel(SensorModel):
"""Sensor model using only orientation information."""
def __init__(self, robot, landmarks=None, distance_variance=200):
if landmarks is None:
landmarks = dict()
super().__init__(robot,landmarks)
self.distance_variance = distance_variance
def evaluate(self,particles,force=False):
# Returns true if particles were evaluated.
# Called with force=True from particle_viewer to force evaluation.
# Only evaluate if the robot moved enough for evaluation to be worthwhile.
(dist,turn_angle) = self.compute_robot_motion()
if not force and dist < 5 and abs(turn_angle) < math.radians(5):
return False
self.last_evaluate_pose = self.robot.pose
seenCubes = [cube for cube in self.robot.world.light_cubes.values()
if cube.is_visible]
# Process each seen cube if it's a landmark:
for cube in seenCubes:
if cube in self.landmarks:
sensor_dx = cube.pose.position.x - self.robot.pose.position.x
sensor_dy = cube.pose.position.y - self.robot.pose.position.y
sensor_dist = sqrt(sensor_dx*sensor_dx + sensor_dy*sensor_dy)
angle = atan2(sensor_dy,sensor_dx)
sensor_bearing = \
wrap_angle(angle - self.robot.pose.rotation.angle_z.radians)
#sensor_orient = wrap_angle(robot.pose.rotation.angle_z.radians -
# cube.pose.rotation.angle_z.radians +
# sensor_bearing)
# simplifies to...
sensor_orient = wrap_angle(angle - cube.pose.rotation.angle_z.radians)
landmark_spec = self.landmarks[cube]
lm_x = landmark_spec.position.x
lm_y = landmark_spec.position.y
lm_orient = landmark_spec.rotation.angle_z.radians
for p in particles:
# ... Orientation error:
#predicted_bearing = wrap_angle(atan2(lm_y-p.y, lm_x-p.x) - p.theta)
#predicted_orient = wrap_angle(p.theta - lm_orient + predicted_bearing)
# simplifies to...
predicted_orient = wrap_angle(atan2(lm_y-p.y, lm_x-p.x) - lm_orient)
error_sq = ((predicted_orient - sensor_orient)*sensor_dist)**2
p.log_weight -= error_sq / self.distance_variance
return True
class CubeSensorModel(SensorModel):
"""Sensor model using combined distance, bearing, and orientation information."""
def __init__(self, robot, landmarksNone, distance_variance=200):
if landmarks is None:
landmarks = dict()
super().__init__(robot,landmarks)
self.distance_variance = distance_variance
def evaluate(self,particles,force=False):
# Returns true if particles were evaluated.
# Called with force=True from particle_viewer to force evaluation.
# Only evaluate if the robot moved enough for evaluation to be worthwhile.
(dist,turn_angle) = self.compute_robot_motion()
if not force and dist < 5 and abs(turn_angle) < math.radians(5):
return False
self.last_evaluate_pose = self.robot.pose
seenCubes = [cube for cube in world.light_cubes.values() if cube.is_visible]
# Process each seen cube if it's a landmark:
for cube in seenCubes:
cube_id = 'Cube-' + cube.cube_id
if cube_id in self.landmarks:
sensor_dx = cube.pose.position.x - robot.pose.position.x
sensor_dy = cube.pose.position.y - robot.pose.position.y
sensor_dist = sqrt(sensor_dx*sensor_dx + sensor_dy*sensor_dy)
angle = atan2(sensor_dy,sensor_dx)
sensor_bearing = wrap_angle(angle - robot.pose.rotation.angle_z.radians)
#sensor_orient = wrap_angle(robot.pose.rotation.angle_z.radians -
# cube.pose.rotation.angle_z.radians +
# sensor_bearing)
# simplifies to...
sensor_orient = wrap_angle(angle - cube.pose.rotation.angle_z.radians)
landmark_spec = self.landmarks[cube_id]
lm_x = landmark_spec.position.x
lm_y = landmark_spec.position.y
lm_orient = landmark_spec.rotation.angle_z.radians
for p in particles:
# ... Bearing and distance errror:
# Use sensed bearing and distance to get particle's
# prediction of landmark position on the world map.
predicted_pos_x = p.x + sensor_dist * cos(p.theta + sensor_bearing)
predicted_pos_y = p.y + sensor_dist * sin(p.theta + sensor_bearing)
dx = lm_x - predicted_pos_x
dy = lm_y - predicted_pos_y
error1_sq = dx*dx + dy*dy
# ... Orientation error:
#predicted_bearing = wrap_angle(atan2(lm_y-p.y, lm_x-p.x) - p.theta)
#predicted_orient = wrap_angle(p.theta - lm_orient + predicted_bearing)
# simplifies to...
predicted_orient = wrap_angle(atan2(lm_y-p.y, lm_x-p.x) - lm_orient)
error2_sq = (sensor_dist*wrap_angle(predicted_orient - sensor_orient))**2
error_sq = error1_sq + error2_sq
p.log_weight -= error_sq / self.distance_variance
return True
#================ Particle Filter ================
class ParticleFilter():
# Particle filter state:
LOCALIZED = 'localized' # Normal
LOCALIZING = 'localizing' # Trying to use LMs to localize
LOST = 'lost' # De-localized and no LMs in view
def __init__(self, robot, num_particles=500,
initializer = RandomWithinRadius(),
motion_model = "default",
sensor_model = "default",
particle_factory = Particle,
landmarks = None):
if landmarks is None:
landmarks = dict() # make a fresh dict each time
self.robot = robot
self.num_particles = num_particles
self.initializer = initializer
self.initializer.pf = self
if motion_model == "default":
motion_model = DefaultMotionModel(robot)
self.motion_model = motion_model
self.motion_model.pf = self
if sensor_model == "default":
sensor_model = ArucoCombinedSensorModel(robot)
if sensor_model:
sensor_model.set_landmarks(landmarks)
self.sensor_model = sensor_model
self.sensor_model.pf = self
self.particle_factory = particle_factory
self.particles = [particle_factory(i) for i in range(num_particles)]
self.best_particle = self.particles[0]
self.min_log_weight = -300 # prevent floating point underflow in exp()
self.initializer.initialize(robot)
self.exp_weights = np.empty(self.num_particles)
self.cdf = np.empty(self.num_particles)
self.variance = (np.array([[0,0],[0,0]]), 0.)
self.new_indices = [0] * num_particles # np.empty(self.num_particles, dtype=np.int)
self.new_x = [0.0] * num_particles # np.empty(self.num_particles)
self.new_y = [0.0] * num_particles # np.empty(self.num_particles)
self.new_theta = [0.0] * num_particles # np.empty(self.num_particles)
self.pose = (0., 0., 0.)
self.dist_jitter = 15 # mm
self.angle_jitter = 10 / 180 * pi
self.state = self.LOST
def move(self):
self.motion_model.move(self.particles)
if self.sensor_model.evaluate(self.particles): # true if log_weights changed
var = self.update_weights()
if var > 0:
self.resample()
self.state = self.LOCALIZED
self.variance_estimate()
if self.robot.carrying:
self.robot.world.world_map.update_carried_object(self.robot.carrying)
def delocalize(self):
self.state = self.LOST
self.initializer.initialize(self.robot)
def pose_estimate(self):
cx = 0.0; cy = 0.0
hsin = 0.0; hcos = 0.0
weight_sum = 0.0
best_particle = self.particles[0]
for p in self.particles:
p.weight = exp(p.log_weight)
if p.weight > best_particle.weight:
best_particle = p
cx += p.weight * p.x
cy += p.weight * p.y
hsin += sin(p.theta) * p.weight
hcos += cos(p.theta) * p.weight
weight_sum += p.weight
if weight_sum == 0:
weight_sum = 1
cx /= weight_sum
cy /= weight_sum
self.pose = (cx, cy, atan2(hsin,hcos))
self.best_particle = best_particle
return self.pose
def variance_estimate(self):
weight = var_xx = var_xy = var_yy = r_sin = r_cos = 0.0
(mu_x, mu_y, mu_theta) = self.pose_estimate()
for p in self.particles:
dx = (p.x - mu_x)
dy = (p.y - mu_y)
var_xx += dx * dx * p.weight
var_xy += dx * dy * p.weight
var_yy += dy * dy * p.weight
r_sin += sin(p.theta) * p.weight
r_cos += cos(p.theta) * p.weight
weight += p.weight
xy_var = np.array([[var_xx, var_xy],
[var_xy, var_yy]]) / weight
Rsq = r_sin**2 + r_cos**2
Rav = sqrt(Rsq) / weight
theta_var = max(0, 1 - Rav)
self.variance = (xy_var, theta_var)
return self.variance
def update_weights(self):
# Clip the log_weight values and calculate the new weights.
max_weight = max(p.log_weight for p in self.particles)
if max_weight >= self.min_log_weight:
wt_inc = 0.0
else:
wt_inc = - self.min_log_weight / 2.0
print('wt_inc',wt_inc,'applied for max_weight',max_weight)
exp_weights = self.exp_weights
particles = self.particles
for i in range(self.num_particles):
p = particles[i]
p.log_weight += wt_inc
exp_weights[i] = p.weight = exp(p.log_weight)
variance = np.var(exp_weights)
return variance
def resample(self):
# Compute and normalize the cdf; make local pointers for faster access.
#print('resampling...')
exp_weights = self.exp_weights
cdf = self.cdf
cumsum = 0
for i in range(self.num_particles):
cumsum += exp_weights[i]
cdf[i] = cumsum
np.divide(cdf,cumsum,cdf)
# Resampling loop: choose particles to spawn
uincr = 1.0 / self.num_particles
u = random.random() * uincr
index = 0
new_indices = self.new_indices
for j in range(self.num_particles):
while u > cdf[index]:
index += 1
new_indices[j] = index
u += uincr
self.install_new_particles()
def install_new_particles(self):
particles = self.particles
new_indices = self.new_indices
new_x = self.new_x
new_y = self.new_y
new_theta = self.new_theta
for i in range(self.num_particles):
p = particles[new_indices[i]]
new_x[i] = p.x
new_y[i] = p.y
new_theta[i] = p.theta
for i in range(self.num_particles):
p = particles[i]
p.x = new_x[i]
p.y = new_y[i]
p.theta = new_theta[i]
p.log_weight = 0.0
p.weight = 1.0
def set_pose(self,x,y,theta):
for p in self.particles:
p.x = x
p.y = y
p.theta = theta
p.log_weight = 0.0
p.weight = 1.0
self.variance_estimate()
def look_for_new_landmarks(self): pass # SLAM only
def clear_landmarks(self):
print('clear_landmarks: Landmarks are fixed in this particle filter.')
#================ "show" commands that can be used by simple_cli
def show_landmarks(self):
landmarks = self.sensor_model.landmarks
print('The particle filter has %d landmark%s:' %
(len(landmarks), '' if (len(landmarks) == 1) else 's'))
self.show_landmarks_workhorse(landmarks)
def show_landmarks_workhorse(self,landmarks):
"Also called by show_particle"
sorted_keys = self.sort_wmobject_ids(landmarks)
for key in sorted_keys:
value = landmarks[key]
if isinstance(value, Pose):
x = value.position.x
y = value.position.y
theta = value.rotation.angle_z.degrees
sigma_x = 0
sigma_y = 0
sigma_theta = 0
else:
x = value[0][0,0]
y = value[0][1,0]
theta = value[1] * 180/pi
sigma_x = sqrt(value[2][0,0])
sigma_y = sqrt(value[2][1,1])
sigma_theta = sqrt(value[2][2,2])*180/pi
if key.startswith('Aruco-'):
print(' Aruco marker %s' % key[6:], end='')
elif key.startswith('Wall-'):
print(' Wall %s' % key[5:], end='')
elif key.startswith('Cube-'):
print(' Cube %s' % key[5:], end='')
else:
print(' %r' % key, end='')
print(' at (%6.1f, %6.1f) @ %4.1f deg +/- (%4.1f,%4.1f) +/- %3.1f deg' %
(x, y, theta, sigma_x, sigma_y, sigma_theta))
print()
def sort_wmobject_ids(self,ids):
preference = ['Charger','Cube','Aruco','Wall','Doorway','CustomCube','CustomMarker','Room','Face']
def key(id):
index = 0
for prefix in preference:
if id.startswith(prefix):
break
else:
index += 1
return ('%02d' % index) + id
result = sorted(ids, key=key)
return result
def show_particle(self,args=[]):
if len(args) == 0:
particle = self.best_particle
particle_number = '(best=%d)' % particle.index
elif len(args) > 1:
print('Usage: show particle [number]')
return
else:
try:
particle_number = int(args[0])
particle = self.particles[particle_number]
except ValueError:
print('Usage: show particle [number]')
return
except IndexError:
print('Particle number must be between 0 and',
len(self.particles)-1)
return
print ('Particle %s: x=%6.1f y=%6.1f theta=%6.1f deg log wt=%f [%.25f]' %
(particle_number, particle.x, particle.y, particle.theta*180/pi,
particle.log_weight, particle.weight))
if isinstance(particle,SLAMParticle) and len(particle.landmarks) > 0:
print('Landmarks:')
self.show_landmarks_workhorse(particle.landmarks)
else:
print()
#================ Particle SLAM ================
class SLAMParticle(Particle):
def __init__(self, index=-1):
super().__init__(index)
self.landmarks = dict()
def __repr__(self):
return '<SLAMParticle %d: (%.2f, %.2f) %.1f deg. log_wt=%f, %d-lm>' % \
(self.index, self.x, self.y, self.theta*180/pi, self.log_weight, len(self.landmarks))
sigma_r = 50
sigma_alpha = 15 * (pi/180)
sigma_phi = 15 * (pi/180)
sigma_theta = 15 * (pi/180)
sigma_z = 50
landmark_sensor_variance_Qt = np.array([[sigma_r**2, 0 , 0],
[0 , sigma_alpha**2, 0],
[0 , 0 , sigma_phi**2]])
# variance of camera location (cylindrical coordinates)
# phi is the angle around the Z axis of the robot
# theta is the angle around the X axis of the camera (pitch)
camera_sensor_variance_Qt = np.array([[sigma_r**2 , 0 , 0 ,0 , 0],
[0 , sigma_alpha**2, 0 ,0 , 0],
[0 , 0 , sigma_z**2 ,0 , 0],
[0 , 0 , 0 ,sigma_phi**2, 0],
[0 , 0 , 0 ,0 , sigma_theta**2]])
@staticmethod
def sensor_jacobian_H(dx, dy, dist):
"""Jacobian of sensor values (r, alpha) wrt particle state x,y
where (dx,dy) is vector from particle to lm, and
r = sqrt(dx**2 + dy**2), alpha = atan2(dy,dx), phi = phi"""
q = dist**2
sqr_q = dist
return np.array([[dx/sqr_q, dy/sqr_q, 0],
[-dy/q , dx/q , 0],
[0 , 0 , 1]])
@staticmethod
def sensor_jacobian_H_cam(dx, dy, dist):
"""Jacobian of sensor values (r, alpha) wrt particle state x,y
where (dx,dy) is vector from particle to lm, and
r = sqrt(dx**2 + dy**2), alpha = atan2(dy,dx), z = z, phi = phi, theta = theta"""
q = dist**2
sqr_q = dist
return np.array([[dx/sqr_q, dy/sqr_q, 0, 0, 0],
[-dy/q , dx/q , 0, 0, 0],
[0 , 0 , 1, 0, 0],
[0 , 0 , 0, 1, 0],
[0 , 0 , 0, 0, 1],])
def add_regular_landmark(self, lm_id, sensor_dist, sensor_bearing, sensor_orient):
direction = self.theta + sensor_bearing
dx = sensor_dist * cos(direction)
dy = sensor_dist * sin(direction)
lm_x = self.x + dx
lm_y = self.y + dy
if lm_id.startswith('Aruco-') or lm_id.startswith('Wall-'):
lm_orient = wrap_angle(sensor_orient + self.theta)
elif lm_id.startswith('Cube-'):
lm_orient = sensor_orient
else:
print('Unrecognized landmark type:',lm_id)
lm_orient = sensor_orient
lm_mu = np.array([[lm_x], [lm_y]])
H = self.sensor_jacobian_H(dx, dy, sensor_dist)
Hinv = np.linalg.inv(H)
Q = self.landmark_sensor_variance_Qt
lm_sigma = Hinv.dot(Q.dot(Hinv.T))
self.landmarks[lm_id] = (lm_mu, lm_orient, lm_sigma)
def update_regular_landmark(self, id, sensor_dist, sensor_bearing, sensor_orient,
dx, dy, I=np.eye(3)):
# (dx,dy) is vector from particle to SENSOR position of lm
(old_mu, old_orient, old_sigma) = self.landmarks[id]
H = self.sensor_jacobian_H(dx, dy, sensor_dist)
Ql = H.dot(old_sigma.dot(H.T)) + self.landmark_sensor_variance_Qt
Ql_inv = np.linalg.inv(Ql)
K = old_sigma.dot((H.T).dot(Ql_inv))
z = np.array([[sensor_dist], [sensor_bearing], [sensor_orient]])
# (ex,ey) is vector from particle to MAP position of lm
ex = old_mu[0,0] - self.x
ey = old_mu[1,0] - self.y
h = np.array([ [sqrt(ex**2+ey**2)],
[wrap_angle(atan2(ey,ex) - self.theta)],
[wrap_angle(old_orient - self.theta)] ])
delta_sensor = wrap_selected_angles(z-h, [1,2])
if False: """#abs(delta_sensor[1,0]) > 0.1 or abs(delta_sensor[0,0]) > 50:
# Huge delta means the landmark must have moved, so reset our estimate.
if isinstance(id,str): # *** DEBUG
print('update_regular_landmark: index=%d id=%s dist=%5.1f brg=%5.1f orient=%5.1f' %
(self.index, id, sensor_dist, sensor_bearing*180/pi, sensor_orient*180/pi), end='')
print(' delta sensor: %.1f %.1f %.1f' %
(delta_sensor[0,0], delta_sensor[1,0]*180/pi, delta_sensor[2,0]*180/pi))
new_mu = np.array([[self.x + sensor_dist*cos(sensor_bearing+self.theta)],
[self.y + sensor_dist*sin(sensor_bearing+self.theta)],
[sensor_orient]])
Hinv = np.linalg.inv(H)
Q = self.landmark_sensor_variance_Qt
new_sigma = Hinv.dot(Q.dot(Hinv.T))"""
else:
# Error not too large: refine current estimate using EKF
new_mu = np.append(old_mu,[old_orient]).reshape([3,1]) + K.dot(delta_sensor)
new_sigma = (I - K.dot(H)).dot(old_sigma)
# landmark tuple is ( [x,y], orient, covariance_matrix )
if self.index == -1: # NOOP: should be == 0
print('id=',id,' old_mu=',[old_mu[0,0],old_mu[1,0]],'@',old_orient*180/pi,
' new_mu=',[new_mu[0][0],new_mu[1][0]],'@',new_mu[2][0]*180/pi)
print(' ','dx,dy=',[dx,dy],' ex,ey=',[ex,ey],
' sensor_dist=',sensor_dist,
' sensor_bearing=',sensor_bearing*180/pi,
' sensor_orient=',sensor_orient*180/pi,
' delta_sensor=',delta_sensor)
self.landmarks[id] = (new_mu[0:2], wrap_angle(new_mu[2][0]), new_sigma)
if not isinstance(self.landmarks[id][1],(float, np.float64)):
print('ORIENT FAIL', self.landmarks[id])
print('new_mu=',new_mu)
print(' ','dx,dy=',[dx,dy],' ex,ey=',[ex,ey],
' sensor_dist=',sensor_dist,
' sensor_bearing=',sensor_bearing*180/pi,
' sensor_orient=',sensor_orient*180/pi,
' delta_sensor=',delta_sensor)
print('old_mu=',old_mu,'\nold_orient=',old_orient,'\nold_sigma=',old_sigma)
print('z=',z, 'h=',h)
input()
def add_cam_landmark(self, lm_id, sensor_dist, sensor_bearing, sensor_height, sensor_phi, sensor_theta):
direction = self.theta + sensor_bearing
dx = sensor_dist * cos(direction)
dy = sensor_dist * sin(direction)
lm_x = self.x + dx
lm_y = self.y + dy
lm_height = (sensor_height, wrap_angle(sensor_phi+self.theta), sensor_theta)
lm_mu = np.array([[lm_x], [lm_y]])
H = self.sensor_jacobian_H_cam(dx, dy, sensor_dist)
Hinv = np.linalg.inv(H)
Q = self.camera_sensor_variance_Qt
lm_sigma = Hinv.dot(Q.dot(Hinv.T))
# [ [x,y], [z,orient,pitch], covarience_matrix]
self.landmarks[lm_id] = (lm_mu, lm_height, lm_sigma)
def update_cam_landmark(self, id, sensor_dist, sensor_bearing, sensor_height, sensor_phi, sensor_theta,
dx, dy, I=np.eye(5)):
# (dx,dy) is vector from particle to SENSOR position of lm
(old_mu, old_height, old_sigma) = self.landmarks[id]
H = self.sensor_jacobian_H_cam(dx, dy, sensor_dist)
Ql = H.dot(old_sigma.dot(H.T)) + self.camera_sensor_variance_Qt
Ql_inv = np.linalg.inv(Ql)
K = old_sigma.dot((H.T).dot(Ql_inv))
z = np.array([[sensor_dist],
[sensor_bearing],
[sensor_height],
[wrap_angle(sensor_phi+self.theta)],
[sensor_theta]])
# (ex,ey) is vector from particle to MAP position of lm
ex = old_mu[0,0] - self.x
ey = old_mu[1,0] - self.y
h = np.array([[sqrt(ex**2+ey**2)],
[wrap_angle(atan2(ey,ex) - self.theta)],
[old_height[0]],
[old_height[1]],
[old_height[2]]])
new_mu = np.append(old_mu,[old_height]).reshape([5,1]) + K.dot(wrap_selected_angles(z - h,[1,3,4]))
new_sigma = (I - K.dot(H)).dot(old_sigma)
# [ [x,y], [z,orient,pitch], covariance_matrix]
self.landmarks[id] = (new_mu[0:2], new_mu[2:5], new_sigma)
class SLAMSensorModel(SensorModel):
@staticmethod
def is_cube(x):
return isinstance(x, cozmo.objects.LightCube) and x.pose.is_valid
@staticmethod
def is_solo_aruco_landmark(x):
#return False # **** DEBUG HACK
"True for independent Aruco landmarks not associated with any wall."
return isinstance(x, ArucoMarker) and x.id_string not in wall_marker_dict
def __init__(self, robot, landmark_test=None, landmarks=None,
distance_variance=200):
if landmarks is None:
landmarks = dict()
if landmark_test is None:
landmark_test = self.is_cube
self.landmark_test = landmark_test
self.distance_variance = distance_variance
self.candidate_arucos = dict()
self.use_perched_cameras = False
super().__init__(robot,landmarks)
def infer_wall_from_corners_lists(self, id, markers):
# Called by generate_walls_from_markers below.
# All these markers have the same wall_spec, so just grab the first one.
wall_spec = wall_marker_dict.get(markers[0][0], None)
world_points = []
image_points = []
for (id, corners) in markers:
(s, (cx, cy)) = wall_spec.marker_specs[id]
if cy < 100:
marker_size = self.robot.world.aruco.marker_size
else:
# Compensate for lintel marker foreshortening.
# TODO: This could be smarter; make it distance-dependent.
marker_size = 0.85 * self.robot.world.aruco.marker_size
world_points.append((cx-s*marker_size/2, cy+marker_size/2, s))
world_points.append((cx+s*marker_size/2, cy+marker_size/2, s))
world_points.append((cx+s*marker_size/2, cy-marker_size/2, s))
world_points.append((cx-s*marker_size/2, cy-marker_size/2, s))
image_points.append(corners[0])
image_points.append(corners[1])
image_points.append(corners[2])
image_points.append(corners[3])
# Find rotation and translation vector from camera frame using SolvePnP
(success, rvecs, tvecs) = cv2.solvePnP(np.array(world_points),
np.array(image_points),
self.robot.world.aruco.camera_matrix,
self.robot.world.aruco.distortion_array)
rotationm, jcob = cv2.Rodrigues(rvecs)
# Change to marker frame.
# Arucos seen head-on have orientation 0, so work with that for now.
# Later we will flip the orientation to pi for the worldmap.
transformed = np.matrix(rotationm).T*(-np.matrix(tvecs))
angles_xyz = rotation_matrix_to_euler_angles(rotationm)
# euler angle flip when back of wall is seen
if angles_xyz[2] > pi/2:
wall_orient = wrap_angle(-(angles_xyz[1]-pi))
elif angles_xyz[2] >= -pi/2 and angles_xyz[2] <= pi/2:
wall_orient = wrap_angle((angles_xyz[1]))
else:
wall_orient = wrap_angle(-(angles_xyz[1]+pi))
wall_x = -transformed[2]*cos(wall_orient) + (transformed[0]-wall_spec.length/2)*sin(wall_orient)
wall_y = (transformed[0]-wall_spec.length/2)*cos(wall_orient) - -transformed[2]*sin(wall_orient)
# Flip wall orientation to match ArUcos for worldmap
wm_wall_orient = wrap_angle(pi - wall_orient)
wall = WallObj(id=wall_spec.spec_id, x=wall_x, y=wall_y, theta=wm_wall_orient,
length=wall_spec.length)
return wall
def generate_walls_from_markers(self, seen_marker_objects, good_markers):
if self.robot.is_moving:
return []
walls = []
wall_markers = dict() # key is wall id
for num in good_markers:
marker = seen_marker_objects[num]
wall_spec = wall_marker_dict.get(marker.id_string,None)
if wall_spec is None: continue # marker not part of a known wall
wall_id = wall_spec.spec_id
markers = wall_markers.get(wall_id, list())
markers.append((marker.id_string, marker.bbox[0]))
wall_markers[wall_id] = markers
# Now infer the walls from the markers
for (wall_id,markers) in wall_markers.items():
# Must see at least two markers to create a wall, but once it's
# in the world map we only require one marker to recognize it.
# Necessary to avoid spurious wall creation.
# NOTE: switched to only requiring 1 marker for wall creation.
if len(markers) >= 1 or wall_id in self.robot.world.world_map.objects:
walls.append(self.infer_wall_from_corners_lists(wall_id,markers))
return walls
def evaluate(self, particles, force=False, just_looking=False):
# Returns true if particles were evaluated.
# Call with force=True from particle_viewer to skip distance traveled check.
# Call with just_looking=True to just look for new landmarks; no evaluation.
evaluated = False
# Don't evaluate if robot is still moving; ArUco info will be bad.
if self.robot.is_moving:
return False
# Compute robot motion even if forced, to check for robot origin_id change
(dist,turn_angle) = self.compute_robot_motion()
# If we're lost but have landmarks in view, see if we can
# recover by using the landmarks to generate a new particle set.
if self.pf.state == ParticleFilter.LOST:
if self.pf.sensor_model.landmarks:
found_lms = self.pf.make_particles_from_landmarks()
if not found_lms:
return False
else:
self.pf.state = ParticleFilter.LOCALIZING
force = True
just_looking = False
else: # no landmarks, so we can't be lost
self.pf.state = ParticleFilter.LOCALIZED
# Unless forced, don't evaluate unless the robot moved enough
# for evaluation to be worthwhile.
#print('force=',force,' dist=',dist, ' state=',self.pf.state)
if (not force) and (dist < 5) and abs(turn_angle) < 2*pi/180:
return False
if not just_looking:
self.last_evaluate_pose = self.robot.pose
# Evaluate any cube landmarks (but we don't normally use cubes as landmarks)
for cube in self.robot.world.light_cubes.values():
if self.landmark_test(cube):
id = 'Cube-'+str(cube.cube_id)
evaluated = self.process_landmark(id, cube, just_looking, []) \
or evaluated
# Evaluate ArUco landmarks
try:
# Cache seen marker objects because vision is in another thread.
seen_marker_objects = self.robot.world.aruco.seen_marker_objects.copy()
except:
seen_marker_objects = dict()
for marker in seen_marker_objects.values():
if self.landmark_test(marker):
evaluated = self.process_landmark(marker.id_string, marker,
just_looking, seen_marker_objects) \
or evaluated
# Evaluate walls. First find the set of "good" markers.
# Good markers have been seen consistently enough to be deemed reliable.
good_markers = []
for marker in seen_marker_objects.values():
if marker.id_string in self.robot.world.world_map.objects or \
self.candidate_arucos.get(marker.id_string,-1) > 10:
good_markers.append(marker.id)
walls = self.generate_walls_from_markers(seen_marker_objects, good_markers)
for wall in walls:
evaluated = self.process_landmark(wall.id, wall, just_looking, seen_marker_objects) \
or evaluated
#print('for', wall, ' evaluated now', evaluated, ' just_looking=', just_looking, seen_marker_objects)
# Evaluate perched cameras as landmarks
if self.use_perched_cameras:
# Add cameras that can see the robot as landmarks.
perched = list(self.robot.world.perched.camera_pool.get(self.robot.aruco_id,{}).values())
for cam in perched:
id = 'Cam-XXX'
evaluated = self.process_landmark(id, cam, just_looking, seen_marker_objects) \
or evaluated
#print('nwalls=', len(walls), ' evaluated=',evaluated)
if evaluated:
wmax = - np.inf
for p in particles:
wmax = max(wmax, p.log_weight)
if wmax > -5.0 and self.pf.state != ParticleFilter.LOCALIZED:
print('::: LOCALIZED :::')
self.pf.state = ParticleFilter.LOCALIZED
elif self.pf.state != ParticleFilter.LOCALIZED:
print('not localized because wmax =', wmax)
min_log_weight = self.robot.world.particle_filter.min_log_weight
if wmax < min_log_weight:
wt_inc = min_log_weight - wmax
# print('wmax=',wmax,'wt_inc=',wt_inc)
for p in particles:
p.log_weight += wt_inc
self.robot.world.particle_filter.variance_estimate()
# Update counts for candidate arucos and delete any losers.
cached_keys = tuple(self.candidate_arucos.keys())
for id in cached_keys:
self.candidate_arucos[id] -= 1
if self.candidate_arucos[id] <= 0:
#print('*** DELETING CANDIDATE ARUCO', id)
del self.candidate_arucos[id]
return evaluated
def process_landmark(self, id, data, just_looking, seen_marker_objects):
particles = self.robot.world.particle_filter.particles
if id.startswith('Aruco-'):
marker_number = int(id[6:])
# print('spurious data=',data)
marker = seen_marker_objects[marker_number]
sensor_dist = marker.camera_distance
sensor_bearing = atan2(marker.camera_coords[0],
marker.camera_coords[2])
# Rotation about Y axis of marker. Fix sign.
sensor_orient = wrap_angle(pi - marker.euler_rotation[1] * (pi/180))
elif id.startswith('Wall-'):
# Turning to polar coordinates
sensor_dist = sqrt(data.x**2 + data.y**2)
sensor_bearing = atan2(data.y, data.x)
sensor_orient = wrap_angle(data.theta)
elif id.startswith('Cube-'):
# sdk values are in SDK's coordinate system, not ours
sdk_dx = data.pose.position.x - self.robot.pose.position.x
sdk_dy = data.pose.position.y - self.robot.pose.position.y
sensor_dist = sqrt(sdk_dx**2 + sdk_dy**2)
sdk_bearing = atan2(sdk_dy, sdk_dx)
# sensor_bearing is lm bearing relative to robot centerline
sensor_bearing = \
wrap_angle(sdk_bearing-self.robot.pose.rotation.angle_z.radians)
# sensor_orient is lm bearing relative to cube's North
sensor_orient = \
wrap_angle(sdk_bearing - data.pose.rotation.angle_z.radians)
elif id.startswith('Cam'):
# Converting to cylindrical coordinates
sensor_dist = sqrt(landmark.x**2 + landmark.y**2)
sensor_bearing = atan2(landmark.y,landmark.x)
sensor_height = landmark.z
sensor_phi = landmark.phi
sensor_theta = landmark.theta
if sensor_height < 0:
print("FLIP!!!")
# Using str instead of capture object as new object is added by perched_cam every time
else:
print("Don't know how to process landmark; id =",id)
if id not in self.landmarks:
if id.startswith('Aruco-'):
seen_count = self.candidate_arucos.get(id,0)
if seen_count < 10:
# add 2 because we're going to subtract 1 later
self.candidate_arucos[id] = seen_count + 2
return False
print(' *** PF ADDING LANDMARK %s at: distance=%6.1f bearing=%5.1f deg. orient=%5.1f deg.' %
(id, sensor_dist, sensor_bearing*180/pi, sensor_orient*180/pi))
for p in particles:
if not id.startswith('Video'):
p.add_regular_landmark(id, sensor_dist, sensor_bearing, sensor_orient)
else:
# special function for cameras as landmark list has more variables
p.add_cam_landmark(id, sensor_dist, sensor_bearing, sensor_height, sensor_phi, sensor_theta)
# Add new landmark to sensor model's landmark list so worldmap can reference it
#self.landmarks[id] = self.robot.world.particle_filter.particles[0].landmarks[id]
self.landmarks[id] = self.pf.best_particle.landmarks[id]
# Delete new aruco from tentative candidate list; it's established now.
if id.startswith('Aruco-'):
del self.candidate_arucos[id]
return False
# If we reach here, we're seeing a familiar landmark, so evaluate
if just_looking: # *** DEBUG ***
# We can't afford to update all the particles on each
# camera frame so we'll just update particle 0 and use
# that to update the sensor model.
#pp = [particles[0]]
return False
pp = [self.pf.best_particle]
evaluated = False
else:
# We've moved a bit, so we should update every particle.
pp = particles
evaluated = True
if id in self.robot.world.world_map.objects:
obj = self.robot.world.world_map.objects[id]
should_update_landmark = (not obj.is_fixed) and \
(self.pf.state == ParticleFilter.LOCALIZED)
else:
should_update_landmark = True
landmark_is_camera = id.startswith('Video')
for p in pp:
# Use sensed bearing and distance to get particle's
# prediction of landmark position in the world. Compare
# to its stored map position.
sensor_direction = p.theta + sensor_bearing
dx = sensor_dist * cos(sensor_direction)
dy = sensor_dist * sin(sensor_direction)
predicted_lm_x = p.x + dx
predicted_lm_y = p.y + dy
(lm_mu, lm_orient, lm_sigma) = p.landmarks[id]
map_lm_x = lm_mu[0,0]
map_lm_y = lm_mu[1,0]
error_x = map_lm_x - predicted_lm_x
error_y = map_lm_y - predicted_lm_y
error1_sq = error_x**2 + error_y**2
error2_sq = 0 # *** (sensor_dist * wrap_angle(sensor_orient - lm_orient))**2
p.log_weight -= (error1_sq + error2_sq) / self.distance_variance
# Update landmark in this particle's map
if should_update_landmark:
if not landmark_is_camera:
p.update_regular_landmark(id, sensor_dist, sensor_bearing,
sensor_orient, dx, dy)
else:
# special function for cameras as landmark list has more variables
p.update_cam_landmark(id, sensor_dist, sensor_bearing,
sensor_height, sensor_phi, sensor_theta, dx, dy)
return evaluated
class SLAMParticleFilter(ParticleFilter):
def __init__(self, robot, landmark_test=SLAMSensorModel.is_solo_aruco_landmark, **kwargs):
if 'sensor_model' not in kwargs or kwargs['sensor_model'] == 'default':
kwargs['sensor_model'] = SLAMSensorModel(robot, landmark_test=landmark_test)
if 'particle_factory' not in kwargs:
kwargs['particle_factory'] = SLAMParticle
if 'initializer' not in kwargs:
kwargs['initializer'] = RobotPosition(0,0,0)
super().__init__(robot, **kwargs)
self.initializer.pf = self
self.new_landmarks = [None] * self.num_particles
def clear_landmarks(self):
for p in self.particles:
p.landmarks.clear()
self.sensor_model.landmarks.clear()
def add_fixed_landmark(self,landmark):
mu = np.array([[landmark.x], [landmark.y]])
theta = landmark.theta
sigma = np.zeros([3,3])
mu_theta_sigma = (mu, theta, sigma)
for p in self.particles:
p.landmarks[landmark.id] = mu_theta_sigma
self.sensor_model.landmarks[landmark.id] = mu_theta_sigma
def update_weights(self):
var = super().update_weights()
best_particle = self.particles[self.exp_weights.argmax()]
#print(' weight update: BEST ==> ',best_particle)
self.sensor_model.landmarks = best_particle.landmarks
return var
def install_new_particles(self):
particles = self.particles # make local for faster access
new_landmarks = self.new_landmarks
new_indices = self.new_indices
for i in range(self.num_particles):
new_landmarks[i] = particles[new_indices[i]].landmarks.copy()
super().install_new_particles()
for i in range(self.num_particles):
particles[i].landmarks = new_landmarks[i]
def make_particles_from_landmarks(self):
try:
# Cache seen marker objects because vision is in another thread.
seen_marker_objects = self.robot.world.aruco.seen_marker_objects.copy()
except:
seen_marker_objects = dict()
lm_specs = self.get_cube_landmark_specs() + \
self.get_aruco_landmark_specs(seen_marker_objects) + \
self.get_wall_landmark_specs(seen_marker_objects)
if not lm_specs: return False
num_specs = len(lm_specs)
particles = self.particles
phi_jitter = np.random.normal(0.0, self.angle_jitter, size=self.num_particles)
x_jitter = np.random.uniform(-self.dist_jitter, self.dist_jitter, size=self.num_particles)
y_jitter = np.random.uniform(-self.dist_jitter, self.dist_jitter, size=self.num_particles)
theta_jitter = np.random.uniform(-self.angle_jitter/2, self.angle_jitter/2, size=self.num_particles)
for i in range(self.num_particles):
(obj, sensor_dist, sensor_bearing, sensor_orient, lm_pose) = lm_specs[i % num_specs]
# phi is our bearing relative to the landmark, independent of our orientation
phi = wrap_angle(lm_pose[1] - sensor_orient + sensor_bearing + phi_jitter[i])
if i == -1: # change to i==1 to re-enable
print('phi=', phi*180/pi, ' lm_pose[1]=', lm_pose[1]*180/pi,
' sensor_bearing=',sensor_bearing*180/pi,
' sensor_orient=', sensor_orient*180/pi)
p = particles[i]
p.x = lm_pose[0][0,0] - sensor_dist * cos(phi) + x_jitter[i]
p.y = lm_pose[0][1,0] - sensor_dist * sin(phi) + y_jitter[i]
p.theta = wrap_angle(phi - sensor_bearing + phi_jitter[i] + theta_jitter[i])
p_landmarks = self.sensor_model.landmarks.copy()
if False: #i<3:
print('NEW PARTICLE %d: ' % i, p.x, p.y, p.theta*180/pi)
print(' lm_pose[1]=',lm_pose[1]*180/pi, ' sensor_orient=',sensor_orient*180/pi,
' phi=',phi*180/pi)
print('lm_pose = ', lm_pose)
return True
def get_cube_landmark_specs(self):
lm_specs = []
# TODO: iterate over cubes as we do aruco markers below
return lm_specs
def get_aruco_landmark_specs(self, seen_marker_objects):
lm_specs = []
for marker in seen_marker_objects.values():
id = 'Aruco-'+str(marker.id)
lm_pose = self.sensor_model.landmarks.get(id,None)
if lm_pose is None: continue # not a familiar landmark
sensor_dist = marker.camera_distance
sensor_bearing = atan2(marker.camera_coords[0],
marker.camera_coords[2])
sensor_orient = wrap_angle(pi - marker.euler_rotation[1] * (pi/180))
lm_specs.append((marker, sensor_dist, sensor_bearing, sensor_orient, lm_pose))
return lm_specs
def get_wall_landmark_specs(self, seen_marker_objects):
lm_specs = []
good_markers = []
for marker in seen_marker_objects.values():
if marker.id_string in self.robot.world.world_map.objects or \
self.sensor_model.candidate_arucos.get(marker.id_string,-1) > 10:
good_markers.append(marker.id)
walls = self.sensor_model.generate_walls_from_markers(seen_marker_objects, good_markers)
for wall in walls:
lm_pose = self.sensor_model.landmarks.get(wall.id,None)
if lm_pose is None: continue # not a familiar landmark
sensor_dist = sqrt(wall.x**2 + wall.y**2)
sensor_bearing = atan2(wall.y, wall.x)
sensor_orient = wall.theta
lm_specs.append((wall, sensor_dist, sensor_bearing, sensor_orient, lm_pose))
return lm_specs
def look_for_new_landmarks(self):
"""Calls evaluate() to find landmarks and add them to the maps.
Also updates existing landmarks."""
self.sensor_model.evaluate(self.particles, force=True, just_looking=True)
self.sensor_model.landmarks = self.best_particle.landmarks
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,017
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/Nested.py
|
"""
The Nested demo shows the use of nested state machines. We define a
new node class DingDong that has a three-node state machine inside
it. We then define the main class, Nested, whose state machine
contains two instances of DingDong. DingDong uses a ParentCompletes
node to cause DinDong to post a completion event, which allows
Nested's first DingDong instance 'dd1' to move on to the next state,
which is 'bridge'. (The 'dd2' instance of DingDong also posts a
completion event, but nothing is listening for it.)
Behavior: Cozmo says 'ding', then 'dong', then says 'once again'
(that's the bridge), then 'ding', and then 'dong'.
"""
from cozmo_fsm import *
class DingDong(StateNode):
def setup(self):
"""
ding: Say('ding') =C=> dong: Say('dong') =C=> ParentCompletes()
"""
# Code generated by genfsm on Mon Feb 17 03:14:24 2020:
ding = Say('ding') .set_name("ding") .set_parent(self)
dong = Say('dong') .set_name("dong") .set_parent(self)
parentcompletes1 = ParentCompletes() .set_name("parentcompletes1") .set_parent(self)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(ding) .add_destinations(dong)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(dong) .add_destinations(parentcompletes1)
return self
class Nested(StateMachineProgram):
def setup(self):
"""
dd1: DingDong() =C=> bridge: Say('once again') =C=> dd2: DingDong()
"""
# Code generated by genfsm on Mon Feb 17 03:14:24 2020:
dd1 = DingDong() .set_name("dd1") .set_parent(self)
bridge = Say('once again') .set_name("bridge") .set_parent(self)
dd2 = DingDong() .set_name("dd2") .set_parent(self)
completiontrans3 = CompletionTrans() .set_name("completiontrans3")
completiontrans3 .add_sources(dd1) .add_destinations(bridge)
completiontrans4 = CompletionTrans() .set_name("completiontrans4")
completiontrans4 .add_sources(bridge) .add_destinations(dd2)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,018
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/CV_Contour.py
|
import cv2
import numpy as np
from cozmo_fsm import *
class CV_Contour(StateMachineProgram):
def __init__(self):
self.colors = [(0,0,255), (0,255,0), (255,0,0),
(255,255,0), (255,0,255), (0,255,255),
(0,0,128), (0,128,0), (128,0,0),
(128,128,0), (0,128,128), (128,0,128),
(255,255,255)]
super().__init__(aruco=False, particle_filter=False, cam_viewer=False,
force_annotation=True, annotate_sdk=False)
def start(self):
super().start()
dummy = numpy.array([[0]*320], dtype='uint8')
cv2.namedWindow('contour')
cv2.imshow('contour',dummy)
cv2.createTrackbar('thresh1','contour',0,255,lambda self: None)
cv2.setTrackbarPos('thresh1','contour',100)
cv2.createTrackbar('minArea','contour',1,1000,lambda self: None)
cv2.setTrackbarPos('minArea','contour',50)
def user_image(self,image,gray):
thresh1 = cv2.getTrackbarPos('thresh1','contour')
ret, thresholded = cv2.threshold(gray, thresh1, 255, 0)
#cv2.imshow('contour',thresholded)
if cv2.__version__[0] >= '4':
contours, hierarchy = \
cv2.findContours(thresholded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
else: # in OpenCV 3.x there was an additional return value
dummy, contours, hierarchy = \
cv2.findContours(thresholded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
areas = [(i, cv2.contourArea(contours[i])) for i in range(len(contours))]
areas.sort(key=lambda x: x[1])
areas.reverse()
self.areas = areas
self.contours = contours
self.hierarchy = hierarchy
def user_annotate(self,annotated_image):
minArea = cv2.getTrackbarPos('minArea','contour')
scale = self.annotated_scale_factor
for area_entry in self.areas:
if area_entry[1] < minArea:
break
temp = index = area_entry[0]
depth = -1
while temp != -1 and depth < len(self.colors)-1:
depth += 1
temp = self.hierarchy[0,temp,3]
contour = scale * self.contours[index]
cv2.drawContours(annotated_image, [contour], 0, self.colors[depth], 2)
cv2.imshow('contour',annotated_image)
cv2.waitKey(1)
return annotated_image
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,019
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/Look5.py
|
"""
Example of starting a behavior and indicating that it should not be
automatically stopped when the behavior node is exited. We later
use StopBehavior() to stop the behavior.
"""
from cozmo_fsm import *
class Look5(StateMachineProgram):
def setup(self):
"""
LookAroundInPlace(stop_on_exit=False)
=T(5)=> Say("I'm almost done")
=T(5)=> StopBehavior()
"""
# Code generated by genfsm on Mon Feb 17 03:13:56 2020:
lookaroundinplace1 = LookAroundInPlace(stop_on_exit=False) .set_name("lookaroundinplace1") .set_parent(self)
say1 = Say("I'm almost done") .set_name("say1") .set_parent(self)
stopbehavior1 = StopBehavior() .set_name("stopbehavior1") .set_parent(self)
timertrans1 = TimerTrans(5) .set_name("timertrans1")
timertrans1 .add_sources(lookaroundinplace1) .add_destinations(say1)
timertrans2 = TimerTrans(5) .set_name("timertrans2")
timertrans2 .add_sources(say1) .add_destinations(stopbehavior1)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,020
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/Texting.py
|
from cozmo_fsm import *
class Texting(StateMachineProgram):
def setup(self):
"""
startnode: StateNode()
startnode =TM('1')=> do_null
startnode =TM('2')=> do_time
startnode =TM('3')=> do_comp
do_null: Say("Full steam ahead") =N=> Forward(20) =C=> startnode
do_time: Say("Full steam ahead") =T(2)=> Forward(20) =C=> startnode
do_comp: Say("Full steam ahead") =C=> Forward(20) =C=> startnode
"""
# Code generated by genfsm on Mon Feb 17 03:17:21 2020:
startnode = StateNode() .set_name("startnode") .set_parent(self)
do_null = Say("Full steam ahead") .set_name("do_null") .set_parent(self)
forward1 = Forward(20) .set_name("forward1") .set_parent(self)
do_time = Say("Full steam ahead") .set_name("do_time") .set_parent(self)
forward2 = Forward(20) .set_name("forward2") .set_parent(self)
do_comp = Say("Full steam ahead") .set_name("do_comp") .set_parent(self)
forward3 = Forward(20) .set_name("forward3") .set_parent(self)
textmsgtrans1 = TextMsgTrans('1') .set_name("textmsgtrans1")
textmsgtrans1 .add_sources(startnode) .add_destinations(do_null)
textmsgtrans2 = TextMsgTrans('2') .set_name("textmsgtrans2")
textmsgtrans2 .add_sources(startnode) .add_destinations(do_time)
textmsgtrans3 = TextMsgTrans('3') .set_name("textmsgtrans3")
textmsgtrans3 .add_sources(startnode) .add_destinations(do_comp)
nulltrans1 = NullTrans() .set_name("nulltrans1")
nulltrans1 .add_sources(do_null) .add_destinations(forward1)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(forward1) .add_destinations(startnode)
timertrans1 = TimerTrans(2) .set_name("timertrans1")
timertrans1 .add_sources(do_time) .add_destinations(forward2)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(forward2) .add_destinations(startnode)
completiontrans3 = CompletionTrans() .set_name("completiontrans3")
completiontrans3 .add_sources(do_comp) .add_destinations(forward3)
completiontrans4 = CompletionTrans() .set_name("completiontrans4")
completiontrans4 .add_sources(forward3) .add_destinations(startnode)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,021
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/speech.py
|
try:
import speech_recognition as sr
except: pass
import time
from threading import Thread
from .evbase import Event
from .events import SpeechEvent
#================ Thesaurus ================
class Thesaurus():
def __init__(self):
self.words = dict()
self.add_homophones('cozmo', \
["cozimo","cosimo","cosmo", \
"kozmo","cosmos","cozmos"])
self.add_homophones('right', ['write','wright'])
self.add_homophones('1',['one','won'])
self.add_homophones('cube1',['q1','coupon','cuban'])
self.phrase_tree = dict()
self.add_phrases('cube1',['cube 1'])
self.add_phrases('cube2',['cube 2'])
self.add_phrases('cube2',['cube to'])
self.add_phrases('cube3',['cube 3'])
self.add_phrases('paperclip',['paper clip'])
self.add_phrases('deli-slicer',['deli slicer'])
def add_homophones(self,word,homophones):
if not isinstance(homophones,list):
homophones = [homophones]
for h in homophones:
self.words[h] = word
def lookup_word(self,word):
return self.words.get(word,word)
def add_phrases(self,word,phrases):
if not isinstance(phrases,list):
phrases = [phrases]
for phrase in phrases:
wdict = self.phrase_tree
for pword in phrase.split(' '):
wdict[pword] = wdict.get(pword,dict())
wdict = wdict[pword]
wdict[''] = word
def substitute_phrases(self,words):
result = []
while words != []:
word = words[0]
del words[0]
wdict = self.phrase_tree.get(word,None)
if wdict is None:
result.append(word)
continue
prefix = [word]
while words != []:
wdict2 = wdict.get(words[0],None)
if wdict2 is None: break
prefix.append(words[0])
del words[0]
wdict = wdict2
subst = wdict.get('',None)
if subst is not None:
result.append(subst)
else:
result = result + prefix
return result
#================ SpeechListener ================
class SpeechListener():
def __init__(self,robot, thesaurus=Thesaurus(), debug=False):
self.robot = robot
self.thesaurus = thesaurus
self.debug = debug
def speech_listener(self):
warned_no_mic = False
print('Launched speech listener.')
self.rec = sr.Recognizer()
while True:
try:
with sr.Microphone() as source:
if warned_no_mic:
print('Got a microphone!')
warned_no_mic = False
while True:
if self.debug: print('--> Listening...')
try:
audio = self.rec.listen(source, timeout=8, phrase_time_limit=8)
audio_len = len(audio.frame_data)
except:
continue
if self.debug:
print('--> Got audio data: length = {:,d} bytes.'. \
format(audio_len))
if audio_len > 1000000: #500000:
print('**** Audio segment too long. Try again.')
continue
try:
utterance = self.rec.recognize_google(audio).lower()
print("Raw utterance: '%s'" % utterance)
words = [self.thesaurus.lookup_word(w) for w in utterance.split(" ")]
words = self.thesaurus.substitute_phrases(words)
string = " ".join(words)
print("Heard: '%s'" % string)
evt = SpeechEvent(string,words)
self.robot.erouter.post(evt)
except sr.RequestError as e:
print("Could not request results from google speech recognition service; {0}".format(e))
except sr.UnknownValueError:
if self.debug:
print('--> Recognizer found no words.')
except Exception as e:
print('Speech recognition got exception:', repr(e))
except OSError as e:
if not warned_no_mic:
print("Couldn't get a microphone:",e)
warned_no_mic = True
time.sleep(10)
def start(self):
self.thread = Thread(target=self.speech_listener)
self.thread.daemon = True #ending fg program will kill bg program
self.thread.start()
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,022
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/nodes.py
|
import time
import asyncio
import inspect
import types
import random
import numpy as np
try: import cv2
except: pass
from math import pi, sqrt, atan2, inf, nan
from multiprocessing import Process, Queue
import cozmo
from cozmo.util import distance_mm, speed_mmps, degrees, Distance, Angle, Pose
from . import evbase
from .base import *
from .events import *
from .cozmo_kin import wheelbase
from .geometry import wrap_angle
from .worldmap import WorldObject, FaceObj, CustomMarkerObj
#________________ Ordinary Nodes ________________
class ParentCompletes(StateNode):
def start(self,event=None):
super().start(event)
if TRACE.trace_level > TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop,
'%s is causing %s to complete' % (self, self.parent))
if self.parent:
self.parent.post_completion()
class ParentSucceeds(StateNode):
def start(self,event=None):
super().start(event)
if TRACE.trace_level > TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop,
'%s is causing %s to succeed' % (self, self.parent))
if self.parent:
self.parent.post_success()
class ParentFails(StateNode):
def start(self,event=None):
super().start(event)
if TRACE.trace_level > TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop,
'%s is causing %s to fail' % (self, self.parent))
if self.parent:
self.parent.post_failure()
class Iterate(StateNode):
"""Iterates over an iterable, posting DataEvents. Completes when done."""
def __init__(self,iterable=None):
super().__init__()
self.iterable = iterable
class NextEvent(Event): pass
def start(self,event=None):
if self.running: return
super().start(event)
if isinstance(event, DataEvent):
self.iterable = event.data
if isinstance(self.iterable, int):
self.iterable = range(self.iterable)
if self.iterable is None:
raise ValueError('~s has nothing to iterate on.' % repr(self))
if not isinstance(event, self.NextEvent):
self.iterator = self.iterable.__iter__()
try:
value = next(self.iterator)
except StopIteration:
self.post_completion()
return
self.post_data(value)
class MoveLift(StateNode):
"Move lift at specified speed."
def __init__(self,speed):
super().__init__()
self.speed = speed
def start(self,event=None):
if self.running: return
super().start(event)
# Temporary hack supplied by Mark Wesley at Anki
msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(True)
self.robot.conn.send_msg(msg)
self.robot.move_lift(self.speed)
def stop(self):
if not self.running: return
self.robot.move_lift(0)
super().stop()
class RelaxLift(StateNode):
def start(self,event=None):
if self.running: return
super().start(event)
# Temporary hack supplied by Mark Wesley at Anki
msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(False)
self.robot.conn.send_msg(msg)
class SetLights(StateNode):
def __init__(self, object, light):
super().__init__()
self.object = object
self.light = light
def start(self,event=None):
super().start(event)
if self.object is not self.robot:
self.object.set_lights(self.light)
else:
if self.light.on_color.int_color & 0x00FFFF00 == 0: # no green or blue component
self.robot.set_all_backpack_lights(self.light)
else:
self.robot.set_backpack_lights_off()
self.robot.set_center_backpack_lights(self.light)
self.post_completion()
class DriveContinuous(StateNode):
def __init__(self,path=[]):
self.path = path
self.polling_interval = 0.05
super().__init__()
def start(self,event=None):
if isinstance(event, DataEvent) and isinstance(event.data,(list,tuple)):
self.path = event.data
if len(self.path) == 0:
raise ValueError('Node %s has a null path' % repr(self))
self.path_index = 0
self.cur = self.path[self.path_index]
self.prev = None
self.last_dist = -1
self.target_q = None
self.reached_dist = False
self.mode = None
self.pause_counter = 0
super().start(event)
def stop(self):
self.robot.stop_all_motors()
super().stop()
def poll(self):
if not self.running: return
# Quit if the robot is picked up.
if self.robot.really_picked_up():
print('** Robot was picked up.')
self.robot.stop_all_motors()
self.poll_handle.cancel()
self.path_index = None
#print('<><><>', self, 'punting')
self.post_failure()
return
# See where we are
x = self.robot.world.particle_filter.pose[0]
y = self.robot.world.particle_filter.pose[1]
q = self.robot.world.particle_filter.pose[2]
dist = sqrt((self.cur.x-x)**2 + (self.cur.y-y)**2)
delta_q = wrap_angle(q - self.target_q) if self.target_q is not None else inf
# If we're pausing, print our position and exit
if self.pause_counter > 0:
#print('%x p%1d. x: %5.1f y: %5.1f q:%6.1f dist: %5.1f' %
# (self.__hash__() & 0xffffffffffffffff, self.pause_counter, x, y, q*180/pi, dist))
self.pause_counter -= 1
return
# See if we've passed the closest approach to the waypoint,
# i.e., distance to the waypoint is consistently INCREASING
# or waypoint is behind us.
if not self.reached_dist:
self.reached_dist = \
abs(delta_q) > 135*pi/180 or \
(dist - self.last_dist) > 0.1 and \
( (self.mode == 'x' and np.sign(x-self.cur.x) == np.sign(self.cur.x-self.prev.x)) or
(self.mode == 'y' and np.sign(y-self.cur.y) == np.sign(self.cur.y-self.prev.y)) )
self.last_dist = dist
# Is it time to switch to the next waypoint?
reached_waypoint = (self.path_index == 0) or \
(self.reached_dist and \
(self.path_index < len(self.path)-1 or \
abs(delta_q) < 5*pi/180))
# Advance to next waypoint if indicated
if reached_waypoint:
self.path_index += 1
print('DriveContinuous: current position is (%.1f, %.1f) @ %.1f deg.' %
(x, y, q*180/pi))
print(' path index advanced to %d' % self.path_index, end='')
if self.path_index == len(self.path):
print('\nDriveContinous: path complete. Stopping.')
self.robot.stop_all_motors()
self.post_completion()
return
elif self.path_index > len(self.path):
# uncaught completion event
print('\nDriveContinuous: uncaught completion! Stopping.')
self.stop()
return
self.prev = self.cur
self.cur = self.path[self.path_index]
self.last_dist = inf
self.reached_dist = False
self.target_q = atan2(self.cur.y-self.prev.y, self.cur.x-self.prev.x)
print(': [%.1f, %.1f] tgtQ is %.1f deg.' % (self.cur.x, self.cur.y, self.target_q*180/pi))
# Is the target behind us?
delta_dist = sqrt((self.cur.x-x)**2 + (self.cur.y-y)**2)
if delta_q < inf and abs(delta_q) > 135*pi/180:
#self.target_q = wrap_angle(self.target_q + pi)
print('New waypoint is behind us --> delta_q = %.1f deg., new target_q = %.1f deg., dist = %.1f' %
(delta_q*180/pi, self.target_q*180/pi, delta_dist))
self.drive_direction = +1 # was -1
else:
self.drive_direction = +1
# Heading determines whether we're solving y=f(x) or x=f(y)
if abs(self.target_q) < pi/4 or abs(abs(self.target_q)-pi) < pi/4:
self.mode = 'x' # y = m*x + b
xdiff = self.cur.x - self.prev.x
xdiv = xdiff if xdiff != 0 else 0.01
self.m = (self.cur.y-self.prev.y) / xdiv
self.b = self.cur.y - self.m * self.cur.x
#print(' y =', self.m, ' * x +', self.b)
else:
self.mode = 'y' # x = m*y + b
ydiff = self.cur.y - self.prev.y
ydiv = ydiff if ydiff != 0 else 0.01
self.m = (self.cur.x-self.prev.x) / ydiv
self.b = self.cur.x - self.m * self.cur.y
#print(' x =', self.m, ' * y +', self.b)
# Do we need to turn in place before setting off toward new waypoint?
if abs(wrap_angle(q-self.target_q)) > 30*pi/180:
self.saved_mode = self.mode
self.mode = 'q'
print('DriveContinuous: turning to %.1f deg. before driving to waypoint.' %
(self.target_q*180/pi))
# If we were moving, come to a full stop before trying to change direction
if self.path_index > 1:
self.robot.stop_all_motors()
self.pause_counter = 5
return
# Haven't reached waypoint yet
elif self.reached_dist:
# But we have traveled far enough, and this is the last waypoint, so
# come to a stop and then fix heading
if self.mode != 'q':
if abs(wrap_angle(q-self.target_q)) > 5:
self.robot.stop_all_motors()
self.robot.pause_counter = 5
self.mode = 'q'
print('DriveContinuous: final waypoint reached; adjusting heading to %.1f deg.' %
(self.target_q*180/pi))
elif self.mode == 'q' and abs(wrap_angle(q-self.target_q)) < 10*pi/180:
# If within 10 degrees, cut motors and let inertia carry us the rest of the way.
print('DriveContinuous: turn to heading complete: heading is %.1f deg.' %
(q*180/pi))
self.robot.stop_all_motors()
self.mode = self.saved_mode
self.pause_counter = 5
return
# Calculate error and correction based on present x/y/q position
q_error = wrap_angle(q - self.target_q)
intercept_distance = 100 # was 25
if self.mode == 'x': # y = m*x + b
target_y = self.m * x + self.b
d_error = (y - target_y) * np.sign(pi/2 - abs(self.target_q)) # *** CHECK THIS
correcting_q = - 0.8*q_error - 0.8*atan2(d_error,intercept_distance)
elif self.mode == 'y': # x = m*y + b
target_x = self.m * y + self.b
d_error = (x - target_x) * np.sign(pi/2 - abs(self.target_q-pi/2)) # *** CHECK THIS
correcting_q = - 0.8*q_error - 0.8*atan2(-d_error,intercept_distance)
elif self.mode == 'q':
d_error = nan
correcting_q = - nan # 0.8*q_error
else:
print("Bad mode value '%s'" % repr(self.mode))
return
# Calculate wheel speeds based on correction value
if self.mode == 'q' or abs(q_error)*180/pi >= 15:
# For large heading error, turn in place
flag = "<>"
speed = 0
qscale = 150 # was 50
correcting_q = nan # - 1.0 * np.sign(q_error) * min(abs(q_error), 25*pi/180)
speedinc = qscale * 15*pi/180 * -np.sign(q_error)
elif abs(q_error)*180/pi > 5 and abs(d_error) < 100:
# For moderate heading error where distance error isn't huge,
# slow down and turn more slowly
flag = "* "
speed = 50 # was 20
qscale = 150
speedinc = qscale * correcting_q
else:
# We're doing pretty well; go fast and make minor corrections
flag = " "
speed = 100
qscale = 150 # was 150
speedinc = qscale * correcting_q
lspeed = self.drive_direction * (speed - self.drive_direction*speedinc)
rspeed = self.drive_direction * (speed + self.drive_direction*speedinc)
if self.mode == 'x': display_target = target_y
elif self.mode == 'y': display_target = target_x
elif self.mode == 'q': display_target = self.target_q*180/pi
elif self.mode == 'p': display_target = inf
else: display_target = nan
"""
print('%x %s x: %5.1f y: %5.1f q:%6.1f tgt:%6.1f derr: %5.1f qerr:%6.1f corq: %5.1f inc: %5.1f dist: %5.1f speeds: %4.1f/%4.1f' %
(self.__hash__() & 0xffffffffffffffff,
self.mode+flag, x, y, q*180/pi, display_target, d_error, q_error*180/pi,
correcting_q*180/pi, speedinc, dist, lspeed, rspeed))
"""
self.robot.drive_wheel_motors(lspeed, rspeed, 500, 500)
class LookAtObject(StateNode):
"Continuously adjust head angle to fixate object."
def __init__(self):
super().__init__()
self.object = None
self.handle = None
def start(self,event=None):
self.set_polling_interval(0.1)
self.handle = None
super().start()
def stop(self):
if self.handle:
self.handle.cancel()
super().stop()
def poll(self):
if not self.running: return
if isinstance(self.object, FaceObj) or isinstance(self.object, CustomMarkerObj):
image_box = self.object.sdk_obj.last_observed_image_box
camera_center = self.robot.camera.config.center.y
delta = image_box.top_left_y + image_box.height/2 - camera_center
adjust_level = 0.1
if self.robot.left_wheel_speed.speed_mmps != 0 and self.robot.right_wheel_speed.speed_mmps != 0:
adjust_level = 0.2
if delta > 15:
angle = self.robot.head_angle.radians - adjust_level
elif delta < -15:
angle = self.robot.head_angle.radians + adjust_level
else:
angle = self.robot.head_angle.radians
angle = cozmo.robot.MAX_HEAD_ANGLE.radians if angle > cozmo.robot.MAX_HEAD_ANGLE.radians else angle
angle = cozmo.robot.MIN_HEAD_ANGLE.radians if angle < cozmo.robot.MIN_HEAD_ANGLE.radians else angle
else:
if isinstance(self.object, WorldObject):
rpose = self.robot.world.particle_filter.pose
dx = self.object.x - rpose[0]
dy = self.object.y - rpose[1]
else:
opos = self.object.pose.position
rpos = self.robot.pose.position
dx = opos.x - rpos.x
dy = opos.y - rpos.y
dist = sqrt(dx**2 + dy**2)
if dist < 60:
angle = -0.4
elif dist < 80:
angle = -0.3
elif dist < 100:
angle = -0.2
elif dist < 140:
angle = -0.1
elif dist < 180:
angle = 0
else:
angle = 0.1
if abs(self.robot.head_angle.radians - angle) > 0.03:
self.handle = self.robot.loop.call_soon(self.move_head, angle)
def move_head(self,angle):
try:
self.robot.set_head_angle(cozmo.util.radians(angle), in_parallel=True, num_retries=2)
except cozmo.exceptions.RobotBusy:
print("LookAtObject: robot busy; can't move head to",angle)
pass
class SetPose(StateNode):
def __init__(self, pose=Pose(0,0,0,angle_z=degrees(0))):
super().__init__()
self.pose = pose
def start(self, event=None):
super().start(event)
if isinstance(event, DataEvent) and isinstance(event.data, Pose):
pose = event.data
else:
pose = self.pose
self.robot.world.particle_filter.set_pose(self.pose.position.x,
self.pose.position.y,
self.pose.rotation.angle_z.radians)
class Print(StateNode):
"Argument can be a string, or a function to be evaluated at print time."
def __init__(self,spec=None):
super().__init__()
self.spec = spec
def start(self,event=None):
super().start(event)
if isinstance(self.spec, types.FunctionType):
text = self.spec()
else:
text = self.spec
if text is None and isinstance(event, DataEvent):
text = repr(event.data)
print(text)
self.post_completion()
class AbortAllActions(StateNode):
def start(self,event=None):
super().start(event)
self.robot.abort_all_actions()
self.post_completion()
class AbortHeadAction(StateNode):
def start(self,event=None):
super().start(event)
actionType = cozmo._clad._clad_to_engine_cozmo.RobotActionType.UNKNOWN
msg = cozmo._clad._clad_to_engine_iface.CancelAction(actionType=actionType)
self.robot.conn.send_msg(msg)
self.post_completion()
class StopAllMotors(StateNode):
def start(self,event=None):
super().start(event)
self.robot.stop_all_motors()
self.post_completion()
#________________ Color Images ________________
class ColorImageBase(StateNode):
def is_color(self,image):
raw = image.raw_image
for i in range(0, raw.height, 15):
pixel = raw.getpixel((i,i))
if pixel[0] != pixel[1]:
return True
return False
class ColorImageEnabled(ColorImageBase):
"""Turn color images on or off and post completion when setting has taken effect."""
def __init__(self,enabled=True):
self.enabled = enabled
super().__init__()
def start(self,event=None):
super().start(event)
if self.robot.camera.color_image_enabled == self.enabled:
self.post_completion()
else:
self.robot.camera.color_image_enabled = self.enabled
self.robot.world.add_event_handler(cozmo.world.EvtNewCameraImage, self.new_image)
def new_image(self,event,**kwargs):
is_color = self.is_color(event.image)
if is_color:
self.robot.world.latest_color_image = event.image
if is_color == self.enabled:
self.robot.world.remove_event_handler(cozmo.world.EvtNewCameraImage, self.new_image)
self.post_completion()
class GetColorImage(ColorImageBase):
"""Post one color image as a data event; leave color mode unchanged."""
def start(self,event=None):
super().start(event)
self.save_enabled = self.robot.camera.color_image_enabled
if not self.save_enabled:
self.robot.camera.color_image_enabled = True
self.robot.world.add_event_handler(cozmo.world.EvtNewCameraImage, self.new_image)
def new_image(self,event,**kwargs):
if self.is_color(event.image):
self.robot.world.latest_color_image = event.image
self.robot.camera.color_image_enabled = self.save_enabled
try:
self.robot.world.remove_event_handler(cozmo.world.EvtNewCameraImage, self.new_image)
except: pass
self.post_data(event.image)
class SaveImage(StateNode):
"Save an image to a file."
def __init__(self, filename="image", filetype="jpg", counter=0, verbose=True):
super().__init__()
self.filename = filename
self.filetype = filetype
self.counter = counter
self.verbose = verbose
def start(self,event=None):
super().start(event)
fname = self.filename
if isinstance(self.counter, int):
fname = fname + str(self.counter)
self.counter = self.counter + 1
fname = fname + "." + self.filetype
image = np.array(self.robot.world.latest_image.raw_image)
cv2.imwrite(fname, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
if self.verbose:
print('Wrote',fname)
#________________ Coroutine Nodes ________________
class CoroutineNode(StateNode):
def __init__(self):
super().__init__()
self.handle = None
self.abort_launch = False
def start(self, event=None):
super().start(event)
if self.abort_launch:
self.handle = None
return
cor = self.coroutine_launcher()
if inspect.iscoroutine(cor):
self.handle = self.robot.loop.create_task(cor)
elif cor is False:
self.handle = None
else:
print('cor=',cor,'type=',type(cor))
raise ValueError("Result of %s launch_couroutine() is %s, not a coroutine." %
(self,cor))
def coroutine_launcher(self):
raise Exception('%s lacks a coroutine_launcher() method' % self)
def post_when_complete(self):
"Call this from within start() if the coroutine will signal completion."
self.robot.loop.create_task(self.wait_for_completion())
async def wait_for_completion(self):
await self.handle
if TRACE.trace_level >= TRACE.await_satisfied:
print('TRACE%d:' % TRACE.await_satisfied, self,
'await satisfied:', self.handle)
self.post_completion()
def stop(self):
if not self.running: return
if self.handle: self.handle.cancel()
super().stop()
class DriveWheels(CoroutineNode):
def __init__(self,l_wheel_speed,r_wheel_speed,**kwargs):
super().__init__()
self.l_wheel_speed = l_wheel_speed
self.r_wheel_speed = r_wheel_speed
self.kwargs = kwargs
def start(self,event=None):
if (isinstance(event,DataEvent) and isinstance(event.data,(list,tuple)) and
len(event.data) == 2):
(lspeed,rspeed) = event.data
if isinstance(lspeed,(int,float)) and isinstance(rspeed,(int,float)):
self.l_wheel_speed = lspeed
self.r_wheel_speed = rspeed
self.abort_launch = False
if self.robot.really_picked_up():
self.abort_launch = True
super().start(event)
self.post_failure()
return
super().start(event)
def coroutine_launcher(self):
return self.robot.drive_wheels(self.l_wheel_speed,self.r_wheel_speed,**self.kwargs)
def stop_wheels(self):
try:
driver = self.robot.drive_wheels(0,0)
# driver is either a co-routine or None
if driver: driver.send(None) # will raise StopIteration
except StopIteration: pass
def stop(self):
if not self.running: return
self.stop_wheels()
super().stop()
class DriveForward(DriveWheels):
def __init__(self, distance=50, speed=50, **kwargs):
if isinstance(distance, cozmo.util.Distance):
distance = distance.distance_mm
if isinstance(speed, cozmo.util.Speed):
speed = speed.speed_mmps
if distance < 0:
distance = -distance
speed = -speed
self.distance = distance
self.speed = speed
self.kwargs = kwargs
super().__init__(speed,speed,**self.kwargs)
self.polling_interval = 0.1
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Distance):
self.distance = event.data.distance_mm
self.start_position = self.robot.pose.position
super().start(event)
def poll(self):
if not self.running: return
"""See how far we've traveled"""
p0 = self.start_position
p1 = self.robot.pose.position
diff = (p1.x - p0.x, p1.y - p0.y)
dist = sqrt(diff[0]*diff[0] + diff[1]*diff[1])
if dist >= self.distance:
self.poll_handle.cancel()
self.stop_wheels()
self.post_completion()
class SmallTurn(CoroutineNode):
"""Estimates how many polling cycles to run the wheels; doesn't use odometry."""
def __init__(self, angle=5):
self.angle = angle
self.counter = 0
self.polling_interval = 0.025
super().__init__()
def start(self,event=None):
# constants were determined empirically for speed 50
self.counter = round((abs(self.angle) + 5) / 1.25) if self.angle else 0
self.abort_launch = False
if self.robot.really_picked_up():
self.abort_launch = True
super().start(event)
self.post_failure()
return
super().start(event)
def coroutine_launcher(self):
if self.angle:
speed = 50 if self.angle < 0 else -50
return self.robot.drive_wheels(speed,-speed,500,500)
else:
self.robot.stop_all_motors()
return False
def poll(self):
if not self.running: return
self.counter -= 1
if self.counter <= 0:
self.poll_handle.cancel()
self.robot.stop_all_motors()
self.post_completion()
class DriveTurn(DriveWheels):
def __init__(self, angle=90, speed=50, **kwargs):
if isinstance(angle, cozmo.util.Angle):
angle = angle.degrees
if isinstance(speed, cozmo.util.Speed):
speed = speed.speed_mmps
if speed <= 0:
raise ValueError('speed parameter must be positive')
self.angle = angle
self.speed = speed
self.kwargs = kwargs
self.polling_interval = 0.05
super().__init__(0,0,**self.kwargs)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Angle):
self.angle = event.data.degrees
if self.angle > 0:
self.l_wheel_speed = -self.speed
self.r_wheel_speed = self.speed
else:
self.l_wheel_speed = self.speed
self.r_wheel_speed = -self.speed
self.last_heading = self.robot.pose.rotation.angle_z.degrees
self.traveled = 0
super().start(event)
def poll(self):
if not self.running: return
"""See how far we've traveled"""
p0 = self.last_heading
p1 = self.robot.pose.rotation.angle_z.degrees
self.last_heading = p1
# Assume we're polling quickly enough that diff will be small;
# typically only about 1 degree. So diff will be large only
# if the heading has passed through 360 degrees since the last
# call to poll(). Use 90 degrees as an arbitrary large threshold.
diff = p1 - p0
if diff < -90.0:
diff += 360.0
elif diff > 90.0:
diff -= 360.0
self.traveled += diff
if abs(self.traveled) > abs(self.angle):
self.poll_handle.cancel()
self.stop_wheels()
self.post_completion()
class DriveArc(DriveWheels):
"""Negative radius means right turn; negative angle means drive
backwards. This node can be passed a DataEvent with a dict
containing any of the arguments accepted by __init__: radius,
angle, distance, speed, and angspeed. Values must already be in
the appropriate units (degrees, mm, deg/sec, or mm/sec)."""
def __init__(self, radius=0, angle=None, distance=None,
speed=None, angspeed=None, **kwargs):
if isinstance(radius, cozmo.util.Distance):
radius = radius.distance_mm
if isinstance(angle, cozmo.util.Angle):
angle = angle.degrees
if isinstance(speed, cozmo.util.Speed):
speed = speed.speed_mmps
if isinstance(angspeed, cozmo.util.Angle):
angspeed = angspeed.degrees
self.calculate_wheel_speeds(radius, angle, distance, speed, angspeed)
super().__init__(self.l_wheel_speed, self.r_wheel_speed, **kwargs)
# Call parent init before setting polling interval.
self.polling_interval = 0.05
def calculate_wheel_speeds(self, radius=0, angle=None, distance=None,
speed=None, angspeed=None):
if radius != 0:
if angle is not None:
pass
elif distance is not None:
angle = self.dist2ang(distance, radius)
else:
raise ValueError('DriveArc requires an angle or distance.')
if speed is not None:
pass
elif angspeed is not None:
speed = self.ang2dist(angspeed, radius)
else:
speed = 40 # degrees/second
if angle < 0:
speed = - speed
self.angle = angle
self.l_wheel_speed = speed * (1 - wheelbase / radius)
self.r_wheel_speed = speed * (1 + wheelbase / radius)
else: # radius is 0
if angspeed is None:
angspeed = 40 # degrees/second
s = angspeed
if angle < 0:
s = -s
self.angle = angle
self.l_wheel_speed = -s
self.r_wheel_speed = s
def ang2dist(self, angle, radius):
return (angle / 360) * 2 * pi * abs(radius)
def dist2ang(self, distance, radius):
return (distance / abs(2 * pi * radius)) * 360
def start(self,event=None):
if self.running: return
if isinstance(event,DataEvent) and isinstance(event.data,dict):
self.calculate_wheel_speeds(**event.data)
self.last_heading = self.robot.pose.rotation.angle_z.degrees
self.traveled = 0
super().start(event)
def poll(self):
if not self.running: return
"""See how far we've traveled"""
p0 = self.last_heading
p1 = self.robot.pose.rotation.angle_z.degrees
self.last_heading = p1
# Assume we're polling quickly enough that diff will be small;
# typically only about 1 degree. So diff will be large only
# if the heading has passed through 360 degrees since the last
# call to poll(). Use 90 degrees as an arbitrary large threshold.
diff = p1 - p0
if diff < -90.0:
diff += 360.0
elif diff > 90.0:
diff -= 360.0
self.traveled += diff
if abs(self.traveled) > abs(self.angle):
self.poll_handle.cancel()
self.stop_wheels()
self.post_completion()
#________________ Cube Disconnect/Reconnect ________________
class DisconnectFromCubes(StateNode):
def start(self, event=None):
super().start(event)
self.robot.world.disconnect_from_cubes()
class ConnectToCubes(CoroutineNode):
def start(self, event=None):
super().start(event)
self.post_when_complete()
def coroutine_launcher(self):
return self.robot.world.connect_to_cubes()
#________________ Action Nodes ________________
class ActionNode(StateNode):
relaunch_delay = 0.050 # 50 milliseconds
def __init__(self, abort_on_stop=True):
"""Call this method only after the subclass __init__ has set
up self.action_kwargs"""
self.abort_on_stop = abort_on_stop
super().__init__()
if 'in_parallel' not in self.action_kwargs:
self.action_kwargs['in_parallel'] = True
if 'num_retries' not in self.action_kwargs:
self.action_kwargs['num_retries'] = 2
self.cozmo_action_handle = None
self.abort_launch = False
def start(self,event=None):
super().start(event)
self.retry_count = 0
if not self.abort_launch:
self.launch_or_retry()
def launch_or_retry(self):
try:
result = self.action_launcher()
except cozmo.exceptions.RobotBusy:
if TRACE.trace_level >= TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop, self, 'launch_action raised RobotBusy')
self.handle = self.robot.loop.call_later(self.relaunch_delay, self.launch_or_retry)
return
if isinstance(result, cozmo.action.Action):
self.cozmo_action_handle = result
elif result is None: # Aborted
return
else:
raise ValueError("Result of %s launch_action() is %s, not a cozmo.action.Action." %
(self,result))
self.post_when_complete()
def action_launcher(self):
raise Exception('%s lacks an action_launcher() method' % self)
def post_when_complete(self):
self.robot.loop.create_task(self.wait_for_completion())
async def wait_for_completion(self):
async_task = self.cozmo_action_handle.wait_for_completed()
await async_task
if TRACE.trace_level >= TRACE.await_satisfied:
print('TRACE%d:' % TRACE.await_satisfied, self,
'await satisfied:', self.cozmo_action_handle)
# check status for 'completed'; if not, schedule relaunch or post failure
if self.running:
if self.cozmo_action_handle.state == 'action_succeeded':
self.post_completion()
elif self.cozmo_action_handle.failure_reason[0] == 'cancelled':
print('CANCELLED: ***>',self,self.cozmo_action_handle)
self.post_completion()
elif self.cozmo_action_handle.failure_reason[0] == 'retry':
if self.retry_count < self.action_kwargs['num_retries']:
print("*** ACTION %s of %s FAILED WITH CODE 'retry': TRYING AGAIN" %
(self.cozmo_action_handle, self.name))
self.retry_count += 1
self.launch_or_retry()
else:
print("*** %s ACTION RETRY COUNT EXCEEDED: FAILING" % self.name)
self.post_failure(self.cozmo_action_handle)
else:
print("*** ACTION NODE %s %s FAILED DUE TO %s AND CAN'T BE RETRIED." %
(self.name,
self.cozmo_action_handle,
self.cozmo_action_handle.failure_reason[0] or 'unknown reason'))
self.post_failure(self.cozmo_action_handle)
def stop(self):
if not self.running: return
if self.cozmo_action_handle and self.abort_on_stop and \
self.cozmo_action_handle.is_running:
self.cozmo_action_handle.abort()
super().stop()
class Say(ActionNode):
"""Speaks some text, then posts a completion event."""
class SayDataEvent(Event):
def __init__(self,text=None):
self.text = text
def __init__(self, text="I'm speechless",
abort_on_stop=False, **action_kwargs):
self.text = text
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, self.SayDataEvent):
utterance = event.text
else:
utterance = self.text
if isinstance(utterance, (list,tuple)):
utterance = random.choice(utterance)
if not isinstance(utterance, str):
utterance = repr(utterance)
self.utterance = utterance
print("Speaking: '",utterance,"'",sep='')
super().start(event)
def action_launcher(self):
if self.utterance.rstrip() == '':
# robot.say_text() action would fail on empty string
self.post_completion()
return None
else:
return self.robot.say_text(self.utterance, **self.action_kwargs)
class Forward(ActionNode):
""" Moves forward a specified distance. Can accept a Distance as a Dataevent."""
def __init__(self, distance=distance_mm(50),
speed=speed_mmps(50), abort_on_stop=True, **action_kwargs):
if isinstance(distance, (int,float)):
distance = distance_mm(distance)
elif not isinstance(distance, cozmo.util.Distance):
raise ValueError('%s distance must be a number or a cozmo.util.Distance' % self)
if isinstance(speed, (int,float)):
speed = speed_mmps(speed)
elif not isinstance(speed, cozmo.util.Speed):
raise ValueError('%s speed must be a number or a cozmo.util.Speed' % self)
self.distance = distance
self.speed = speed
if 'should_play_anim' not in action_kwargs:
action_kwargs['should_play_anim'] = False
self.action_kwargs = action_kwargs
# super's init must come last because it checks self.action_kwargs
super().__init__(abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Distance):
self.distance = event.data
self.abort_launch = False
if self.robot.really_picked_up():
self.abort_launch = True
super().start(event)
self.post_failure()
return
super().start(event)
def action_launcher(self):
return self.robot.drive_straight(self.distance, self.speed,
**self.action_kwargs)
class Turn(ActionNode):
"""Turns by a specified angle. Can accept an Angle as a DataEvent."""
def __init__(self, angle=degrees(90), abort_on_stop=True, **action_kwargs):
if isinstance(angle, (int,float)):
angle = degrees(angle)
elif angle is None:
pass
elif not isinstance(angle, cozmo.util.Angle):
raise ValueError('%s angle must be a number or a cozmo.util.Angle' % self)
self.angle = angle
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Angle):
self.angle = event.data
self.abort_launch = False
if self.robot.really_picked_up():
self.abort_launch = True
super().start(event)
self.post_failure()
return
super().start(event)
def action_launcher(self):
if self.angle is None:
return None
elif not isinstance(self.angle, cozmo.util.Angle):
print("*** WARNING: node", self.name, "self.angle =", self.angle, "is not an instance of cozmo.util.Angle")
self.angle = degrees(self.angle) if isinstance(self.angle, (int,float)) else degrees(0)
return self.robot.turn_in_place(self.angle, **self.action_kwargs)
class GoToPose(ActionNode):
"Uses SDK's go_to_pose method."
def __init__(self, pose, abort_on_stop=True, **action_kwargs):
self.pose = pose
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop)
def action_launcher(self):
return self.robot.go_to_pose(self.pose, **self.action_kwargs)
class SetHeadAngle(ActionNode):
def __init__(self, angle=degrees(0), abort_on_stop=True, **action_kwargs):
if isinstance(angle, (int,float)):
angle = degrees(angle)
elif not isinstance(angle, cozmo.util.Angle):
raise ValueError('%s angle must be a number or a cozmo.util.Angle' % self)
self.angle = angle
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Angle):
self.angle = event.data
super().start(event)
def action_launcher(self):
return self.robot.set_head_angle(self.angle, **self.action_kwargs)
class SetLiftHeight(ActionNode):
def __init__(self, height=0, abort_on_stop=True, **action_kwargs):
"""height is a percentage from 0 to 1"""
self.height = height
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop)
def action_launcher(self):
# Temporary hack supplied by Mark Wesley at Anki
msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(True)
self.robot.conn.send_msg(msg)
return self.robot.set_lift_height(self.height, **self.action_kwargs)
class SetLiftAngle(SetLiftHeight):
def __init__(self, angle, abort_on_stop=True, **action_kwargs):
#def get_theta(height):
# return math.asin((height-45)/66)
if isinstance(angle, cozmo.util.Angle):
angle = angle.degrees
self.angle = angle
super().__init__(0, abort_on_stop=abort_on_stop, **action_kwargs)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Angle):
self.angle = event.data.degrees
min_theta = cozmo.robot.MIN_LIFT_ANGLE.degrees
max_theta = cozmo.robot.MAX_LIFT_ANGLE.degrees
angle_range = max_theta - min_theta
self.height = (self.angle - min_theta) / angle_range
super().start(event)
class SdkDockWithCube(ActionNode):
"Uses SDK's dock_with_cube method."
def __init__(self, object=None, abort_on_stop=False, **action_kwargs):
self.object = object
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop=abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and \
isinstance(event.data,cozmo.objects.LightCube):
self.object = event.data
super().start(event)
def action_launcher(self):
if self.object is None:
raise ValueError('No cube to dock with')
return self.robot.dock_with_cube(self.object, **self.action_kwargs)
class SdkPickUpObject(ActionNode):
"Uses SDK's pick_up_object method."
def __init__(self, object=None, abort_on_stop=False, **action_kwargs):
self.object = object
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop=abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and \
isinstance(event.data,cozmo.objects.LightCube):
self.object = event.data
super().start(event)
def action_launcher(self):
if self.object is None:
raise ValueError('No object to pick up')
return self.robot.pickup_object(self.object, **self.action_kwargs)
class SdkPlaceObjectOnGroundHere(ActionNode):
"Uses SDK's place_object_on_ground_here method."
def __init__(self, object=None, abort_on_stop=False, **action_kwargs):
self.object = object
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop=abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and \
isinstance(event.data,cozmo.objects.LightCube):
self.object = event.data
super().start(event)
def action_launcher(self):
if self.object is None:
raise ValueError('No object to place')
return self.robot.place_object_on_ground_here(self.object, **self.action_kwargs)
class SdkPlaceOnObject(ActionNode):
"Uses SDK's place_on_object method."
def __init__(self, object=None, abort_on_stop=False, **action_kwargs):
self.object = object
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop=abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and \
isinstance(event.data,cozmo.objects.LightCube):
self.object = event.data
super().start(event)
def action_launcher(self):
if self.object is None:
raise ValueError('No object to place')
return self.robot.place_on_object(self.object, **self.action_kwargs)
class SdkRollCube(ActionNode):
"Uses SDK's roll_cube method."
def __init__(self, object=None, abort_on_stop=True, **action_kwargs):
self.object = object
self.action_kwargs = action_kwargs
super().__init__(abort_on_stop=abort_on_stop)
def start(self,event=None):
if self.running: return
if isinstance(event, DataEvent) and \
isinstance(event.data,cozmo.objects.LightCube):
self.object = event.data
super().start(event)
def action_launcher(self):
if self.object is None:
raise ValueError('No object to roll')
return self.robot.roll_cube(self.object, **self.action_kwargs)
# Note: additional nodes for object manipulation are in pickup.fsm.
#________________ Animations ________________
class AnimationNode(ActionNode):
def __init__(self, anim_name='anim_bored_01', **kwargs):
self.anim_name = anim_name
self.action_kwargs = kwargs
super().__init__()
def action_launcher(self):
return self.robot.play_anim(self.anim_name, **self.action_kwargs)
class AnimationTriggerNode(ActionNode):
def __init__(self, trigger=cozmo.anim.Triggers.CubePouncePounceNormal, **kwargs):
if not isinstance(trigger, cozmo.anim._AnimTrigger):
raise TypeError('%s is not an instance of cozmo.anim._AnimTrigger' %
repr(trigger))
self.trigger = trigger
self.action_kwargs = kwargs
super().__init__()
def action_launcher(self):
return self.robot.play_anim_trigger(self.trigger, **self.action_kwargs)
#________________ Behaviors ________________
class StartBehavior(StateNode):
def __init__(self, behavior=None, stop_on_exit=True):
if not isinstance(behavior, cozmo.behavior._BehaviorType):
raise ValueError("'%s' isn't an instance of cozmo.behavior._BehaviorType" %
repr(behavior))
self.behavior = behavior
self.behavior_handle = None
self.stop_on_exit = stop_on_exit
super().__init__()
def __repr__(self):
if self.behavior_handle:
return '<%s %s active=%s>' % \
(self.__class__.__name__, self.name, self.behavior_handle.is_active)
else:
return super().__repr__()
def start(self,event=None):
if self.running: return
super().start(event)
try:
if self.robot.behavior_handle:
self.robot.behavior_handle.stop()
except: pass
finally:
self.robot.behavior_handle = None
self.behavior_handle = self.robot.start_behavior(self.behavior)
self.robot.behavior_handle = self.behavior_handle
self.post_completion()
def stop(self):
if not self.running: return
if self.stop_on_exit and self.behavior_handle is self.robot.behavior_handle:
self.robot.behavior_handle.stop()
self.robot.behavior_handle = None
super().stop()
class StopBehavior(StateNode):
def start(self,event=None):
if self.running: return
super().start(event)
try:
if self.robot.behavior_handle:
self.robot.behavior_handle.stop()
except: pass
self.robot.behavior_handle = None
self.post_completion()
class FindFaces(StartBehavior):
def __init__(self,stop_on_exit=True):
super().__init__(cozmo.robot.behavior.BehaviorTypes.FindFaces,stop_on_exit)
class KnockOverCubes(StartBehavior):
def __init__(self,stop_on_exit=True):
super().__init__(cozmo.robot.behavior.BehaviorTypes.KnockOverCubes,stop_on_exit)
class LookAroundInPlace(StartBehavior):
def __init__(self,stop_on_exit=True):
super().__init__(cozmo.robot.behavior.BehaviorTypes.LookAroundInPlace,stop_on_exit)
class PounceOnMotion(StartBehavior):
def __init__(self,stop_on_exit=True):
super().__init__(cozmo.robot.behavior.BehaviorTypes.PounceOnMotion,stop_on_exit)
class RollBlock(StartBehavior):
def __init__(self,stop_on_exit=True):
super().__init__(cozmo.robot.behavior.BehaviorTypes.RollBlock,stop_on_exit)
class StackBlocks(StartBehavior):
def __init__(self,stop_on_exit=True):
super().__init__(cozmo.robot.behavior.BehaviorTypes.StackBlocks,stop_on_exit)
#________________ Multiprocessing ________________
class LaunchProcess(StateNode):
def __init__(self):
super().__init__()
self.process = None
@staticmethod
def process_workhorse(reply_token):
"""
Override this static method with the code to do your computation.
The method must be static because we can't pickle methods of StateNode
instances.
"""
print('*** Failed to override process_workhorse for LaunchProcess node ***')
print('Sleeping for 2 seconds...')
time.sleep(2)
# A process returns its result to the caller as an event.
result = 42
LaunchProcess.post_event(reply_token,DataEvent(result)) # source must be None for pickling
LaunchProcess.post_event(reply_token,CompletionEvent()) # we can post more than one event
@staticmethod
def post_event(reply_token,event):
id,queue = reply_token
event_pair = (id, event)
queue.put(event_pair)
def create_process(self, reply_token):
p = Process(target=self.__class__.process_workhorse,
args=[reply_token])
return p
def start(self, event=None):
super().start(event)
reply_token = (id(self), self.robot.erouter.interprocess_queue)
self.process = self.create_process(reply_token)
self.robot.erouter.add_process_node(self)
self.process.start()
print('Launched', self.process)
def stop(self):
if self.process:
print('Exiting',self.process,self.process.is_alive())
self.process = None
super().stop()
self.robot.erouter.delete_process_node(self)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,023
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/event_monitor.py
|
"""
Event Monitor Tool for Cozmo
============================
Usage:
monitor(robot) to monitor all event types in the dispatch table
monitor(robot, Event) to monitor a specific type of event
unmonitor(robot[, Event]) to turn off monitoring
Author: David S. Touretzky, Carnegie Mellon University
=====
ChangeLog
=========
* Add event handlers to world instead of to robot.
Dave Touretzky
- Many events (e.g. face stuff) aren't reliably sent to robot.
* Renaming and more face support
Dave Touretzky
- Renamed module to event_monitor
- Renamed monitor_on/off to monitor/unmonitor
- Added monitor_face to handle face events
* Created
Dave Touretzky
"""
import re
import cozmo
def print_prefix(evt):
robot.world.last_event = evt
print('-> ', evt.event_name, ' ', sep='', end='')
def print_object(obj):
if isinstance(obj,cozmo.objects.LightCube):
cube_id = next(k for k,v in robot.world.light_cubes.items() if v==obj)
print('LightCube-',cube_id,sep='',end='')
else:
r = re.search('<(\w*)', obj.__repr__())
print(r.group(1), end='')
def monitor_generic(evt, **kwargs):
print_prefix(evt)
if 'behavior_type_name' in kwargs:
print(kwargs['behavior_type_name'], '', end='')
print(' ', end='')
if 'obj' in kwargs:
print_object(kwargs['obj'])
print(' ', end='')
if 'action' in kwargs:
action = kwargs['action']
if isinstance(action, cozmo.anim.Animation):
print(action.anim_name, '', end='')
elif isinstance(action, cozmo.anim.AnimationTrigger):
print(action.trigger.name, '', end='')
print(set(kwargs.keys()))
def monitor_EvtActionCompleted(evt, action, state, failure_code, failure_reason, **kwargs):
print_prefix(evt)
print_object(action)
if isinstance(action, cozmo.anim.Animation):
print('', action.anim_name, end='')
elif isinstance(action, cozmo.anim.AnimationTrigger):
print('', action.trigger.name, end='')
print('',state,end='')
if failure_code is not None:
print('',failure_code,failure_reason,end='')
print()
def monitor_EvtObjectTapped(evt, *, obj, tap_count, tap_duration, tap_intensity, **kwargs):
print_prefix(evt)
print_object(obj)
print(' count=', tap_count,
' duration=', tap_duration, ' intensity=', tap_intensity, sep='')
def monitor_EvtObjectMovingStarted(evt, *, obj, acceleration, **kwargs):
print_prefix(evt)
print_object(obj)
print(' accleration=', acceleration, sep='')
def monitor_EvtObjectMovingStopped(evt, *, obj, move_duration, **kwargs):
print_prefix(evt)
print_object(obj)
print(' move_duration=%3.1f secs' %move_duration)
def monitor_face(evt, face, **kwargs):
print_prefix(evt)
name = face.name if face.name != '' else '[unknown face]'
expr = face.expression if face.expression is not None else 'expressionless'
kw = set(kwargs.keys()) if len(kwargs) > 0 else '{}'
print(name, ' (%s) ' % expr, ' face_id=', face.face_id, ' ', kw, sep='')
dispatch_table = {
cozmo.action.EvtActionStarted : monitor_generic,
cozmo.action.EvtActionCompleted : monitor_EvtActionCompleted,
cozmo.behavior.EvtBehaviorStarted : monitor_generic,
cozmo.behavior.EvtBehaviorStopped : monitor_generic,
cozmo.anim.EvtAnimationsLoaded : monitor_generic,
cozmo.anim.EvtAnimationCompleted : monitor_EvtActionCompleted,
cozmo.objects.EvtObjectAppeared : monitor_generic,
cozmo.objects.EvtObjectDisappeared : monitor_generic,
cozmo.objects.EvtObjectMovingStarted : monitor_EvtObjectMovingStarted,
cozmo.objects.EvtObjectMovingStopped : monitor_EvtObjectMovingStopped,
cozmo.objects.EvtObjectObserved : monitor_generic,
cozmo.objects.EvtObjectTapped : monitor_EvtObjectTapped,
cozmo.faces.EvtFaceAppeared : monitor_face,
cozmo.faces.EvtFaceObserved : monitor_face,
cozmo.faces.EvtFaceDisappeared : monitor_face,
}
excluded_events = { # Occur too frequently to monitor by default
cozmo.objects.EvtObjectObserved,
cozmo.faces.EvtFaceObserved,
}
def monitor(_robot, evt_class=None):
if not isinstance(_robot, cozmo.robot.Robot):
raise TypeError('First argument must be a Robot instance')
if evt_class is not None and not issubclass(evt_class, cozmo.event.Event):
raise TypeError('Second argument must be an Event subclass')
global robot
robot = _robot
if evt_class in dispatch_table:
robot.world.add_event_handler(evt_class,dispatch_table[evt_class])
elif evt_class is not None:
robot.world.add_event_handler(evt_class,monitor_generic)
else:
for k,v in dispatch_table.items():
if k not in excluded_events:
robot.world.add_event_handler(k,v)
def unmonitor(_robot, evt_class=None):
if not isinstance(_robot, cozmo.robot.Robot):
raise TypeError('First argument must be a Robot instance')
if evt_class is not None and not issubclass(evt_class, cozmo.event.Event):
raise TypeError('Second argument must be an Event subclass')
global robot
robot = _robot
try:
if evt_class in dispatch_table:
robot.world.remove_event_handler(evt_class,dispatch_table[evt_class])
elif evt_class is not None:
robot.world.remove_event_handler(evt_class,monitor_generic)
else:
for k,v in dispatch_table.items():
robot.world.remove_event_handler(k,v)
except Exception:
pass
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,024
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/obstavoidance.py
|
from cozmo.util import Pose
from numpy import matrix, tan, arctan2
try: from cv2 import Rodrigues
except: pass
from .nodes import *
from .transitions import *
from .geometry import wrap_angle
from .pilot import PilotToPose, PilotCheckStart
from .worldmap import WallObj
from time import sleep
class GoToWall(StateNode):
def __init__(self, wall=None, door=-1):
super().__init__()
self.object = wall
if isinstance(wall, int):
self.wall_name = 'Wall-'+str(wall)
elif isinstance(wall, str):
self.wall_name = wall
elif wall is None:
self.wall_name = None
else:
raise ValueError('wall should be an integer, string, or None, not %r' % wall)
self.door_id = door
def start(self,event=None):
if self.wall_name is None:
self.wall_name = self.find_closest_wall()
if self.wall_name in self.robot.world.world_map.objects:
self.wobj = self.robot.world.world_map.objects[self.wall_name]
else:
print("GoToWall: %s is not in the map." % self.wall_name)
super().start(event)
self.post_failure()
return
if self.wobj != -1:
if self.door_id == -1:
self.door_coordinates = -1
print("Going to closest door")
super().start(event)
elif self.door_id in self.wobj.door_ids:
self.door_coordinates = self.wobj.markers[self.door_id][1]
print(self.door_coordinates)
super().start(event)
else:
print(self.door_id,"is not a door")
super().start(event)
self.post_failure()
def find_closest_wall(self):
(x,y,theta) = self.robot.world.particle_filter.pose
walls = []
for obj in self.robot.world.world_map.objects.values():
if isinstance(obj,WallObj):
distsq = (x-obj.x)**2 + (y-obj.y)**2
walls.append((distsq,obj))
walls = sorted(walls, key=lambda x: x[0])
return 'Wall-%d' % walls[0][1].id if walls else None
def pick_side(self, dist):
wall = self.object
door_coordinates = self.door_coordinates
x = self.wobj.x
y = self.wobj.y
ang = self.wobj.theta
rx = self.robot.world.particle_filter.pose[0]
ry = self.robot.world.particle_filter.pose[1]
l = self.wobj.length/2
if door_coordinates == -1:
door_ids = self.wobj.door_ids
sides = []
for id in door_ids:
door_coordinates = self.wobj.markers[id][1]
s = self.wobj.markers[id][0]
sides.append((x - s*cos(ang)*dist - sin(ang)*(l - door_coordinates[0]),
y - s*sin(ang)*dist + cos(ang)*( l - door_coordinates[0]),
wrap_angle(ang+(1-s)*pi/2), id))
sorted_sides = sorted(sides, key=lambda pt: (pt[0]-rx)**2 + (pt[1]-ry)**2)
self.door_id = sorted_sides[0][3]
self.door_coordinates = self.wobj.markers[self.door_id][1]
print("Going to door", self.door_id )
shortest = sorted_sides[0][0:3]
else:
side1 = (x + cos(ang)*dist - sin(ang)*(self.wobj.length/2 - door_coordinates[0]),
y + sin(ang)*dist + cos(ang)*( self.wobj.length/2 - door_coordinates[0]),
wrap_angle(ang+pi))
side2 = (x - cos(ang)*dist - sin(ang)*(self.wobj.length/2 - door_coordinates[0]),
y - sin(ang)*dist + cos(ang)*( self.wobj.length/2 - door_coordinates[0]),
wrap_angle(ang))
sides = [side1, side2]
sorted_sides = sorted(sides, key=lambda pt: (pt[0]-rx)**2 + (pt[1]-ry)**2)
shortest = sorted_sides[0]
return shortest
class TurnToSide(Turn):
def __init__(self):
super().__init__()
def start(self, event=None):
wall = self.parent.object
wobj = self.parent.wobj
(x, y, ang) = self.parent.pick_side(150)
dtheta = wrap_angle(ang - self.robot.world.particle_filter.pose_estimate()[2])
if abs(dtheta) > 0.1:
self.angle = Angle(dtheta)
super().start(event)
else:
self.angle = Angle(0)
super().start(event)
self.post_success()
class GoToSide(PilotToPose):
def __init__(self):
super().__init__(None)
def start(self, event=None):
wall = self.parent.object
print('Selected wall',self.parent.wobj)
(x, y, theta) = self.parent.pick_side(150)
self.target_pose = Pose(x, y, self.robot.pose.position.z,
angle_z=Angle(radians = wrap_angle(theta)))
print('Traveling to',self.target_pose)
super().start(event)
class ReportPosition(StateNode):
def start(self,event=None):
super().start(event)
wall = self.parent.object
wobj = self.parent.wobj
cx = wobj.x
cy = wobj.y
rx = self.robot.pose.position.x
ry = self.robot.pose.position.y
dx = cx - rx
dy = cy - ry
dist = math.sqrt(dx*dx + dy*dy)
bearing = wrap_angle(atan2(dy,dx) - self.robot.pose.rotation.angle_z.radians) * 180/pi
print('wall at (%5.1f,%5.1f) robot at (%5.1f,%5.1f) dist=%5.1f brg=%5.1f' %
(cx, cy, rx, ry, dist, bearing))
class TurnToWall(Turn):
def __init__(self):
super().__init__()
def start(self, event=None):
if self.running: return
cube = self.parent.object
door_id = self.parent.door_id
for i in range(4):
if door_id not in self.robot.world.aruco.seen_marker_ids:
#Check three times that the marker is not visible
if i > 2:
self.angle = Angle(degrees=0)
super().start(event)
self.post_failure()
break
else:
sleep(0.1)
continue
else:
while True:
rx = self.robot.pose.position.x
ry = self.robot.pose.position.y
rt = self.robot.pose.rotation.angle_z.radians
marker = self.robot.world.aruco.seen_marker_objects.get(door_id,0)
if marker!=0:
break
sensor_dist = marker.camera_distance
sensor_bearing = atan2(marker.camera_coords[0],
marker.camera_coords[2])
sensor_orient = - marker.opencv_rotation[1] * (pi/180)
direction = rt + sensor_bearing
dx = sensor_dist * cos(direction)
dy = sensor_dist * sin(direction)
cx = rx + dx
cy = ry + dy
dist = math.sqrt(dx*dx + dy*dy)
self.angle = wrap_angle(atan2(dy,dx) - self.robot.pose.rotation.angle_z.radians) \
* 180/pi
if abs(self.angle) < 2:
self.angle = 0
self.angle = Angle(degrees=self.angle)
#print("TurnToWall", self.angle)
super().start(event)
break
class ForwardToWall(Forward):
def __init__(self, offset):
self.offset = offset
super().__init__()
def start(self, event=None):
if self.running: return
door_id = self.parent.door_id
rx = self.robot.pose.position.x
ry = self.robot.pose.position.y
rt = self.robot.pose.rotation.angle_z.radians
if door_id in self.robot.world.aruco.seen_marker_objects:
marker = self.robot.world.aruco.seen_marker_objects[door_id]
sensor_dist = marker.camera_distance
sensor_bearing = atan2(marker.camera_coords[0],
marker.camera_coords[2])
sensor_orient = - marker.opencv_rotation[1] * (pi/180)
direction = rt + sensor_bearing
dx = sensor_dist * cos(direction)
dy = sensor_dist * sin(direction)
cx = rx + dx
cy = ry + dy
dist = math.sqrt(dx*dx + dy*dy)
self.distance = Distance(sqrt(dx*dx + dy*dy) - self.offset)
super().start(event)
else:
self.distance = Distance(0)
super().start(event)
self.post_failure()
class FindWall(SetHeadAngle):
def __init__(self):
super().__init__()
def start(self, event=None):
if self.running: return
door_id = self.parent.door_id
if door_id not in self.robot.world.aruco.seen_marker_ids:
#print('Looking higher for wall')
if self.robot.head_angle.degrees < 40:
self.angle = Angle(self.robot.head_angle.radians + 0.15)
super().start(event)
else:
self.angle = self.robot.head_angle
super().start(event)
else:
self.angle = self.robot.head_angle
super().start(event)
# GoToWall state machine
def setup(self):
"""
droplift: SetLiftHeight(0) =T(0.5)=> check_start # time for vision to set up world map
check_start: PilotCheckStart()
check_start =S=> SetHeadAngle(0) =C=> turn_to_side
check_start =F=> Forward(-80) =C=> check_start
turn_to_side: self.TurnToSide()
turn_to_side =C=> turn_to_side
turn_to_side =S=> self.ReportPosition() =N=> go_side
go_side: self.GoToSide() =C=> self.TurnToSide() =C=> lookup
lookup: SetHeadAngle(35) =C=> find
find: self.TurnToWall() =C=>approach
find =F=> Forward(-80) =C=> StateNode() =T(1)=> find2
find2: self.TurnToWall() =C=>approach
find2 =F=> Forward(-80) =C=> Say("No Door trying again") =C=> turn_to_side
approach: self.ForwardToWall(100) =C=> self.FindWall() =C=>
self.TurnToWall() =C=> self.FindWall() =C=>
self.ForwardToWall(70) =C=> self.FindWall() =C=>
self.TurnToWall()=C=> end
approach =F=> end
end: SetHeadAngle(0) =C=> Forward(150) =C=> ParentCompletes()
"""
# Code generated by genfsm on Fri Apr 6 04:49:50 2018:
droplift = SetLiftHeight(0) .set_name("droplift") .set_parent(self)
check_start = PilotCheckStart() .set_name("check_start") .set_parent(self)
setheadangle1 = SetHeadAngle(0) .set_name("setheadangle1") .set_parent(self)
forward1 = Forward(-80) .set_name("forward1") .set_parent(self)
turn_to_side = self.TurnToSide() .set_name("turn_to_side") .set_parent(self)
reportposition1 = self.ReportPosition() .set_name("reportposition1") .set_parent(self)
go_side = self.GoToSide() .set_name("go_side") .set_parent(self)
turntoside1 = self.TurnToSide() .set_name("turntoside1") .set_parent(self)
lookup = SetHeadAngle(35) .set_name("lookup") .set_parent(self)
find = self.TurnToWall() .set_name("find") .set_parent(self)
forward2 = Forward(-80) .set_name("forward2") .set_parent(self)
statenode1 = StateNode() .set_name("statenode1") .set_parent(self)
find2 = self.TurnToWall() .set_name("find2") .set_parent(self)
forward3 = Forward(-80) .set_name("forward3") .set_parent(self)
say1 = Say("No Door trying again") .set_name("say1") .set_parent(self)
approach = self.ForwardToWall(100) .set_name("approach") .set_parent(self)
findwall1 = self.FindWall() .set_name("findwall1") .set_parent(self)
turntowall1 = self.TurnToWall() .set_name("turntowall1") .set_parent(self)
findwall2 = self.FindWall() .set_name("findwall2") .set_parent(self)
forwardtowall1 = self.ForwardToWall(70) .set_name("forwardtowall1") .set_parent(self)
findwall3 = self.FindWall() .set_name("findwall3") .set_parent(self)
turntowall2 = self.TurnToWall() .set_name("turntowall2") .set_parent(self)
end = SetHeadAngle(0) .set_name("end") .set_parent(self)
forward4 = Forward(150) .set_name("forward4") .set_parent(self)
parentcompletes1 = ParentCompletes() .set_name("parentcompletes1") .set_parent(self)
timertrans1 = TimerTrans(0.5) .set_name("timertrans1")
timertrans1 .add_sources(droplift) .add_destinations(check_start)
successtrans1 = SuccessTrans() .set_name("successtrans1")
successtrans1 .add_sources(check_start) .add_destinations(setheadangle1)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(setheadangle1) .add_destinations(turn_to_side)
failuretrans1 = FailureTrans() .set_name("failuretrans1")
failuretrans1 .add_sources(check_start) .add_destinations(forward1)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(forward1) .add_destinations(check_start)
completiontrans3 = CompletionTrans() .set_name("completiontrans3")
completiontrans3 .add_sources(turn_to_side) .add_destinations(turn_to_side)
successtrans2 = SuccessTrans() .set_name("successtrans2")
successtrans2 .add_sources(turn_to_side) .add_destinations(reportposition1)
nulltrans1 = NullTrans() .set_name("nulltrans1")
nulltrans1 .add_sources(reportposition1) .add_destinations(go_side)
completiontrans4 = CompletionTrans() .set_name("completiontrans4")
completiontrans4 .add_sources(go_side) .add_destinations(turntoside1)
completiontrans5 = CompletionTrans() .set_name("completiontrans5")
completiontrans5 .add_sources(turntoside1) .add_destinations(lookup)
completiontrans6 = CompletionTrans() .set_name("completiontrans6")
completiontrans6 .add_sources(lookup) .add_destinations(find)
completiontrans7 = CompletionTrans() .set_name("completiontrans7")
completiontrans7 .add_sources(find) .add_destinations(approach)
failuretrans2 = FailureTrans() .set_name("failuretrans2")
failuretrans2 .add_sources(find) .add_destinations(forward2)
completiontrans8 = CompletionTrans() .set_name("completiontrans8")
completiontrans8 .add_sources(forward2) .add_destinations(statenode1)
timertrans2 = TimerTrans(1) .set_name("timertrans2")
timertrans2 .add_sources(statenode1) .add_destinations(find2)
completiontrans9 = CompletionTrans() .set_name("completiontrans9")
completiontrans9 .add_sources(find2) .add_destinations(approach)
failuretrans3 = FailureTrans() .set_name("failuretrans3")
failuretrans3 .add_sources(find2) .add_destinations(forward3)
completiontrans10 = CompletionTrans() .set_name("completiontrans10")
completiontrans10 .add_sources(forward3) .add_destinations(say1)
completiontrans11 = CompletionTrans() .set_name("completiontrans11")
completiontrans11 .add_sources(say1) .add_destinations(turn_to_side)
completiontrans12 = CompletionTrans() .set_name("completiontrans12")
completiontrans12 .add_sources(approach) .add_destinations(findwall1)
completiontrans13 = CompletionTrans() .set_name("completiontrans13")
completiontrans13 .add_sources(findwall1) .add_destinations(turntowall1)
completiontrans14 = CompletionTrans() .set_name("completiontrans14")
completiontrans14 .add_sources(turntowall1) .add_destinations(findwall2)
completiontrans15 = CompletionTrans() .set_name("completiontrans15")
completiontrans15 .add_sources(findwall2) .add_destinations(forwardtowall1)
completiontrans16 = CompletionTrans() .set_name("completiontrans16")
completiontrans16 .add_sources(forwardtowall1) .add_destinations(findwall3)
completiontrans17 = CompletionTrans() .set_name("completiontrans17")
completiontrans17 .add_sources(findwall3) .add_destinations(turntowall2)
completiontrans18 = CompletionTrans() .set_name("completiontrans18")
completiontrans18 .add_sources(turntowall2) .add_destinations(end)
failuretrans4 = FailureTrans() .set_name("failuretrans4")
failuretrans4 .add_sources(approach) .add_destinations(end)
completiontrans19 = CompletionTrans() .set_name("completiontrans19")
completiontrans19 .add_sources(end) .add_destinations(forward4)
completiontrans20 = CompletionTrans() .set_name("completiontrans20")
completiontrans20 .add_sources(forward4) .add_destinations(parentcompletes1)
return self
class Exploren(StateNode):
def __init__(self):
self.current_wall = None
self.to_do_wall = []
self.done_wall = []
super().__init__()
class Think(StateNode):
def start(self,event=None):
super().start(event)
for key, val in self.robot.world.world_map.objects.items():
if isinstance(val,WallObj) and val.id not in self.parent.done_wall and val.id not in self.parent.to_do_wall:
self.parent.to_do_wall.append(val)
print(val.id)
if len(self.parent.to_do_wall) > 0:
wall = self.parent.to_do_wall.pop()
self.parent.current_wall = wall.id
self.parent.done_wall.append(wall.id)
print(self.parent.to_do_wall,self.parent.current_wall,self.parent.done_wall)
self.post_failure()
else:
self.post_success()
class Go(GoToWall):
def __init__(self):
super().__init__()
def start(self,event=None):
self.object = self.parent.current_wall
self.wall_name = 'Wall-'+str(self.object)
self.door_id = -1
super().start(event)
# Explore state machine
def setup(self):
"""
look: LookAroundInPlace(stop_on_exit=False) =T(5)=> StopBehavior() =C=> think
think: self.Think()
think =F=> go
think =S=> end
go: self.Go() =C=> look
end: Say("Done") =C=> ParentCompletes()
"""
# Code generated by genfsm on Fri Apr 6 04:49:50 2018:
look = LookAroundInPlace(stop_on_exit=False) .set_name("look") .set_parent(self)
stopbehavior1 = StopBehavior() .set_name("stopbehavior1") .set_parent(self)
think = self.Think() .set_name("think") .set_parent(self)
go = self.Go() .set_name("go") .set_parent(self)
end = Say("Done") .set_name("end") .set_parent(self)
parentcompletes2 = ParentCompletes() .set_name("parentcompletes2") .set_parent(self)
timertrans3 = TimerTrans(5) .set_name("timertrans3")
timertrans3 .add_sources(look) .add_destinations(stopbehavior1)
completiontrans21 = CompletionTrans() .set_name("completiontrans21")
completiontrans21 .add_sources(stopbehavior1) .add_destinations(think)
failuretrans5 = FailureTrans() .set_name("failuretrans5")
failuretrans5 .add_sources(think) .add_destinations(go)
successtrans3 = SuccessTrans() .set_name("successtrans3")
successtrans3 .add_sources(think) .add_destinations(end)
completiontrans22 = CompletionTrans() .set_name("completiontrans22")
completiontrans22 .add_sources(go) .add_destinations(look)
completiontrans23 = CompletionTrans() .set_name("completiontrans23")
completiontrans23 .add_sources(end) .add_destinations(parentcompletes2)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,025
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/path_viewer.py
|
"""
Path planner display in OpenGL.
"""
try:
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
pass
import time
from math import pi, sin, cos
import array
import numpy as np
import platform
WINDOW = None
WINDOW_WF = None
from . import opengl
from .rrt import RRTNode
from .rrt_shapes import *
from .wavefront import WaveFront
from . import geometry
from .geometry import wrap_angle
the_rrt = None
old_grid = None
the_items = [] # each item is a tuple (tree,color)
help_text = """
Path viewer commands:
arrows Translate the view up/down/left/right
Home Center the view (zero translation)
< Zoom in
> Zoom out
o Show objects
b Show obstacles
p Show pose
space Toggle redisplay (for debugging)
h Print this help text
"""
help_text_mac = """
Path viewer commands:
arrows Translate the view up/down/left/right
fn + left-arrow Center the view (zero translation)
option + < Zoom in
option + > Zoom out
option + o Show objects
option + b Show obstacles
option + p Show pose
space Toggle redisplay (for debugging)
option + h Print this help text
"""
class PathViewer():
def __init__(self, robot, rrt,
width=512, height=512,
windowName = "path viewer",
bgcolor = (0,0,0)):
global the_rrt, the_items
the_rrt = rrt
the_items = []
self.robot = robot
self.width = width
self.height = height
self.bgcolor = bgcolor
self.aspect = self.width/self.height
self.windowName = windowName
self.translation = [0., 0.] # Translation in mm
self.scale = 0.64
def window_creator(self):
global WINDOW
WINDOW = opengl.create_window(bytes(self.windowName,'utf-8'), (self.width,self.height))
glutDisplayFunc(self.display)
glutReshapeFunc(self.reshape)
glutKeyboardFunc(self.keyPressed)
glutSpecialFunc(self.specialKeyPressed)
glViewport(0,0,self.width,self.height)
glClearColor(*self.bgcolor, 0)
# Enable transparency
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
def window_creator_wf(self):
global WINDOW_WF
WINDOW_WF = opengl.create_window(bytes('wavefront grid','utf-8'), (self.width,self.height))
glutDisplayFunc(self.display_wf)
# glutReshapeFunc(self.reshape)
glutKeyboardFunc(self.keyPressed)
glutSpecialFunc(self.specialKeyPressed)
glViewport(0,0,self.width,self.height)
glClearColor(*self.bgcolor, 0)
# Enable transparency
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
def start(self): # Displays in background
opengl.init()
if not WINDOW:
opengl.CREATION_QUEUE.append(self.window_creator)
if not WINDOW_WF:
opengl.CREATION_QUEUE.append(self.window_creator_wf)
if platform.system() == 'Darwin':
print("Type 'option' + 'h' in the path viewer window for help.")
else:
print("Type 'h' in the path viewer window for help.")
def clear(self):
global the_items, old_grid
the_items = []
old_grid = np.zeros([1,1], dtype=np.int32)
the_rrt.grid_display = None
the_rrt.draw_path = None
the_rrt.treeA = []
the_rrt.treeB = []
def set_rrt(self,new_rrt):
global the_rrt
the_rrt = new_rrt
def draw_rectangle(self, center, width=4, height=None,
angle=0, color=(1,1,1), fill=True):
# Default to solid color and square shape
if len(color)==3:
color = (color[0],color[1],color[2],1)
if height is None:
height = width
# Calculate vertices as offsets from center
w = width/2; h = height/2
v1 = (-w,-h); v2 = (w,-h); v3 = (w,h); v4 = (-w,h)
# Draw the rectangle
glPushMatrix()
if fill:
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)
else:
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE)
glColor4f(color[0],color[1],color[2],color[3])
glTranslatef(*center,0)
glRotatef(angle,0,0,1)
glBegin(GL_QUADS)
glVertex2f(*v1)
glVertex2f(*v2)
glVertex2f(*v3)
glVertex2f(*v4)
glEnd()
glPopMatrix()
def draw_circle(self,center,radius=1,color=(1,1,1),fill=True):
if len(color) == 3:
color = (*color,1)
glColor4f(*color)
if fill:
glBegin(GL_TRIANGLE_FAN)
glVertex2f(*center)
else:
glBegin(GL_LINE_LOOP)
for angle in range(0,360):
theta = angle/180*pi
glVertex2f(center[0]+radius*cos(theta), center[1]+radius*sin(theta))
glEnd()
def draw_triangle(self,center,scale=1,angle=0,color=(1,1,1),fill=True):
# Default to solid color
if len(color) == 3:
color = (*color,1)
glPushMatrix()
if fill:
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)
else:
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE)
glColor4f(*color)
glTranslatef(*center,0)
glRotatef(angle,0,0,1)
glBegin(GL_TRIANGLES)
glVertex2f( 5.*scale, 0.)
glVertex2f(-5.*scale, -3.*scale)
glVertex2f(-5.*scale, 3.*scale)
glEnd()
glPopMatrix()
def draw_line(self,pt1,pt2,color=(1,1,1,1)):
if len(color) == 3:
color = (*color,1)
glBegin(GL_LINES)
glColor4f(*color)
glVertex2f(*pt1)
glVertex2f(*pt2)
glEnd()
def draw_path(self,path):
""" Also used if WaveFront generated the path and we want to display it."""
if isinstance(path[0], RRTNode):
path = [(node.x,node.y) for node in path]
for i in range(len(path)-1):
self.draw_line(path[i],path[i+1])
def draw_tree(self,tree,color):
for node in tree:
self.draw_node(node,color)
def draw_node(self,node,color):
self.draw_rectangle((node.x,node.y), color=color)
if node.parent:
if node.radius is None or node.radius == 0:
self.draw_line((node.x,node.y), (node.parent.x,node.parent.y), color=color)
else:
color = (1, 1, 0.5)
init_x = node.parent.x
init_y = node.parent.y
init_q = node.parent.q
targ_q = node.q
radius = node.radius
dir = +1 if radius >= 0 else -1
r = abs(radius)
center = geometry.translate(init_x,init_y).dot(
geometry.aboutZ(init_q+dir*pi/2).dot(geometry.point(r)))
theta = wrap_angle(init_q - dir*pi/2)
targ_theta = wrap_angle(targ_q - dir*pi/2)
ang_step = 0.05 # radians
while abs(theta - targ_theta) > ang_step:
theta = wrap_angle(theta + dir * ang_step)
cur_x = center[0,0] + r*cos(theta)
cur_y = center[1,0] + r*sin(theta)
self.draw_line((init_x,init_y), (cur_x,cur_y), color=color)
(init_x,init_y) = (cur_x,cur_y)
def draw_robot(self,node):
parts = the_rrt.robot_parts_to_node(node)
for part in parts:
if isinstance(part,Circle):
self.draw_circle(center=(part.center[0,0],part.center[1,0]),
radius=part.radius,
color=(1,1,0,0.7), fill=False)
elif isinstance(part,Rectangle):
self.draw_rectangle(center=(part.center[0,0],part.center[1,0]),
width=part.max_Ex-part.min_Ex,
height=part.max_Ey-part.min_Ey,
angle=part.orient*180/pi,
color=(1,1,0,0.7), fill=False)
def draw_obstacle(self,obst):
if isinstance(obst,Circle):
self.draw_circle(center=(obst.center[0,0],obst.center[1,0]),
radius=obst.radius,
color=(1,0,0,0.5), fill=True)
elif isinstance(obst,Rectangle):
width = obst.max_Ex - obst.min_Ex
height = obst.max_Ey - obst.min_Ey
if width <= 10*height:
color = (1, 0, 0, 0.5)
else:
color = (1, 1, 0, 0.5)
self.draw_rectangle(center=(obst.center[0], obst.center[1]),
angle=obst.orient*(180/pi),
width=width, height=height, color=color, fill=True)
def draw_wf(self, grid):
square_size = 6
grid_flat = list(set(grid.flatten()))
grid_flat.sort()
goal_marker = WaveFront.goal_marker
try:
max_val = grid_flat[-2]
except IndexError:
max_val = max(grid_flat)
if max_val <= 0:
max_val = goal_marker
max_val = float(max_val)
w = square_size * 0.5
h = square_size * 0.5
for x in range(0, grid.shape[0]):
for y in range(0, grid.shape[1]):
c = (x*square_size, y*square_size)
try:
if grid[x,y] == goal_marker:
self.draw_rectangle(center=c, width=w, height=h, color=(0, 1, 0)) # green for goal
elif grid[x,y] == 1:
self.draw_rectangle(center=c, width=w, height=h, color=(1, 1, 0)) # yellow for start
elif grid[x,y] < 0:
self.draw_rectangle(center=c, width=w, height=h, color=(1, 0, 0)) # red for obstacle
else:
value = grid[x,y]/max_val # shades of gray for distance values
self.draw_rectangle(center=c, width=w, height=h, color=(value, value, value))
except IndexError:
# print('index is out of bounds', x, y)
pass
def add_tree(self, tree, color):
global the_items
the_items.append((tree,color))
def display(self):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
w = self.width / 2
glOrtho(-w, w, -w, w, 1, -1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glRotatef(90,0,0,1)
glScalef(self.scale, self.scale, self.scale)
glTranslatef(-self.translation[0], -self.translation[1], 0.)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
self.draw_rectangle(center=(0,0), angle=45, width=5, height=5, color=(0.9, 0.5, 0), fill=False)
if the_rrt.draw_path: # WaveFront-generated path
self.draw_path(the_rrt.draw_path)
self.draw_tree(the_rrt.treeA, color=(0,1,0))
self.draw_tree(the_rrt.treeB, color=(0,0,1))
for (tree,color) in the_items:
self.draw_tree(tree,color)
for obst in the_rrt.obstacles:
self.draw_obstacle(obst)
#if the_rrt.start:
# self.draw_robot(the_rrt.start)
pose = self.robot.world.particle_filter.pose
self.draw_robot(RRTNode(x=pose[0], y=pose[1], q=pose[2]))
glutSwapBuffers()
def display_wf(self):
global old_grid
grid = the_rrt.grid_display if the_rrt.grid_display is not None else old_grid
if grid is None: return
old_grid = grid
square_size = 5
w = max(grid.shape) * square_size / 2
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-w, w, -w, w, 1, -1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glRotatef(90,0,0,1)
glScalef(self.scale/2, self.scale/2, self.scale/2)
glTranslatef(-self.translation[0]-w, -self.translation[1]-w, 0.)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
self.draw_wf(grid)
glutSwapBuffers()
def reshape(self,width,height):
glViewport(0,0,width,height)
self.width = width
self.height = height
self.aspect = self.width/self.height
self.display()
glutPostRedisplay()
def keyPressed(self,key,mouseX,mouseY):
# print(str(key), ord(key))
if key == b'<': # zoom in
self.scale *= 1.25
self.print_display_params()
return
elif key == b'>': # zoom out
self.scale /= 1.25
self.print_display_params()
return
elif key == b'o': # show objects
self.robot.world.world_map.show_objects()
return
elif key == b'b': # show obstacles
self.show_obstacles()
return
elif key == b'p': # show pose
self.robot.world.world_map.show_pose()
return
elif key == b'h': # print help
self.print_help()
return
def specialKeyPressed(self, key, mouseX, mouseY):
# arrow keys for translation
incr = 25.0 # millimeters
if key == GLUT_KEY_UP:
self.translation[0] += incr / self.scale
elif key == GLUT_KEY_DOWN:
self.translation[0] -= incr / self.scale
elif key == GLUT_KEY_LEFT:
self.translation[1] += incr / self.scale
elif key == GLUT_KEY_RIGHT:
self.translation[1] -= incr / self.scale
elif key == GLUT_KEY_HOME:
self.translation = [0., 0.]
self.print_display_params()
glutPostRedisplay()
def print_display_params(self):
print('scale=%.2f translation=[%.1f, %.1f]' %
(self.scale, *self.translation))
def show_obstacles(self):
print('RRT has %d obstacles.' % len(the_rrt.obstacles))
for obstacle in the_rrt.obstacles:
print(' ', obstacle)
print()
def print_help(self):
if platform.system() == 'Darwin':
print(help_text_mac)
else:
print(help_text)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,026
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/sharedmap.py
|
import socket
import pickle
import threading
from time import sleep
from numpy import inf, arctan2, pi, cos, sin
from .worldmap import RobotForeignObj, LightCubeForeignObj, WallObj
from .geometry import wrap_angle
from cozmo.objects import LightCube
from copy import deepcopy
class ServerThread(threading.Thread):
def __init__(self, robot, port=1800):
threading.Thread.__init__(self)
self.port = port
self.socket = None #not running until startServer is called
self.robot= robot
self.camera_landmark_pool = {} # used to find transforms
self.poses = {}
self.started = False
self.foreign_objects = {} # foreign walls and cubes
def run(self):
self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.socket.setblocking(True)
self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) #enables server restart
self.socket.bind(("",self.port))
self.threads =[]
print("Server started")
self.started = True
self.fusion.start()
self.robot.world.is_server = True
for i in range(100): # Limit of 100 clients
self.socket.listen(5) # Now wait for client connection.
c, addr = self.socket.accept() # Establish connection with client.
print('Got connection from', addr)
self.threads.append(ClientHandlerThread(i, c, self.robot))
self.threads[i].start()
def start_server_thread(self):
if self.robot.aruco_id == -1:
self.robot.aruco_id = int(input("Please enter the aruco id of the robot:"))
self.robot.world.server.camera_landmark_pool[self.robot.aruco_id]={}
# try to get transforms from camera_landmark_pool
self.fusion = FusionThread(self.robot)
self.start()
class ClientHandlerThread(threading.Thread):
def __init__(self, threadID, client, robot):
threading.Thread.__init__(self)
self.threadID = threadID
self.c = client
self.robot = robot
self.c.sendall(pickle.dumps("Hello"))
self.aruco_id = int(pickle.loads(self.c.recv(1024)))
self.name = "Client-"+str(self.aruco_id)
self.robot.world.server.camera_landmark_pool[self.aruco_id]={}
self.to_send={}
print("Started thread for",self.name)
def run(self):
# Send from server to clients
while(True):
for key, value in self.robot.world.world_map.objects.items():
if isinstance(key,LightCube):
self.to_send["LightCubeForeignObj-"+str(value.id)]= LightCubeForeignObj(id=value.id, x=value.x, y=value.y, z=value.z, theta=value.theta)
elif isinstance(key,str):
# Send walls and cameras
self.to_send[key] = value # Fix case when object removed from shared map
else:
pass # Nothing else in sent
# append 'end' to end to mark end
self.c.sendall(pickle.dumps([self.robot.world.perched.camera_pool,self.to_send])+b'end')
# hack to recieve variable size data without crashing
data = b''
while True:
data += self.c.recv(1024)
if data[-3:]==b'end':
break
cams, landmarks, foreign_objects, pose = pickle.loads(data[:-3])
for key, value in cams.items():
if key in self.robot.world.perched.camera_pool:
self.robot.world.perched.camera_pool[key].update(value)
else:
self.robot.world.perched.camera_pool[key]=value
self.robot.world.server.camera_landmark_pool[self.aruco_id].update(landmarks)
self.robot.world.server.poses[self.aruco_id] = pose
self.robot.world.server.foreign_objects[self.aruco_id] = foreign_objects
class FusionThread(threading.Thread):
def __init__(self, robot):
threading.Thread.__init__(self)
self.robot = robot
self.aruco_id = self.robot.aruco_id
self.accurate = {}
self.transforms = {}
def run(self):
while(True):
# adding local camera landmarks into camera_landmark_pool
self.robot.world.server.camera_landmark_pool[self.aruco_id].update( \
{k:self.robot.world.particle_filter.sensor_model.landmarks[k] for k in \
[x for x in self.robot.world.particle_filter.sensor_model.landmarks.keys()\
if isinstance(x,str) and "Video" in x]})
flag = False
# Choose accurate camera
for key1, value1 in self.robot.world.server.camera_landmark_pool.items():
for key2, value2 in self.robot.world.server.camera_landmark_pool.items():
if key1 == key2:
continue
for cap, lan in value1.items():
if cap in value2:
varsum = lan[2].sum()+value2[cap][2].sum()
if varsum < self.accurate.get((key1,key2),(inf,None))[0]:
self.accurate[(key1,key2)] = (varsum,cap)
flag = True
# Find transform
if flag:
for key, value in self.accurate.items():
x1,y1 = self.robot.world.server.camera_landmark_pool[key[0]][value[1]][0]
h1,p1,t1 = self.robot.world.server.camera_landmark_pool[key[0]][value[1]][1]
x2,y2 = self.robot.world.server.camera_landmark_pool[key[1]][value[1]][0]
h2,p2,t2 = self.robot.world.server.camera_landmark_pool[key[1]][value[1]][1]
theta_t = wrap_angle(p1 - p2)
x_t = x2 - ( x1*cos(theta_t) + y1*sin(theta_t))
y_t = y2 - (-x1*sin(theta_t) + y1*cos(theta_t))
self.transforms[key] = (x_t, y_t, theta_t, value[1])
self.update_foreign_robot()
self.update_foreign_objects()
sleep(0.01)
def update_foreign_robot(self):
for key, value in self.transforms.items():
if key[1] == self.robot.aruco_id:
x_t, y_t, theta_t, cap = value
x, y, theta = self.robot.world.server.poses[key[0]]
x2 = x*cos(theta_t) + y*sin(theta_t) + x_t
y2 = -x*sin(theta_t) + y*cos(theta_t) + y_t
# improve using update function instead of new obj everytime
self.robot.world.world_map.objects["Foreign-"+str(key[0])]=RobotForeignObj(cozmo_id=key[0],
x=x2, y=y2, z=0, theta=wrap_angle(theta-theta_t), camera_id = int(cap[-2]))
def update_foreign_objects(self):
for key, value in self.transforms.items():
if key[1] == self.robot.aruco_id:
x_t, y_t, theta_t, cap = value
for k, v in self.robot.world.server.foreign_objects[key[0]].items():
x2 = v.x*cos(theta_t) + v.y*sin(theta_t) + x_t
y2 = -v.x*sin(theta_t) + v.y*cos(theta_t) + y_t
if isinstance(k,str) and "Wall" in k:
# update wall
if k in self.robot.world.world_map.objects:
if self.robot.world.world_map.objects[k].is_foreign:
self.robot.world.world_map.objects[k].update(x=x2, y=y2, theta=wrap_angle(v.theta-theta_t))
else:
copy_obj = deepcopy(v)
copy_obj.x = x2
copy_obj.y = y2
copy_obj.theta = wrap_angle(v.theta-theta_t)
copy_obj.is_foreign = True
self.robot.world.world_map.objects[k]=copy_obj
elif isinstance(k,str) and "Cube" in k and not self.robot.world.light_cubes[v.id].is_visible:
# update cube
if k in self.robot.world.world_map.objects:
if self.robot.world.world_map.objects[k].is_foreign:
self.robot.world.world_map.objects[k].update(x=x2, y=y2, theta=wrap_angle(v.theta-theta_t))
else:
copy_obj = deepcopy(v)
copy_obj.x = x2
copy_obj.y = y2
copy_obj.theta = wrap_angle(v.theta-theta_t)
copy_obj.is_foreign = True
self.robot.world.world_map.objects[k]=copy_obj
class ClientThread(threading.Thread):
def __init__(self, robot):
threading.Thread.__init__(self)
self.port = None
self.socket = None #not running until startClient is called
self.ipaddr = None
self.robot= robot
self.to_send = {}
def start_client_thread(self,ipaddr="",port=1800):
if self.robot.aruco_id == -1:
self.robot.aruco_id = int(input("Please enter the aruco id of the robot:"))
self.robot.world.server.camera_landmark_pool[self.robot.aruco_id]={}
self.port = port
self.ipaddr = ipaddr
self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
while True:
try:
print("Attempting to connect to %s at port %d" % (ipaddr,port))
self.socket.connect((ipaddr,port))
data = pickle.loads(self.socket.recv(1024))
break
except:
print("No server found, make sure the address is correct, retrying in 10 seconds")
sleep(10)
print("Connected.")
self.socket.sendall(pickle.dumps(self.robot.aruco_id))
self.robot.world.is_server = False
self.start()
def use_shared_map(self):
# currently affects only worldmap_viewer
# uses robot.world.world_map.shared_objects instead of robot.world.world_map.objects
self.robot.use_shared_map = True
def use_local_map(self):
self.robot.use_shared_map = False
def run(self):
# Send from client to server
while(True):
# hack to recieve variable size data without crashing
data = b''
while True:
data += self.socket.recv(1024)
if data[-3:]==b'end':
break
self.robot.world.perched.camera_pool, self.robot.world.world_map.shared_objects = pickle.loads(data[:-3])
for key, value in self.robot.world.world_map.objects.items():
if isinstance(key,LightCube):
self.to_send["LightCubeForeignObj-"+str(value.id)]= LightCubeForeignObj(id=value.id, cozmo_id=self.robot.aruco_id, x=value.x, y=value.y, z=value.z, theta=value.theta)
elif isinstance(key,str) and 'Wall' in key:
# Send walls
self.to_send[key] = value # Fix case when object removed from shared map
else:
pass
# send cameras, landmarks, objects and pose
self.socket.sendall(pickle.dumps([self.robot.world.perched.cameras,
{k:self.robot.world.particle_filter.sensor_model.landmarks[k] for k in
[x for x in self.robot.world.particle_filter.sensor_model.landmarks.keys()
if isinstance(x,str) and "Video" in x]},
self.to_send,
self.robot.world.particle_filter.pose])+b'end')
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,027
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/path_planner.py
|
"""
Path planner using RRT and Wavefront algorithms.
"""
from math import pi, sin, cos
from multiprocessing import Process
from .nodes import LaunchProcess
from .events import DataEvent, PilotEvent
from .pilot0 import NavPlan, NavStep
from .worldmap import WorldObject, LightCubeObj, ChargerObj, CustomMarkerObj, RoomObj, DoorwayObj, MapFaceObj
from .rrt import RRT, RRTNode, StartCollides, GoalCollides, GoalUnreachable
from .wavefront import WaveFront
from .geometry import wrap_angle, segment_intersect_test
from .doorpass import DoorPass
from . import rrt
class PathPlanner():
"""This path planner can be called directly, or it can be used inside
a PathPlannerProcess node that runs the heavy lifting portion of
the algorithm in a child process. Because child processes in
Windows don't share memory with the parent, we must transmit
certain data to the child as parameters during process creation.
But only structures that are pickle-able can be sent. The
setup_problem() method sets up those structures, and do_planning()
uses them to do the work. If we don't want to run in a separate
process then we can use plan_path_this_process() to call both
methods in the main process and return the result.
"""
# Note: the obstacle inflation parameter is a radius, not a diameter.
# Fat obstacles for the wavefefront algorithm because the robot
# itself is treated as a point. Since the robot is longer than it is wide,
# an inflation value less than the length (95 mm) could miss a collision if
# the robot turns.
fat_obstacle_inflation = 50 # must be << pilot's escape_distance
fat_wall_inflation = 35
fat_doorway_adjustment = -62
# Skinny obstacles for the RRT are skinny because we model the
# robot's shape explicitly.
skinny_obstacle_inflation = 10
skinny_wall_inflation = 10
skinny_doorway_adjustment = 0
@staticmethod
def plan_path_this_process(goal_object, robot, use_doorways=False):
# Get pickle-able data structures
(start_node, goal_shape, robot_parts, bbox,
fat_obstacles, skinny_obstacles, doorway_list, need_grid_display) = \
__class__.setup_problem(goal_object, robot, use_doorways)
# Do the actual path planning
result = \
__class__.do_planning(robot.world.rrt, start_node, goal_shape,
fat_obstacles, skinny_obstacles, doorway_list,
need_grid_display)
if isinstance(result, PilotEvent):
grid_display = result.args['grid_display']
elif isinstance(result, DataEvent):
(navplan, grid_display) = result.data
else:
ValueError('Bad result type:', result)
robot.world.rrt.grid_display = grid_display
return result
@staticmethod
def setup_problem(goal_object, robot, use_doorways):
"""Calculate values from world map in main process since the map won't
be available in the child process."""
# Fat obstacles and narrow doorways for WaveFront
robot.world.rrt.generate_obstacles(PathPlanner.fat_obstacle_inflation,
PathPlanner.fat_wall_inflation,
PathPlanner.fat_doorway_adjustment)
fat_obstacles = robot.world.rrt.obstacles
# Skinny obstacles and normal doorways for RRT
robot.world.rrt.generate_obstacles(PathPlanner.skinny_obstacle_inflation,
PathPlanner.skinny_wall_inflation,
PathPlanner.skinny_doorway_adjustment)
skinny_obstacles = robot.world.rrt.obstacles
(pose_x, pose_y, pose_theta) = robot.world.particle_filter.pose
start_node = RRTNode(x=pose_x, y=pose_y, q=pose_theta)
if isinstance(goal_object, (LightCubeObj,ChargerObj)):
goal_shape = RRT.generate_cube_obstacle(goal_object)
elif isinstance(goal_object, CustomMarkerObj):
goal_shape = RRT.generate_marker_obstacle(goal_object)
elif isinstance(goal_object, RoomObj):
goal_shape = RRT.generate_room_obstacle(goal_object)
elif isinstance(goal_object, MapFaceObj):
goal_shape = RRT.generate_mapFace_obstacle(goal_object)
else:
raise ValueError("Can't convert path planner goal %s to shape." % goal_object)
robot_parts = robot.world.rrt.make_robot_parts(robot)
bbox = robot.world.rrt.compute_bounding_box()
if use_doorways:
doorway_list = robot.world.world_map.generate_doorway_list()
else:
doorway_list = [] # don't truncate path at doorways in simulator
need_grid_display = robot.world.path_viewer is not None
return (start_node, goal_shape, robot_parts, bbox,
fat_obstacles, skinny_obstacles, doorway_list, need_grid_display)
@staticmethod
def do_planning(rrt_instance, start_node, goal_shape,
fat_obstacles, skinny_obstacles, doorway_list, need_grid_display):
"""Does the heavy lifting; may be called in a child process."""
escape_options = (
# angle distance(mm)
(0, 40),
(+30/180*pi, 50),
(-30/180*pi, 50),
(pi, 40),
(pi, 80), # if we're wedged between two cubes
(+60/180*pi, 80),
(-60/180*pi, 80),
(+pi/2, 70),
(-pi/2, 70)
)
rrt_instance.obstacles = skinny_obstacles
start_escape_move = None
wf = WaveFront(bbox=rrt_instance.bbox)
for obstacle in fat_obstacles:
wf.add_obstacle(obstacle)
collider = rrt_instance.collides(start_node)
if not collider:
collider = wf.check_start_collides(start_node.x, start_node.y)
if collider:
if collider.obstacle_id is goal_shape.obstacle_id: # We're already at the goal
step = NavStep(NavStep.DRIVE, [RRTNode(x=start_node.x, y=start_node.y)])
navplan = NavPlan([step])
grid_display = None if not need_grid_display else wf.grid
result = (navplan, grid_display)
return DataEvent(result)
else:
# Find an escape move from this collision condition
q = start_node.q
for (phi, escape_distance) in escape_options:
if phi != pi:
new_q = wrap_angle(q + phi)
escape_type = NavStep.DRIVE
else:
new_q = q # drive backwards on current heading
escape_type = NavStep.BACKUP
new_start = RRTNode(x=start_node.x + escape_distance*cos(q+phi),
y=start_node.y + escape_distance*sin(q+phi),
q=new_q)
collider2 = rrt_instance.collides(new_start)
#print('trying escape', new_start, 'collision:', collider2)
if not collider2 and \
not wf.check_start_collides(new_start.x,new_start.y):
start_escape_move = (escape_type, phi, start_node, new_start)
start_node = new_start
print('Path planner found escape move from', collider, 'using:', start_escape_move)
break
if start_escape_move is None:
print('PathPlanner: Start collides!', collider)
return PilotEvent(StartCollides,collider=collider,grid_display=None,text="start collides")
# Run the wavefront path planner
rrt_instance.obstacles = fat_obstacles
if goal_shape.obstacle_id.startswith('Room'):
offsets = [1, -25, -1]
else:
offsets = [None]
for i in range(len(offsets)):
offset = offsets[i]
if i > 0:
wf = WaveFront(bbox=rrt_instance.bbox) # need a fresh grid
# obstacles come after the goal so they can overwrite goal pixels
for obstacle in fat_obstacles:
wf.add_obstacle(obstacle)
wf.set_goal_shape(goal_shape, offset, obstacle_inflation=PathPlanner.fat_obstacle_inflation)
wf_start = (start_node.x, start_node.y)
goal_found = wf.propagate(*wf_start)
if goal_found: break
print('Wavefront planning failed with offset', offset)
grid_display = None if not need_grid_display else wf.grid
if goal_found is None:
print('PathPlanner wavefront: goal unreachable!')
return PilotEvent(GoalUnreachable, grid_display=grid_display, text='unreachable')
# Extract and smooth the path
coords_pairs = wf.extract(goal_found, wf_start)
rrt_instance.path = rrt_instance.coords_to_path(coords_pairs)
rrt_instance.obstacles = skinny_obstacles
#rrt_instance.obstacles = fat_obstacles
rrt_instance.smooth_path()
# If the path ends in a collision according to the RRT, back off
while len(rrt_instance.path) > 2:
last_node = rrt_instance.path[-1]
if rrt_instance.collides(last_node):
rrt_instance.path = rrt_instance.path[:-1]
else:
break
# Construct the navigation plan
navplan = PathPlanner.from_path(rrt_instance.path, doorway_list)
# Insert the StartCollides escape move if there is one
if start_escape_move:
escape_type, phi, start, new_start = start_escape_move
if escape_type == NavStep.BACKUP:
escape_step = NavStep(NavStep.BACKUP, (RRTNode(x=new_start.x, y=new_start.y),))
navplan.steps.insert(0, escape_step)
elif navplan.steps[0].type == NavStep.DRIVE:
navplan.steps[0].param.insert(0, RRTNode(x=start.x, y=start.y))
else:
# Shouldn't get here, but just in case
print("Shouldn't end up here!", navplan.steps[0])
escape_step = NavStep(NavStep.DRIVE,
(RRTNode(x=start.x, y=start.y),
RRTNode(x=new_start.x, y=new_start.y)))
navplan.steps.insert(0, escape_step)
# Return the navigation plan
print('navplan=',navplan, ' steps=',navplan.steps)
result = (navplan, grid_display)
return DataEvent(result)
@staticmethod
def intersects_doorway(node1, node2, doorways):
for door in doorways:
p1 = (node1.x, node1.y)
p2 = (node2.x, node2.y)
p3 = door[1][0]
p4 = door[1][1]
result = segment_intersect_test(p1, p2, p3, p4)
#label = '**INTERSECTS**' if result else 'no_int:'
#print(label,door[0].id,' ( %.1f, %.1f )<=>( %.1f, %.1f ) vs ( %.1f, %.1f )<=>( %.1f, %.1f )' % (p1+p2+p3+p4))
if result:
return door[0]
return None
@staticmethod
def from_path(path, doorways):
# Consider each path segment (defined by start and end
# RRTNodes) and see if it crosses a doorway.
door = None
i = 0 # in case len(path) is 1 and we skip the for loop
pt1 = path[i]
for i in range(1, len(path)):
pt2 = path[i]
door = PathPlanner.intersects_doorway(pt1,pt2,doorways)
if door:
i -= 1
break
else:
pt1 = pt2
# If no doorway, we're good to go
if door is None:
step = NavStep(NavStep.DRIVE, path)
plan = NavPlan([step])
return plan
# Truncate the path at the doorway, and ajust to make sure
# we're outside the approach gate.
start_point = (pt1.x, pt1.y)
DELTA = 15 # mm
gate = DoorPass.calculate_gate(start_point, door, DoorPass.OUTER_GATE_DISTANCE + DELTA)
(dx,dy) = (door.x, door.y)
(gx,gy) = (gate[0],gate[1])
gate_node = RRTNode(x=gx, y=gy)
print('door=', door, 'gate_node=', gate_node)
while i > 0:
(px,py) = (path[i].x, path[i].y)
if ((px-dx)**2 + (py-dy)**2) > (DoorPass.OUTER_GATE_DISTANCE + DELTA)**2:
break
i -= 1
# For now, just truncate the path and insert an approach gate node.
new_path = path[0:i+1]
new_path.append(gate_node)
step1 = NavStep(NavStep.DRIVE, new_path)
step2 = NavStep(NavStep.DOORPASS, door)
plan = NavPlan([step1, step2])
return plan
#----------------------------------------------------------------
# This code is for running the path planner in a child process.
class PathPlannerProcess(LaunchProcess):
def start(self, event=None):
if not isinstance(event,DataEvent):
raise ValueError('PathPlanner node must be invoked with a DataEvent for the goal.')
goal_object = event.data
if not isinstance(goal_object, WorldObject):
raise ValueError('Path planner goal %s is not a WorldObject' % goal_object)
self.goal_object = goal_object
self.print_trace_message('started:', 'goal=%s' % goal_object)
super().start(event) # will call create_process
def create_process(self, reply_token):
use_doorways = True # assume we're running on the robot
(start_node, goal_shape, robot_parts, bbox,
fat_obstacles, skinny_obstacles, doorway_list, need_grid_display) = \
PathPlanner.setup_problem(self.goal_object, self.robot, use_doorways)
p = Process(target=self.__class__.process_workhorse,
args = [reply_token,
start_node, goal_shape, robot_parts, bbox,
fat_obstacles, skinny_obstacles, doorway_list,
need_grid_display])
return p
@staticmethod
def process_workhorse(reply_token, start_node, goal_shape, robot_parts, bbox,
fat_obstacles, skinny_obstacles, doorway_list, need_grid_display):
rrt_instance = RRT(robot_parts=robot_parts, bbox=bbox)
result = \
PathPlanner.do_planning(rrt_instance, start_node, goal_shape,
fat_obstacles, skinny_obstacles, doorway_list,
need_grid_display)
__class__.post_event(reply_token, result)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,028
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/base.py
|
"""
Base classes StateNode for nodes.py and Transition for
transitions.py are placed here due to circular dependencies.
Their parent class EventListener is imported from evbase.py.
"""
import cozmo
from .trace import TRACE
from .evbase import Event, EventListener
from .events import CompletionEvent, SuccessEvent, FailureEvent, DataEvent
class StateNode(EventListener):
"""Base class for state nodes; does nothing."""
def __init__(self):
super().__init__()
self.parent = None
self.children = {}
self.transitions = []
self.start_node = None
self.setup()
self.setup2()
# Cache 'robot' in the instance because we could have two state
# machine instances controlling different robots.
@property
def robot(self):
return self._robot
def setup(self):
"""Redefine this to set up a child state machine."""
pass
def setup2(self):
"""Redefine this if post-setup processing is required."""
pass
def start(self,event=None):
if self.running: return
if TRACE.trace_level >= TRACE.statenode_start:
print('TRACE%d:' % TRACE.statenode_start, self, 'starting')
super().start()
# Start transitions before children, because children
# may post an event that we're listening for (such as completion).
for t in self.transitions:
t.start()
if self.start_node:
if TRACE.trace_level >= TRACE.statenode_start:
print('TRACE%d:' % TRACE.statenode_start, self, 'starting child', self.start_node)
self.start_node.start()
def stop(self):
# If this node was stopped by an outgoing transition firing,
# and then its parent tries to stop it, we need to cancel the
# pending fire2 call.
if self.running:
if TRACE.trace_level >= TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop, self, 'stopping')
super().stop()
self.stop_children()
# Stop transitions even if we're not running, because a firing
# transition could have stopped us and left a fire2 pending.
for t in self.transitions:
t.stop()
def stop_children(self):
if self.children == {}:
return
if TRACE.trace_level >= TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop, self, 'is stopping its children')
for child in self.children.values():
if child.running:
child.stop()
def add_transition(self, trans):
if not isinstance(trans, Transition):
raise TypeError('%s is not a Transition' % trans)
self.transitions.append(trans)
def set_parent(self, parent):
if not isinstance(parent, StateNode):
raise TypeError('%s is not a StateNode' % parent)
try:
if isinstance(self.parent, StateNode):
raise Exception('parent already set')
except AttributeError:
raise Exception("It appears %s's __init__ method did not call super().__init__"
% self.__class__.__name__)
self.parent = parent
parent.children[self.name] = self
# First-declared child is the default start node.
if not parent.start_node:
parent.start_node = self
return self
def post_event(self, event, suppress_trace=False):
if not isinstance(event,Event):
raise ValuError('post_event given a non-Event argument:',event)
if event.source is None:
event.source = self
if (not suppress_trace) and (TRACE.trace_level >= TRACE.event_posted):
print('TRACE%d:' % TRACE.event_posted, self, 'posting event',event)
if not self.running:
print("*** ERROR: Node", self, "posted event", event,"before calling super().start(). ***")
self.robot.erouter.post(event)
def post_completion(self):
if TRACE.trace_level > TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop, self, 'posting completion')
event = CompletionEvent()
event.source = self
self.post_event(event, suppress_trace=True)
def post_success(self,details=None):
if TRACE.trace_level > TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop,
self, 'posting success, details=%s' % details)
event = SuccessEvent(details)
event.source = self
self.post_event(event, suppress_trace=True)
def post_failure(self,details=None):
if TRACE.trace_level > TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop,
self, 'posting failure, details=%s' % details)
event = FailureEvent(details)
event.source = self
self.post_event(event, suppress_trace=True)
def post_data(self,value):
if TRACE.trace_level > TRACE.statenode_startstop:
print('TRACE%d:' % TRACE.statenode_startstop,
self, 'posting data', value)
event = DataEvent(value)
event.source = self
self.post_event(event, suppress_trace=True)
def now(self):
"""Use now() to execute this node from the command line instead of as part of a state machine."""
if not self.robot:
raise ValueError('Node %s has no robot designated.' % self)
# 'program' is inserted into this module by __init__ to avoid circular importing
program.running_fsm.children = dict()
program.running_fsm.children[self.name] = self
self.robot.loop.call_soon(self.start)
return self
def print_trace_message(self, msg1='', msg2=''):
print('<><><> %s' % msg1, self, end='')
p = self.parent
while p is not None:
print(' of', p.name, end='')
p = p.parent
print(' ', msg2)
class Transition(EventListener):
"""Base class for transitions: does nothing."""
def __init__(self):
super().__init__()
self.sources = []
self.destinations = []
self.handle = None
def __repr__(self):
srcs = ','.join(node.name for node in self.sources)
dests = ','.join(node.name for node in self.destinations)
return '<%s %s: %s=>%s >' % \
(self.__class__.__name__, self.name, srcs, dests)
@property
def robot(self):
return self._robot
def _sibling_check(self,node):
for sibling in self.sources + self.destinations:
if sibling.parent is not node.parent:
raise ValueError("All source/destination nodes must have the same parent.")
def add_sources(self, *nodes):
for node in nodes:
if not isinstance(node, StateNode):
raise TypeError('%s is not a StateNode' % node)
self._sibling_check(node)
node.add_transition(self)
self.sources.append(node)
return self
def add_destinations(self, *nodes):
for node in nodes:
if not isinstance(node, StateNode):
raise TypeError('%s is not a StateNode' % node)
self._sibling_check(node)
self.destinations.append(node)
return self
def start(self):
if self.running: return
self.handle = None
if TRACE.trace_level >= TRACE.transition_startstop:
print('TRACE%d:' % TRACE.transition_startstop, self, 'starting')
super().start()
def stop(self):
if self.running:
# don't stop if we still have a live source
for src in self.sources:
if src.running:
if TRACE.trace_level >= TRACE.transition_startstop:
print('TRACE%d:' % TRACE.transition_startstop,self,'saved from stopping by',src)
return
if TRACE.trace_level >= TRACE.transition_startstop:
print('TRACE%d:' % TRACE.transition_startstop, self, 'stopping')
super().stop()
# stop pending fire2 if fire already stopped this transition
if self.handle:
self.handle.cancel()
if TRACE.trace_level >= TRACE.task_cancel:
print('TRACE%d:' % TRACE.task_cancel, self.handle, 'cancelled')
self.handle = None
def fire(self,event=None):
"""Shut down source nodes and schedule start of destination nodes.
Lets the stack unwind by returning before destinations are started.
Delay also gives time for Cozmo action cancellation to take effect."""
if not self.running: return
if TRACE.trace_level >= TRACE.transition_fire:
if event == None:
evt_desc = ''
else:
evt_desc = ' on %s' % event
print('TRACE%d:' % TRACE.transition_fire, self, 'firing'+evt_desc)
for src in self.sources:
src.stop()
self.stop()
action_cancel_delay = 0.01 # wait for source node action cancellations to take effect
self.handle = self.robot.loop.call_later(action_cancel_delay, self.fire2, event)
def fire2(self,event):
if self.handle is None:
print('@ @ @ @ @ HANDLE GONE:', self, 'SHOULD BE DEAD', self, event)
return
else:
self.handle = None
parent = self.sources[0].parent
if not parent.running:
# print('@ @ @ @ @ PARENT OF', self, 'IS', parent, 'IS DEAD! event=', event, '%x' % event.__hash__())
return
for dest in self.destinations:
if TRACE.trace_level >= TRACE.transition_fire:
print('TRACE%d: ' % TRACE.transition_fire, self, 'starting', dest)
dest.start(event)
default_value_delay = 0.1 # delay before wildcard match will fire
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,029
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/cozmo_kin.py
|
from math import pi, tan
import cozmo
from .kine import *
from cozmo_fsm import geometry
from .geometry import tprint, point, translation_part, rotation_part
from .rrt_shapes import *
# ================ Constants ================
wheelbase = 45 # millimeters
front_wheel_diameter = 52 # millimeters
hook_spacing = 35 # millimeters
center_of_rotation_offset = -19.7 # millimeters
# ================================================================
class CozmoKinematics(Kinematics):
def __init__(self,robot):
base_frame = Joint('base',
description='Base frame: the root of the kinematic tree')
# cor is center of rotation
cor_frame = Joint('cor', parent=base_frame,
description='Center of rotation',
r=-19.,
collision_model=Rectangle(geometry.point(),
dimensions=(95,60)))
# Use link instead of joint for world_frame
world_frame = Joint('world', parent=base_frame, type='world', getter=self.get_world,
description='World origin in base frame coordinates',
qmin=None, qmax=None)
front_axle_frame = Joint('front_axle', parent=base_frame,
description='Center of the front axle',
d=front_wheel_diameter/2, alpha=pi/2)
back_axle_frame = Joint('back_axle', parent=base_frame, r=-46., alpha=pi/2)
# This frame is on the midline. Could add separate left and right shoulders.
# Positive angle is up, so z must point to the right.
# x is forward, y points up.
shoulder_frame = Joint('shoulder', parent=base_frame,
type='revolute', getter=self.get_shoulder,
description='Rotation axis of the lift; z points to the right',
qmin=cozmo.robot.MIN_LIFT_ANGLE.radians,
qmax=cozmo.robot.MAX_LIFT_ANGLE.radians,
d=21., r=-39., alpha=pi/2)
lift_attach_frame = \
Joint('lift_attach', parent=shoulder_frame, type='revolute',
description='Tip of the lift, where cubes attach; distal end of four-bar linkage',
getter=self.get_lift_attach, r=66.,
qmax = - cozmo.robot.MIN_LIFT_ANGLE.radians,
qmin = - cozmo.robot.MAX_LIFT_ANGLE.radians,
#collision_model=Circle(geometry.point(), radius=10))
)
# Positive head angle is up, so z must point to the right.
# With x pointing forward, y must point up.
head_frame = Joint('head', parent=base_frame, type='revolute',
getter=self.get_head,
description='Axis of head rotation; z points to the right',
qmin=cozmo.robot.MIN_HEAD_ANGLE.radians,
qmax=cozmo.robot.MAX_HEAD_ANGLE.radians,
d=35., r=-10., alpha=pi/2)
# Dummy joint located below head joint at level of the camera frame,
# and x axis points down, z points forward, y points left
camera_dummy = Joint('camera_dummy', parent=head_frame,
description='Dummy joint below the head, at the level of the camera frame',
theta=-pi/2, r=7.5, alpha=-pi/2)
# x axis points right, y points down, z points forward
camera_frame = Joint('camera', parent=camera_dummy,
description='Camera reference frame; y is down and z is outward',
d=15., theta=-pi/2)
joints = [base_frame, world_frame, cor_frame,
front_axle_frame, back_axle_frame,
shoulder_frame, lift_attach_frame,
head_frame, camera_dummy, camera_frame]
super().__init__(joints,robot)
def get_head(self):
return self.robot.head_angle.radians
def get_shoulder(self):
# Formula supplied by Mark Wesley at Anki
# Check SDK documentation for new lift-related calls that might replace this
return math.asin( (self.robot.lift_height.distance_mm-45.0) / 66.0)
def get_lift_attach(self):
return -self.get_shoulder()
def get_world(self):
return self.robot.world.particle_filter.pose_estimate()
def project_to_ground(self,cx,cy):
"Converts camera coordinates to a ground point in the base frame."
# Formula taken from Tekkotsu's projectToGround method
camera_res = (320, 240)
half_camera_max = max(*camera_res) / 2
config = self.robot.camera.config
# Convert to generalized coordinates in range [-1, 1]
gx = (cx-config.center.x) / half_camera_max
gy = (cy-config.center.y) / half_camera_max
#tekkotsu_focal_length_x = camera_res[0]/camera_max / tan(config.fov_x.radians/2)
#tekkotsu_focal_length_y = camera_res[1]/camera_max / tan(config.fov_y.radians/2)
# Generate a ray in the camera frame
rx = gx / (config.focal_length.x / half_camera_max)
ry = gy / (config.focal_length.y / half_camera_max)
ray = point(rx,ry,1)
cam_to_base = self.robot.kine.joint_to_base('camera')
offset = translation_part(cam_to_base)
rot_ray = rotation_part(cam_to_base).dot(ray)
dist = - offset[2,0]
align = rot_ray[2,0]
if abs(align) > 1e-5:
s = dist / align
hit = point(rot_ray[0,0]*s, rot_ray[1,0]*s, rot_ray[2,0]*s) + offset
elif align * dist < 0:
hit = point(-rot_ray[0,0], -rot_ray[1,0], -rot_ray[2,0], abs(align))
else:
hit = point(rot_ray[0,0], rot_ray[1,0], rot_ray[2,0], abs(align))
return hit
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,030
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/Iteration.py
|
"""
Iteration.fsm demonstrates nested iteration using the Iterate node
and the =CNext=> transition, which waits for completion before advancing
the iterator. Use =Next=> if the source nodes don't need to
complete.
"""
from cozmo_fsm import *
class PrintIt(StateNode):
def start(self,event=None):
if self.running: return
super().start(event)
if isinstance(event,DataEvent):
print('I got some data: ', event.data)
class Iteration(StateMachineProgram):
def setup(self):
"""
outer_loop: Iterate(['alpha', 'bravo', 'charlie'])
outer_loop =SayData=> Say() =C=> inner_loop
inner_loop: Iterate(4) =D=> PrintIt() =Next=> inner_loop
# When inner iteration is done, it posts a completion event.
inner_loop =CNext=> outer_loop
outer_loop =C=> Say('Done')
"""
# Code generated by genfsm on Mon Feb 17 03:13:49 2020:
outer_loop = Iterate(['alpha', 'bravo', 'charlie']) .set_name("outer_loop") .set_parent(self)
say1 = Say() .set_name("say1") .set_parent(self)
inner_loop = Iterate(4) .set_name("inner_loop") .set_parent(self)
printit1 = PrintIt() .set_name("printit1") .set_parent(self)
say2 = Say('Done') .set_name("say2") .set_parent(self)
saydatatrans1 = SayDataTrans() .set_name("saydatatrans1")
saydatatrans1 .add_sources(outer_loop) .add_destinations(say1)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(say1) .add_destinations(inner_loop)
datatrans1 = DataTrans() .set_name("datatrans1")
datatrans1 .add_sources(inner_loop) .add_destinations(printit1)
nexttrans1 = NextTrans() .set_name("nexttrans1")
nexttrans1 .add_sources(printit1) .add_destinations(inner_loop)
cnexttrans1 = CNextTrans() .set_name("cnexttrans1")
cnexttrans1 .add_sources(inner_loop) .add_destinations(outer_loop)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(outer_loop) .add_destinations(say2)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,031
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/Randomness.py
|
"""
Randomness.fsm demonstrates three ways to introduce randomness in
state machine behavior.
1) Use the =RND=> transition to select a destination node at random.
2) Pass a list of utterances to Say(), and it will choose one at
random.
3) Specialize a node class such as Forward or Turn and use Python's
random() function to generate a random value for the node's
parameter.
"""
import random
from cozmo_fsm import *
class RandomForward(Forward):
"""Move forward a random distance."""
def __init__(self,mindist=10,maxdist=50,**kwargs):
super().__init__(**kwargs)
self.mindist = mindist if isinstance(mindist,Distance) else distance_mm(mindist)
self.maxdist = maxdist if isinstance(maxdist,Distance) else distance_mm(maxdist)
def start(self,event=None):
self.distance = distance_mm(self.mindist.distance_mm +
random.random() * (self.maxdist.distance_mm - self.mindist.distance_mm))
super().start(event)
class RandomTurn(Turn):
"""Turn by a random amount."""
def __init__(self,minangle=20,maxangle=170,**kwargs):
super().__init__(**kwargs)
self.minangle = minangle if isinstance(minangle,Angle) else degrees(minangle)
self.maxangle = maxangle if isinstance(maxangle,Angle) else degrees(maxangle)
def start(self,event=None):
angle = self.minangle.degrees + random.random()*(self.maxangle.degrees - self.minangle.degrees)
self.angle = degrees(angle) if random.random()>=0.5 else degrees(-angle)
super().start(event)
class Randomness(StateMachineProgram):
def setup(self):
"""
startnode: StateNode() =RND=> {fwd, fwd, turn, turn, joke}
fwd: Say(["Forward", "Straight", "Full steam ahead"])
=T(2)=> RandomForward() =T(2)=> startnode
turn: Say(["Turn", "Rotate", "Yaw"])
=T(2)=> RandomTurn() =C=> startnode
joke: Say(["Watch this", "Hold my beer", "I'm not lost",
"Be cool", "Wanna race?"])
=C=> StateNode() =T(2)=> startnode
"""
# Code generated by genfsm on Mon Feb 17 03:16:24 2020:
startnode = StateNode() .set_name("startnode") .set_parent(self)
fwd = Say(["Forward", "Straight", "Full steam ahead"]) .set_name("fwd") .set_parent(self)
randomforward1 = RandomForward() .set_name("randomforward1") .set_parent(self)
turn = Say(["Turn", "Rotate", "Yaw"]) .set_name("turn") .set_parent(self)
randomturn1 = RandomTurn() .set_name("randomturn1") .set_parent(self)
joke = Say(["Watch this", "Hold my beer", "I'm not lost",
"Be cool", "Wanna race?"]) .set_name("joke") .set_parent(self)
statenode1 = StateNode() .set_name("statenode1") .set_parent(self)
randomtrans1 = RandomTrans() .set_name("randomtrans1")
randomtrans1 .add_sources(startnode) .add_destinations(fwd,fwd,turn,turn,joke)
timertrans1 = TimerTrans(2) .set_name("timertrans1")
timertrans1 .add_sources(fwd) .add_destinations(randomforward1)
timertrans2 = TimerTrans(2) .set_name("timertrans2")
timertrans2 .add_sources(randomforward1) .add_destinations(startnode)
timertrans3 = TimerTrans(2) .set_name("timertrans3")
timertrans3 .add_sources(turn) .add_destinations(randomturn1)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(randomturn1) .add_destinations(startnode)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(joke) .add_destinations(statenode1)
timertrans4 = TimerTrans(2) .set_name("timertrans4")
timertrans4 .add_sources(statenode1) .add_destinations(startnode)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,032
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/rrt_shapes.py
|
from cozmo_fsm import geometry
from math import sqrt, pi, atan2
import numpy as np
class Shape():
def __init__(self, center=geometry.point()):
if center is None: raise ValueError()
self.center = center
self.rotmat = geometry.identity()
self.obstacle_id = None # only store the string, so shape is pickle-able
def __repr__(self):
return "<%s >" % (self.__class__.__name__)
def collides(self, shape):
if isinstance(shape, Rectangle):
return self.collides_rect(shape)
elif isinstance(shape, Polygon):
return self.collides_poly(shape)
elif isinstance(shape, Circle):
return self.collides_circle(shape)
elif isinstance(shape, Compound):
return shape.collides(self)
else:
raise Exception("%s has no collides() method defined for %s." % (self, shape))
def get_bounding_box(self):
"""Should return ((xmin,ymin), (xmax,ymax))"""
raise NotImplementedError("get_bounding_box")
#================ Basic Shapes ================
class Circle(Shape):
def __init__(self, center=geometry.point(), radius=25/2):
super().__init__(center)
self.radius = radius
self.orient = 0.
def __repr__(self):
id = self.obstacle_id if self.obstacle_id else '[no obstacle]'
return '<Circle (%.1f,%.1f) r=%.1f %s>' % \
(self.center[0,0], self.center[1,0], self.radius, id)
def instantiate(self, tmat):
return Circle(center=tmat.dot(self.center), radius=self.radius)
def collides_rect(self,rect):
return rect.collides_circle(self)
def collides_poly(self,poly):
return poly.collides(self)
def collides_circle(self,circle):
dx = self.center[0,0] - circle.center[0,0]
dy = self.center[1,0] - circle.center[1,0]
dist = sqrt(dx*dx + dy*dy)
return dist < (self.radius + circle.radius)
def get_bounding_box(self):
xmin = self.center[0,0] - self.radius
xmax = self.center[0,0] + self.radius
ymin = self.center[1,0] - self.radius
ymax = self.center[1,0] + self.radius
return ((xmin,ymin), (xmax,ymax))
class Polygon(Shape):
def __init__(self, vertices=None, orient=0):
center = vertices.mean(1)
center.resize(4,1)
super().__init__(center)
self.vertices = vertices
self.orient = orient # should move vertex rotation code from Rectangle to here
N = vertices.shape[1]
self.edges = tuple( (vertices[:,i:i+1], vertices[:,(i+1)%N:((i+1)%N)+1])
for i in range(N) )
def get_bounding_box(self):
mins = self.vertices.min(1)
maxs = self.vertices.max(1)
xmin = mins[0]
ymin = mins[1]
xmax = maxs[0]
ymax = maxs[1]
return ((xmin,ymin), (xmax,ymax))
def collides_poly(self,poly):
raise NotImplementedError()
def collides_circle(self,circle):
raise NotImplementedError()
class Rectangle(Polygon):
def __init__(self, center=None, dimensions=None, orient=0):
self.dimensions = dimensions
self.orient = orient
if not isinstance(dimensions[0],(float,int)):
raise ValueError(dimensions)
dx2 = dimensions[0]/2
dy2 = dimensions[1]/2
relative_vertices = np.array([[-dx2, dx2, dx2, -dx2 ],
[-dy2, -dy2, dy2, dy2 ],
[ 0, 0, 0, 0 ],
[ 1, 1, 1, 1 ]])
self.unrot = geometry.aboutZ(-orient)
center_ex = self.unrot.dot(center)
extents = geometry.translate(center_ex[0,0],center_ex[1,0]).dot(relative_vertices)
# Extents measured along the rectangle's axes, not world axes
self.min_Ex = min(extents[0,:])
self.max_Ex = max(extents[0,:])
self.min_Ey = min(extents[1,:])
self.max_Ey = max(extents[1,:])
vertices = geometry.translate(center[0,0],center[1,0]).dot(
geometry.aboutZ(orient).dot(relative_vertices))
super().__init__(vertices=vertices, orient=orient)
def __repr__(self):
id = self.obstacle_id if self.obstacle_id else '[no obstacle]'
return '<Rectangle (%.1f,%.1f) %.1fx%.1f %.1f deg %s>' % \
(self.center[0,0],self.center[1,0],*self.dimensions,
self.orient*(180/pi), id)
def instantiate(self, tmat):
dimensions = (self.max_Ex-self.min_Ex, self.max_Ey-self.min_Ey)
rot = atan2(tmat[1,0], tmat[0,0])
return Rectangle(center = tmat.dot(self.center),
orient = rot + self.orient,
dimensions = dimensions)
def collides_rect(self,other):
# Test others edges in our reference frame
o_verts = self.unrot.dot(other.vertices)
o_min_x = min(o_verts[0,:])
o_max_x = max(o_verts[0,:])
o_min_y = min(o_verts[1,:])
o_max_y = max(o_verts[1,:])
if o_max_x <= self.min_Ex or self.max_Ex <= o_min_x or \
o_max_y <= self.min_Ey or self.max_Ey <= o_min_y:
return False
if self.orient == other.orient: return True
# Test our edges in other's reference frame
s_verts = other.unrot.dot(self.vertices)
s_min_x = min(s_verts[0,:])
s_max_x = max(s_verts[0,:])
s_min_y = min(s_verts[1,:])
s_max_y = max(s_verts[1,:])
if s_max_x <= other.min_Ex or other.max_Ex <= s_min_x or \
s_max_y <= other.min_Ey or other.max_Ey <= s_min_y:
return False
return True
def collides_circle(self,circle):
p = self.unrot.dot(circle.center)[0:2,0]
pmin = p - circle.radius
pmax = p + circle.radius
if pmax[0] <= self.min_Ex or self.max_Ex <= pmin[0] or \
pmax[1] <= self.min_Ey or self.max_Ey <= pmin[1]:
return False
# Need corner tests here
return True
#================ Compound Shapes ================
class Compound(Shape):
def __init__(self, shapes=[]):
self.shapes = shapes
def collides(self,shape):
for s in self.shapes:
if s.collides(shape):
return True
return False
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,033
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/transitions.py
|
import random
import re
from .base import *
from .events import *
from .nodes import Say, Iterate
class NullTrans(Transition):
"""Transition fires immediately; does not require an event to trigger it."""
def start(self):
if self.running: return
super().start()
# Don't fire immediately on start because the source node(s) may
# have other startup calls to make. Give them time to finish.
self.handle = self.robot.loop.call_soon(self.fire)
def stop(self):
if self.handle:
print(self, 'cancelling', self.handle)
self.handle.cancel()
self.handle = None
super().stop()
def fire(self, event=None):
self.handle = None
super().fire(event)
class CSFEventBase(Transition):
"""Base class for Completion, Success, and Failure Events"""
def __init__(self,event_type,count=None):
super().__init__()
self.event_type = event_type
self.count = count
def start(self):
if self.running: return
super().start()
self.observed_sources = set()
for source in self.sources:
self.robot.erouter.add_listener(self, self.event_type, source)
def handle_event(self,event):
if not self.running:
print('***',self,'got an event ', event, ' while not running!')
return
if TRACE.trace_level >= TRACE.listener_invocation:
print('TRACE%d: %s is handling %s' %
(TRACE.listener_invocation, self,event))
super().handle_event(event)
if isinstance(event, self.event_type):
self.observed_sources.add(event.source)
if len(self.observed_sources) >= (self.count or len(self.sources)):
self.fire(event)
else:
raise ValueError("%s can't handle %s" % (self.event_type, event))
class CompletionTrans(CSFEventBase):
"""Transition fires when source nodes complete."""
def __init__(self,count=None):
super().__init__(CompletionEvent,count)
class SuccessTrans(CSFEventBase):
"""Transition fires when source nodes succeed."""
def __init__(self,count=None):
super().__init__(SuccessEvent,count)
class FailureTrans(CSFEventBase):
"""Transition fires when source nodes fail."""
def __init__(self,count=None):
super().__init__(FailureEvent,count)
class CNextTrans(CSFEventBase):
"""Transition fires when source nodes complete."""
def __init__(self,count=None):
super().__init__(CompletionEvent,count)
def fire(self, event=None):
super().fire(Iterate.NextEvent())
class NextTrans(Transition):
"""Transition sends a NextEvent to its target nodes to advance an iterator."""
def start(self, event=None):
super().start()
self.fire(Iterate.NextEvent())
class SayDataTrans(Transition):
"""Converts a DataEvent to Say.SayDataEvent so we can speak the data."""
def start(self):
if self.running: return
super().start()
for source in self.sources:
self.robot.erouter.add_listener(self, DataEvent, source)
self.robot.erouter.add_listener(self, Say.SayDataEvent, source)
def handle_event(self,event):
if not self.running: return
super().handle_event(event)
if isinstance(event, Say.SayDataEvent):
say_data_event = event
elif isinstance(event, DataEvent):
say_data_event = Say.SayDataEvent(event.data)
else:
return
self.fire(say_data_event)
class TimerTrans(Transition):
"""Transition fires when the timer has expired."""
def __init__(self,duration=None):
if not isinstance(duration, (int, float)) or duration < 0:
raise ValueError("TimerTrans requires a positive number for duration, not %s" % duration)
super().__init__()
self.set_polling_interval(duration)
def poll(self):
if not self.running: return
self.fire()
class TapTrans(Transition):
"""Transition fires when a cube is tapped."""
def __init__(self,cube=None):
super().__init__()
self.cube = cube
def start(self):
if self.running: return
super().start()
if self.cube:
self.robot.erouter.add_listener(self,TapEvent,self.cube)
else:
self.robot.erouter.add_wildcard_listener(self,TapEvent,None)
def handle_event(self,event):
if not self.running: return
if self.cube:
self.fire(event)
else:
self.handle = \
self.robot.loop.call_later(Transition.default_value_delay, self.fire, event)
class ObservedMotionTrans(Transition):
"""Transition fires when motion is observed in the camera image."""
def start(self):
if self.running: return
super().start()
self.robot.erouter.add_listener(self,ObservedMotionEvent,None)
def handle_event(self,event):
if not self.running: return
super().handle_event(event)
self.fire(event)
class UnexpectedMovementTrans(Transition):
"""Transition fires when unexpected movement is detected."""
def start(self):
if self.running: return
super().start()
self.robot.erouter.add_listener(self,UnexpectedMovementEvent,None)
def handle_event(self,event):
if not self.running: return
super().handle_event(event)
self.fire(event)
class DataTrans(Transition):
"""Transition fires when data matches."""
def __init__(self, data=None):
super().__init__()
self.data = data
def start(self):
if self.running: return
super().start()
for source in self.sources:
if self.data is None or isinstance(self.data, type):
self.robot.erouter.add_wildcard_listener(self, DataEvent, source)
else:
self.robot.erouter.add_listener(self, DataEvent, source)
def handle_event(self,event):
if not self.running: return
super().handle_event(event)
if isinstance(event,DataEvent):
if self.data is None or \
(isinstance(self.data, type) and isinstance(event.data, self.data)):
self.fire(event)
else:
try:
if self.data == event.data: # error if == barfs
self.fire(event)
except TypeError: pass
else:
raise TypeError('%s is not a DataEvent' % event)
class ArucoTrans(Transition):
"""Fires if one of the specified markers is visible"""
def __init__(self,marker_ids=None):
super().__init__()
self.polling_interval = 0.1
if isinstance(marker_ids,(list,tuple)):
marker_ids = set(marker_ids)
self.marker_ids = marker_ids
def poll(self,event=None):
if not self.running: return
if self.marker_ids is None:
if self.robot.world.aruco.seen_marker_ids != []:
self.fire()
elif isinstance(self.marker_ids,set):
if self.marker_ids.intersection(self.robot.world.aruco.seen_marker_ids) != set():
self.fire()
elif self.marker_ids in self.robot.world.aruco.seen_marker_ids:
self.fire()
class PatternMatchTrans(Transition):
wildcard = re.compile('.*')
def __init__(self, pattern=None, event_type=None):
super().__init__()
if pattern:
pattern = re.compile(pattern)
self.pattern = pattern
self.event_type = event_type
def start(self):
if self.running: return
super().start()
if self.pattern is None:
self.robot.erouter.add_wildcard_listener(self, self.event_type, None)
else:
self.robot.erouter.add_listener(self, self.event_type, None)
def handle_event(self,event):
if not self.running: return
super().handle_event(event)
if self.pattern is None:
result = self.wildcard.match(event.string)
else:
result = self.pattern.match(event.string)
if result:
match_event = self.event_type(event.string,event.words,result)
self.fire(match_event)
class TextMsgTrans(PatternMatchTrans):
"""Transition fires when text message event matches pattern."""
def __init__(self,pattern=None):
super().__init__(pattern,TextMsgEvent)
class HearTrans(PatternMatchTrans):
"""Transition fires if speech event matches pattern."""
def __init__(self,pattern=None):
super().__init__(pattern,SpeechEvent)
class PilotTrans(Transition):
"""Fires if a matching PilotEvent is observed."""
def __init__(self,status=None):
super().__init__()
self.status = status
def start(self):
if self.running: return
super().start()
for source in self.sources:
if self.status == None:
self.robot.erouter.add_wildcard_listener(self, PilotEvent, source)
else:
self.robot.erouter.add_listener(self, PilotEvent, source)
def handle_event(self,event):
if not self.running: return
super().handle_event(event)
if self.status == None or self.status == event.status:
self.fire(event)
class RandomTrans(Transition):
"""Picks a destination node at random."""
def start(self):
if self.running: return
super().start()
# Don't fire immediately on start because the source node(s) may
# have other startup calls to make. Give them time to finish.
self.handle = self.robot.loop.call_soon(self.fire) # okay to use Transition.fire
def stop(self):
if self.handle:
self.handle.cancel()
self.handle = None
super().stop()
def fire2(self,event):
"""Overrides Transition.fire2 to only start one randomly-chosen destination node."""
dest = random.choice(self.destinations)
dest.start(event)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,034
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/worldmap.py
|
from math import pi, inf, sin, cos, tan, atan2, sqrt
import time
from cozmo.faces import Face
from cozmo.objects import LightCube, CustomObject
from cozmo.util import Pose
from . import evbase
from . import geometry
from . import custom_objs
from .geometry import wrap_angle, quat2rot, quaternion_to_euler_angle, get_orientation_state
import math
import numpy as np
class WorldObject():
def __init__(self, id=None, x=0, y=0, z=0, is_visible=None):
self.id = id
self.x = x
self.y = y
self.z = z
self.is_fixed = False # True for walls and markers in predefined maps
self.is_obstacle = True
if is_visible is not None:
self.is_visible = is_visible
self.sdk_obj = None
self.update_from_sdk = False
self.is_foreign = False
if is_visible:
self.pose_confidence = +1
else:
self.pose_confidence = -1
class LightCubeObj(WorldObject):
light_cube_size = (44., 44., 44.)
def __init__(self, sdk_obj, id=None, x=0, y=0, z=0, theta=0):
if id is None:
id = 'Cube-' + str(sdk_obj.cube_id)
super().__init__(id,x,y,z)
self.sdk_obj = sdk_obj
if sdk_obj and sdk_obj.pose:
self.sdk_obj.wm_obj = self
self.update_from_sdk = True
self.orientation, _, _, self.theta = get_orientation_state(self.sdk_obj.pose.rotation.q0_q1_q2_q3)
else:
self.theta = theta
self.orientation = geometry.ORIENTATION_UPRIGHT
self.size = self.light_cube_size
@property
def is_visible(self):
return self.sdk_obj and self.sdk_obj.is_visible
def get_bounding_box(self):
s = self.light_cube_size[0]
pts = np.array([[-s/2, -s/2, s/2, s/2],
[-s/2, s/2, -s/2, s/2],
[ 0, 0, 0, 0 ],
[ 1, 1, 1, 1 ]])
pts = geometry.aboutZ(self.theta).dot(pts)
pts = geometry.translate(self.x, self.y).dot(pts)
mins = pts.min(1)
maxs = pts.max(1)
xmin = mins[0]
ymin = mins[1]
xmax = maxs[0]
ymax = maxs[1]
return ((xmin,ymin), (xmax,ymax))
def __repr__(self):
if self.pose_confidence >= 0:
vis = ' visible' if self.sdk_obj and self.is_visible else ''
return '<LightCubeObj %s: (%.1f, %.1f, %.1f) @ %d deg.%s %s>' % \
(self.id, self.x, self.y, self.z, self.theta*180/pi, vis, self.orientation)
else:
return '<LightCubeObj %s: position unknown>' % self.id
class ChargerObj(WorldObject):
charger_size = (104, 98, 10)
def __init__(self, sdk_obj, id=None, x=0, y=0, z=0, theta=0):
if id is None:
id = 'Charger'
super().__init__(id,x,y,z)
self.sdk_obj = sdk_obj
if sdk_obj:
self.sdk_obj.wm_obj = self
self.update_from_sdk = True
self.orientation = geometry.ORIENTATION_UPRIGHT
self.theta = theta
self.size = self.charger_size
if self.sdk_obj and self.sdk_obj.pose:
self.orientation, _, _, self.theta = get_orientation_state(self.sdk_obj.pose.rotation.q0_q1_q2_q3)
@property
def is_visible(self):
return self.sdk_obj and self.sdk_obj.is_visible
def __repr__(self):
if self.pose_confidence >= 0:
vis = ' visible' if self.sdk_obj and self.is_visible else ''
return '<ChargerObj: (%.1f, %.1f, %.1f) @ %d deg.%s %s>' % \
(self.x, self.y, self.z, self.theta*180/pi, vis, self.orientation)
else:
return '<ChargerObj: position unknown>'
class CustomMarkerObj(WorldObject):
custom_marker_size = (4,44,44)
def __init__(self, sdk_obj, id=None, x=0, y=0, z=0, theta=0, rotation=0):
# 'theta' is orientation relative to North in particle filter reference frame
# 'rotation' is orientation relative to "up" in the camera image
if id is None:
custom_type = sdk_obj.object_type.name[-2:]
id = 'CustomMarkerObj-' + str(custom_type)
super().__init__(id,x,y,z)
self.theta = wrap_angle(theta)
self.sdk_obj = sdk_obj
self.marker_number = int(id[-2:])
self.size = self.custom_marker_size
if self.sdk_obj:
self.orientation, self.rotation, _, _ = \
get_orientation_state(self.sdk_obj.pose.rotation.q0_q1_q2_q3, True)
else:
self.rotation = wrap_angle(rotation)
if abs(self.rotation) < 0.1:
self.orientation = geometry.ORIENTATION_UPRIGHT
elif abs(self.rotation-pi/2) < 0.1:
self.orientation = geometry.ORIENTATION_LEFT
elif abs(self.rotation+pi/2) < 0.1:
self.orientation = geometry.ORIENTATION_RIGHT
elif abs(wrap_angle(self.rotation+pi)) < 0.1:
self.orientation = geometry.ORIENTATION_INVERTED
else:
self.orientation = geometry.ORIENTATION_TILTED
@property
def is_visible(self):
return self.sdk_obj and self.sdk_obj.is_visible
def get_bounding_box(self):
sx,sy,sz = self.size
pts = np.array([[ 0, 0, sx, sx],
[-sy/2, sy/2, sy/2, -sy/2],
[ 0, 0, 0, 0 ],
[ 1, 1, 1, 1 ]])
pts = geometry.aboutZ(self.theta).dot(pts)
pts = geometry.translate(self.x, self.y).dot(pts)
mins = pts.min(1)
maxs = pts.max(1)
xmin = mins[0]
ymin = mins[1]
xmax = maxs[0]
ymax = maxs[1]
return ((xmin,ymin), (xmax,ymax))
def __repr__(self):
if self.sdk_obj:
vis = ' visible' if self.is_visible else ''
return '<CustomMarkerObj-%s %d: (%.1f,%.1f) @ %d deg.%s %s>' % \
(self.sdk_obj.object_type.name[-2:], self.sdk_obj.object_id,
self.x, self.y, self.theta*180/pi, vis, self.orientation)
else:
return '<CustomMarkerObj %s (%.1f,%.1f) %s>' % \
(self.id, self.x, self.y, self.orientation)
class CustomCubeObj(WorldObject):
# *** TODO: add self.rotation and self.orientation similar to CustomMarkerObj
def __init__(self, sdk_obj, id=None, x=0, y=0, z=0, theta=0, size=None):
custom_type = sdk_obj.object_type.name[-2:]
if id is None:
id = 'CustomCubeObj-' + str(custom_type)
super().__init__(id,x,y,z)
self.sdk_obj = sdk_obj
self.update_from_sdk = True
self.theta = theta
self.custom_type = custom_type
if (size is None) and isinstance(id, CustomObject):
self.size = (id.x_size_mm, id.y_size_mm, id.z_size_mm)
elif size:
self.size = size
else:
self.size = (50., 50., 50.)
@property
def is_visible(self):
return self.sdk_obj and self.sdk_obj.is_visible
def __repr__(self):
vis = ' visible' if self.sdk_obj and self.is_visible else ''
return '<CustomCubeObj-%s %d: (%.1f,%.1f, %.1f) @ %d deg.%s>' % \
(self.sdk_obj.object_type.name[-2:], self.sdk_obj.object_id,
self.x, self.y, self.z, self.theta*180/pi, vis)
class ArucoMarkerObj(WorldObject):
def __init__(self, aruco_parent, marker_number, id=None, x=0, y=0, z=0, theta=0):
if id is None:
id = 'Aruco-' + str(marker_number)
super().__init__(id,x,y,z)
self.aruco_parent = aruco_parent
self.marker_number = marker_number
self.theta = theta
self.pose_confidence = +1
@property
def is_visible(self):
return self.marker_number in self.aruco_parent.seen_marker_ids
def __repr__(self):
if self.pose_confidence >= 0:
vis = ' visible' if self.is_visible else ''
fix = ' fixed' if self.is_fixed else ''
return '<ArucoMarkerObj %d: (%.1f, %.1f, %.1f) @ %d deg.%s%s>' % \
(self.marker_number, self.x, self.y, self.z, self.theta*180/pi, fix, vis)
else:
return '<ArucoMarkerObj %d: position unknown>' % self.marker_number
class WallObj(WorldObject):
def __init__(self, id=None, x=0, y=0, theta=0, length=100, height=150,
door_width=75, door_height=105, marker_specs=dict(),
doorways=[], door_ids=[], is_foreign=False, is_fixed=False,
wall_spec=None, spec_id=None):
if wall_spec:
spec_id = wall_spec.spec_id
length = wall_spec.length
height = wall_spec.height
door_width = wall_spec.door_width
door_height = wall_spec.door_height
marker_specs = wall_spec.marker_specs.copy()
doorways = wall_spec.doorways.copy()
door_ids = wall_spec.door_ids.copy()
if id:
self.wall_label = id[1+id.rfind('-'):]
else:
if len(marker_specs) > 0:
k = list(marker_specs.keys())
k.sort()
self.wall_label = k[0][1+k[0].rfind('-'):]
id = 'Wall-%s' % self.wall_label
elif wall_spec and wall_spec.label:
self.wall_label = wall_spec.label
id = 'Wall-%s' % wall_spec.label
else:
raise ValueError('id (e.g., "A") must be supplied if wall has no markers')
super().__init__(id, x, y)
self.z = height/2
self.theta = theta
self.spec_id = spec_id
self.length = length
self.height = height
self.door_width = door_width
self.door_height = door_height
self.marker_specs = marker_specs
self.doorways = doorways
self.door_ids = door_ids
self.is_foreign = is_foreign
self.is_fixed = is_fixed
self.pose_confidence = +1
def update(self, world_map, x=0, y=0, theta=0):
# Used instead of making new object for efficiency
self.x = x
self.y = y
self.theta = theta
def make_doorways(self, world_map):
index = 0
wall = self
for index in range(len(self.doorways)):
doorway = DoorwayObj(wall, index)
doorway.pose_confidence = +1
world_map.objects[doorway.id] = doorway
def make_arucos(self, world_map):
"Called by add_fixed_landmark to make fixed aruco markers."
for key,value in self.marker_specs.items():
# Project marker onto the wall; move marker if it already exists
marker = world_map.objects.get(key, None)
if marker is None:
marker_number = int(key[1+key.rfind('-'):])
marker = ArucoMarkerObj(world_map.robot.world.aruco, marker_number=marker_number)
world_map.objects[marker.id] = marker
wall_xyz = geometry.point(self.length/2 - value[1][0], 0, value[1][1])
s = 0 if value[0] == +1 else pi
rel_xyz = geometry.aboutZ(self.theta+s).dot(wall_xyz)
marker.x = self.x + rel_xyz[1][0]
marker.y = self.y + rel_xyz[0][0]
marker.z = rel_xyz[2][0]
marker.theta = wrap_angle(self.theta + s)
marker.is_fixed = self.is_fixed
@property
def is_visible(self):
try:
seen_marker_keys = [('Aruco-%d' % id) for id in evbase.robot_for_loading.world.aruco.seen_marker_ids]
except:
return True
for m in self.marker_specs.keys():
if m in seen_marker_keys:
return True
return False
def __repr__(self):
if self.pose_confidence >= 0:
vis = ' visible' if self.is_visible else ''
fix = ' fixed' if self.is_fixed else ''
return '<WallObj %s: (%.1f,%.1f) @ %d deg. for %.1f%s%s>' % \
(self.id, self.x, self.y, self.theta*180/pi, self.length, fix, vis)
else:
return '<WallObj %s: position unknown>' % self.id
class DoorwayObj(WorldObject):
def __init__(self, wall, index):
self.marker_ids = wall.door_ids[index]
id = 'Doorway-' + str(self.marker_ids[0])
super().__init__(id,0,0)
self.theta = wall.theta
self.wall = wall
self.door_width = wall.door_width
self.index = index # which doorway is this? 0, 1, ...
self.is_obstacle = False
self.update()
def update(self):
bignum = 1e6
self.theta = self.wall.theta
m = max(-bignum, min(bignum, tan(self.theta+pi/2)))
b = self.wall.y - m*self.wall.x
dy = (self.wall.length/2 - self.wall.doorways[self.index][0]) * cos(self.theta)
self.y = self.wall.y - dy
if abs(m) > 1/bignum:
self.x = (self.y - b) / m
else:
self.x = self.wall.x
self.pose_confidence = self.wall.pose_confidence
def __repr__(self):
if self.pose_confidence >= 0:
return '<DoorwayObj %s: (%.1f,%.1f) @ %d deg.>' % \
(self.id, self.x, self.y, self.theta*180/pi)
else:
return '<DoorwayObj %s: position unknown>' % self.id
class RoomObj(WorldObject):
def __init__(self, name,
points=np.resize(np.array([0,0,0,1]),(4,4)).transpose(),
floor=1, door_ids=[], connections=[]):
"points should be four points in homogeneous coordinates forming a convex polygon"
id = 'Room-' + name
self.name = name
x,y,z,s = points.mean(1)
super().__init__(id,x,y)
self.points = points
self.floor = floor
self.door_ids = door_ids
self.connections = connections
self.is_obstacle = False
self.is_fixed = True
def __repr__(self):
return '<RoomObj %s: (%.1f,%.1f) floor=%s>' % (self.id, self.x, self.y, self.floor)
def get_bounding_box(self):
mins = self.points.min(1)
maxs = self.points.max(1)
return ((mins[0],mins[1]), (maxs[0],maxs[1]))
class ChipObj(WorldObject):
def __init__(self, id, x, y, z=0, radius=25/2, thickness=4):
super().__init__(id,x,y,z)
self.radius = radius
self.thickness = thickness
def __repr__(self):
return '<ChipObj (%.1f,%.1f) radius %.1f>' % \
(self.x, self.y, self.radius)
class FaceObj(WorldObject):
def __init__(self, sdk_obj, id, x, y, z, name):
super().__init__(id, x, y, z)
self.sdk_obj = sdk_obj
self.is_obstacle = False
self.expression = 'unknown'
@property
def name(self):
return self.sdk_obj.name
@property
def is_visible(self):
return self.sdk_obj and self.sdk_obj.is_visible
def __repr__(self):
return "<FaceObj name:'%s' expression:%s (%.1f, %.1f, %.1f) vis:%s>" % \
(self.name, self.expression, self.x, self.y, self.z, self.is_visible)
class CameraObj(WorldObject):
camera_size = (44., 44., 44.)
def __init__(self, id=None, x=0, y=0, z=0, theta=0, phi = 0):
super().__init__(id,x,y,z)
self.size = self.camera_size
self.id = id
self.x = x
self.y = y
self.z = z
self.theta = theta
self.phi = phi
def update(self,x=0, y=0, z=0, theta = 0, phi = 0):
# Used instead of making new object for efficiency
self.x = x
self.y = y
self.z = z
self.theta = theta
self.phi = phi
def __repr__(self):
return '<CameraObj %d: (%.1f, %.1f, %.1f) @ %f.>\n' % \
(self.id, self.x, self.y, self.z, self.phi*180/pi)
class RobotForeignObj(WorldObject):
def __init__(self, cozmo_id=None, x=0, y=0, z=0, theta=0, camera_id = -1 ):
super().__init__(id,x,y,z)
self.cozmo_id = cozmo_id
self.x = x
self.y = y
self.z = z
self.theta = theta
self.size = (120., 90., 100.)
self.camera_id = camera_id
def __repr__(self):
return '<RobotForeignObj %d: (%.1f, %.1f, %.1f) @ %f.> from camera %f\n' % \
(self.cozmo_id, self.x, self.y, self.z, self.theta*180/pi, self.camera_id)
def update(self, x=0, y=0, z=0, theta=0, camera_id=-1):
# Used instead of making new object for efficiency
self.x = x
self.y = y
self.z = z
self.theta = theta
self.camera_id = camera_id
class LightCubeForeignObj(WorldObject):
light_cube_size = (44., 44., 44.)
def __init__(self, id=None, cozmo_id=None, x=0, y=0, z=0, theta=0, is_visible=False):
super().__init__(id,x,y,z)
self.theta = theta
self.cozmo_id = cozmo_id
self.size = self.light_cube_size
self.is_visible = is_visible
def __repr__(self):
return '<LightCubeForeignObj %d: (%.1f, %.1f, %.1f) @ %d deg.> by cozmo %d \n' % \
(self.id, self.x, self.y, self.z, self.theta*180/pi, self.cozmo_id)
def update(self, x=0, y=0, z=0, theta=0):
# Used instead of making new object for efficiency
self.x = x
self.y = y
self.z = z
self.theta = theta
class MapFaceObj(WorldObject):
mapFace_size = (104., 98.)
def __init__(self, id=None, x=0, y=0, is_visible=False, expression='unknown'):
super().__init__(id,x,y,0)
self.theta = 0
self.is_visible = is_visible
self.expression = expression
self.size = self.mapFace_size
def __repr__(self):
return "<MapFaceObj: expression:%s (%.1f, %.1f, %.1f) vis:%s>" % \
(self.expression, self.x, self.y, self.z, self.is_visible)
def get_bounding_box(self):
# ((xmin,ymin), (xmax,ymax))
return ((self.x-self.size[0]/2, self.y-self.size[1]/2), (self.x+self.size[0]/2, self.y+self.size[1]/2))
#================ WorldMap ================
class WorldMap():
vision_z_fudge = 10 # Cozmo underestimates object z coord by about this much
def __init__(self,robot):
self.robot = robot
self.objects = dict()
self.shared_objects = dict()
def clear(self):
self.objects.clear()
self.robot.world.particle_filter.clear_landmarks()
def add_fixed_landmark(self,landmark):
landmark.is_fixed = True
self.objects[landmark.id] = landmark
if isinstance(landmark,WallObj):
wall = landmark
if wall.marker_specs:
self.robot.world.particle_filter.add_fixed_landmark(landmark)
wall.make_doorways(self)
wall.make_arucos(self)
else:
self.robot.world.particle_filter.add_fixed_landmark(landmark)
def add_mapFace(self, mapFace):
self.objects[mapFace.id] = mapFace
def delete_wall(self,wall_id):
"Delete a wall, its markers, and its doorways, so we can predefine a new one."
wall = self.objects.get(wall_id,None)
if wall is None: return
marker_ids = [('Aruco-'+str(id)) for id in wall.marker_specs.keys()]
door_ids = [('Doorway-'+str(id)) for id in wall.door_ids]
landmarks = self.robot.world.particle_filter.sensor_model.landmarks
del self.objects[wall_id]
if wall_id in landmarks:
del landmarks[wall_id]
for marker_id in marker_ids:
if marker_id in self.objects:
del self.objects[marker_id]
if marker_id in landmarks:
del landmarks[marker_id]
for door_id in door_ids:
if door_id in self.objects:
del self.objects[door_id]
def update_map(self):
"""Called to update the map after every camera image, after
object_observed and object_moved events, and just before the
path planner runs.
"""
for (id,cube) in self.robot.world.light_cubes.items():
self.update_cube(cube)
if self.robot.world.charger: self.update_charger()
for face in self.robot.world._faces.values():
if face.face_id == face.updated_face_id:
self.update_face(face)
else:
if face in self.robot.world.world_map.objects:
del self.robot.world.world_map.objects[face]
self.update_aruco_landmarks()
self.update_walls()
self.update_doorways()
self.update_rooms()
self.update_perched_cameras()
def update_cube(self, cube):
cube_id = 'Cube-' + str(cube.cube_id)
if cube_id in self.objects:
foreign_id = "LightCubeForeignObj-"+str(cube.cube_id)
if foreign_id in self.objects:
# remove foreign cube when local cube seen
del self.objects[foreign_id]
wmobject = self.objects[cube_id]
wmobject.sdk_obj = cube # In case created before seen
if self.robot.carrying is wmobject:
if cube.is_visible: # we thought we were carrying it, but we're wrong
self.robot.carrying = None
return self.update_cube(cube)
else: # we do appear to be carrying it
self.update_carried_object(wmobject)
elif cube.pose is None: # not in contact with cube
return None
else:
# Cube is not in the worldmap, so add it.
wmobject = LightCubeObj(cube)
self.objects[cube_id] = wmobject
if cube.is_visible:
wmobject.update_from_sdk = True # In case we've just dropped it; now we see it
wmobject.pose_confidence = +1
elif (cube.pose is None):
return wmobject
elif wmobject.update_from_sdk and not cube.pose.is_comparable(self.robot.pose): # Robot picked up or cube moved
if (self.robot.fetching and self.robot.fetching.sdk_obj is cube) or \
(self.robot.carrying and self.robot.carrying.sdk_obj is cube):
pass
else:
wmobject.pose_confidence = -1
return wmobject
else: # Robot re-localized so cube came back
pass # skip for now due to SDK bug
# wmobject.update_from_sdk = True
wmobject.pose_confidence = max(0, wmobject.pose_confidence)
if wmobject.update_from_sdk: # True unless if we've dropped it and haven't seen it yet
self.update_coords_from_sdk(wmobject, cube)
wmobject.orientation, _, _, wmobject.theta = get_orientation_state(cube.pose.rotation.q0_q1_q2_q3)
return wmobject
def update_charger(self):
charger = self.robot.world.charger
if charger is None: return
charger_id = 'Charger'
wmobject = self.objects.get(charger_id, None)
if wmobject is None:
wmobject = ChargerObj(charger)
self.objects[charger_id] = wmobject
wmobject.sdk_obj = charger # In case we created charger before seeing it
if self.robot.is_on_charger:
wmobject.update_from_sdk = False
theta = wrap_angle(self.robot.world.particle_filter.pose[2] + pi)
charger_offset = np.array([[-30], [0], [0], [1]])
offset = geometry.aboutZ(theta).dot(charger_offset)
wmobject.x = self.robot.world.particle_filter.pose[0] + offset[0,0]
wmobject.y = self.robot.world.particle_filter.pose[1] + offset[1,0]
wmobject.theta = theta
wmobject.pose_confidence = +1
elif charger.is_visible:
wmobject.update_from_sdk = True
wmobject.pose_confidence = +1
elif ((charger.pose is None) or not charger.pose.is_comparable(self.robot.pose)):
wmobject.update_from_sdk = False
wmobject.pose_confidence = -1
else: # Robot re-localized so charger pose came back
pass # skip for now due to SDK bug
# wmobject.update_from_sdk = True
# wmobject.pose_confidence = max(0, wmobject.pose_confidence)
if wmobject.update_from_sdk: # True unless pose isn't comparable
self.update_coords_from_sdk(wmobject, charger)
wmobject.orientation, _, _, wmobject.theta = get_orientation_state(charger.pose.rotation.q0_q1_q2_q3)
return wmobject
def update_aruco_landmarks(self):
try:
seen_marker_objects = self.robot.world.aruco.seen_marker_objects.copy()
except:
return
aruco_parent = self.robot.world.aruco
for (key,value) in seen_marker_objects.items():
marker_id = value.id_string
wmobject = self.objects.get(marker_id, None)
if wmobject is None:
# TODO: wait to see marker several times before adding.
wmobject = ArucoMarkerObj(aruco_parent,key) # coordinates will be filled in below
self.objects[marker_id] = wmobject
landmark_spec = None
else:
landmark_spec = self.robot.world.particle_filter.sensor_model.landmarks.get(marker_id, None)
wmobject.pose_confidence = +1
if isinstance(landmark_spec, tuple): # Particle filter is tracking this marker
wmobject.x = landmark_spec[0][0][0]
wmobject.y = landmark_spec[0][1][0]
wmobject.theta = landmark_spec[1]
elevation = atan2(value.camera_coords[1], value.camera_coords[2])
cam_pos = geometry.point(0,
value.camera_distance * sin(elevation),
value.camera_distance * cos(elevation))
base_pos = self.robot.kine.joint_to_base('camera').dot(cam_pos)
wmobject.z = base_pos[2,0]
wmobject.elevation = elevation
wmobject.cam_pos = cam_pos
wmobject.base_pos = base_pos
elif isinstance(landmark_spec, Pose): # Hard-coded landmark pose for laboratory exercises
wmobject.x = landmark_spec.position.x
wmobject.y = landmark_spec.position.y
wmobject.theta = landmark_spec.rotation.angle_z.radians
wmobject.is_fixed = True
else:
# Non-landmark: convert aruco sensor values to pf coordinates and update
elevation = atan2(value.camera_coords[1], value.camera_coords[2])
cam_pos = geometry.point(0,
value.camera_distance * sin(elevation),
value.camera_distance * cos(elevation))
base_pos = self.robot.kine.joint_to_base('camera').dot(cam_pos)
wmobject.x = base_pos[0,0]
wmobject.y = base_pos[1,0]
wmobject.z = base_pos[2,0]
wmobject.theta = wrap_angle(self.robot.world.particle_filter.pose[2] +
value.euler_rotation[1]*(pi/180) + pi)
wmobject.elevation = elevation
wmobject.cam_pos = cam_pos
wmobject.base_pos = base_pos
def update_walls(self):
for key, value in self.robot.world.particle_filter.sensor_model.landmarks.items():
if key.startswith('Wall-'):
if key in self.objects:
wall = self.objects[key]
if not wall.is_fixed and not wall.is_foreign:
wall.update(self,x=value[0][0][0], y=value[0][1][0], theta=value[1])
else:
print('Creating new wall in worldmap:',key)
wall_spec = wall_marker_dict[key]
wall = WallObj(id=key,
x=value[0][0][0],
y=value[0][1][0],
theta=value[1],
length=wall_spec.length,
height=wall_spec.height,
door_width=wall_spec.door_width,
door_height=wall_spec.door_height,
marker_specs=wall_spec.marker_specs,
doorways=wall_spec.doorways,
door_ids=wall_spec.door_ids,
is_foreign=False,
spec_id=key)
self.objects[key] = wall
wall.pose_confidence = +1
# Make the doorways
wall.make_doorways(self.robot.world.world_map)
# Relocate the aruco markers to their predefined positions
spec = wall_marker_dict.get(wall.id, None)
if spec is None: return
for key,value in spec.marker_specs.items():
if key in self.robot.world.world_map.objects:
aruco_marker = self.robot.world.world_map.objects[key]
dir = value[0] # +1 for front side or -1 for back side
s = 0 if dir == +1 else pi
aruco_marker.theta = wrap_angle(wall.theta + s)
wall_xyz = geometry.point(-dir*(wall.length/2 - value[1][0]), 0, value[1][1])
rel_xyz = geometry.aboutZ(aruco_marker.theta + pi/2).dot(wall_xyz)
aruco_marker.x = wall.x + rel_xyz[0][0]
aruco_marker.y = wall.y + rel_xyz[1][0]
aruco_marker.z = rel_xyz[2][0]
aruco_marker.is_fixed = wall.is_fixed
def update_doorways(self):
for key,value in self.robot.world.world_map.objects.items():
if key.startswith('Doorway'):
value.update()
def update_rooms(self):
LOCALIZED = 'localized' # should be from ParticleFilter.LOCALIZED
if self.robot.world.particle_filter.state == LOCALIZED:
confidence = +1
else:
confidence = -1
for obj in self.robot.world.world_map.objects.values():
if isinstance(obj, RoomObj):
obj.pose_confidence = confidence
def lookup_face_obj(self,face):
"Look up face by name, not by Face instance."
for (key,value) in self.robot.world.world_map.objects.items():
if isinstance(value, FaceObj) and value.name == face.name:
if value.sdk_obj is not face and face.is_visible:
# Older Face object with same name: replace it with new one
value.sdk_obj = face
value.id = face.face_id
return value
return None
def update_face(self,face):
if face.pose is None:
return
pos = face.pose.position
face_obj = self.lookup_face_obj(face)
if face_obj is None:
face_obj = FaceObj(face, face.face_id, pos.x, pos.y, pos.z,
face.name)
if len(face.name) == 0:
key = 'Face:unknown'
else:
key = 'Face:' + face.name
self.robot.world.world_map.objects[key] = face_obj
else:
face_obj.sdk_obj = face # in case face.updated_id changed
# now update the face
if face.is_visible:
face_obj.x = pos.x
face_obj.y = pos.y
face_obj.z = pos.z
face_obj.expression = face.expression
self.update_coords_from_sdk(face_obj, face)
def update_custom_object(self, sdk_obj):
if not sdk_obj.pose.is_comparable(self.robot.pose):
print('Should never get here:',sdk_obj.pose,self.robot.pose)
return
id = 'CustomMarkerObj-' + str(sdk_obj.object_type.name[-2:])
if not sdk_obj.is_unique:
id += '-' + str(sdk_obj.object_id)
if id in self.objects:
wmobject = self.objects[id]
wmobject.sdk_obj = sdk_obj # In case created marker before seeing it
else:
type = sdk_obj.object_type
if type in custom_objs.custom_marker_types:
wmobject = CustomMarkerObj(sdk_obj,id)
elif type in custom_objs.custom_cube_types:
wmobject = CustomCubeObj(sdk_obj,id)
else: # if we don't know what else to do with it, treat as a custom marker
wmobject = CustomMarkerObj(sdk_obj,id)
self.objects[id] = wmobject
wmobject.pose_confidence = +1
self.update_coords_from_sdk(wmobject, sdk_obj)
if isinstance(wmobject, CustomMarkerObj):
wmobject.orientation, wmobject.rotation, _, _ = \
get_orientation_state(sdk_obj.pose.rotation.q0_q1_q2_q3, isPlanar=True)
elif isinstance(wmobject, CustomCubeObj):
wmobject.orientation, _, _, wmobject.rotation = \
get_orientation_state(sdk_obj.pose.rotation.q0_q1_q2_q3, isPlanar=False)
def update_carried_object(self, wmobject):
#print('Updating carried object ',wmobject)
# set x,y based on robot's pose
# need to cache initial orientation relative to robot:
# grasped_orient = wmobject.theta - robot.pose.rotation.angle_z
world_frame = self.robot.kine.joints['world']
lift_attach_frame = self.robot.kine.joints['lift_attach']
tmat = self.robot.kine.base_to_link(world_frame).dot(self.robot.kine.joint_to_base(lift_attach_frame))
# *** HACK *** : depth calculation only works for cubes; need to handle custom obj, chips
half_depth = wmobject.size[0] / 2
new_pose = tmat.dot(geometry.point(half_depth,0))
theta = self.robot.world.particle_filter.pose[2]
wmobject.x = new_pose[0,0]
wmobject.y = new_pose[1,0]
wmobject.z = new_pose[2,0]
wmobject.theta = theta
def update_coords_from_sdk(self, wmobject, sdk_obj):
dx = sdk_obj.pose.position.x - self.robot.pose.position.x
dy = sdk_obj.pose.position.y - self.robot.pose.position.y
alpha = atan2(dy,dx) - self.robot.pose.rotation.angle_z.radians
r = sqrt(dx*dx + dy*dy)
(rob_x,rob_y,rob_theta) = self.robot.world.particle_filter.pose
wmobject.x = rob_x + r * cos(alpha + rob_theta)
wmobject.y = rob_y + r * sin(alpha + rob_theta)
wmobject.z = sdk_obj.pose.position.z
orient_diff = wrap_angle(rob_theta - self.robot.pose.rotation.angle_z.radians)
wmobject.theta = wrap_angle(sdk_obj.pose.rotation.angle_z.radians + orient_diff)
def update_perched_cameras(self):
if self.robot.world.server.started:
pool = self.robot.world.server.camera_landmark_pool
for key, val in pool.get(self.robot.aruco_id,{}).items():
if key.startswith('Video'):
if key in self.objects:
self.objects[key].update(x=val[0][0,0], y=val[0][1,0], z=val[1][0],
theta=val[1][2], phi=val[1][1])
else:
# last digit of capture id as camera key
self.objects[key] = \
CameraObj(id=int(key[-2]), x=val[0][0,0], y=val[0][1,0],
z=val[1][0], theta=val[1][2], phi=val[1][1])
else:
for key, val in self.robot.world.particle_filter.sensor_model.landmarks.items():
if key.startswith('Video'):
if key in self.objects:
self.objects[key].update(x=val[0][0,0], y=val[0][1,0], z=val[1][0],
theta=val[1][2], phi=val[1][1])
else:
# last digit of capture id as camera key
self.objects[key] = \
CameraObj(id=int(key[-2]), x=val[0][0,0], y=val[0][1,0],
z=val[1][0], theta=val[1][2], phi=val[1][1])
def invalidate_poses(self):
# *** This medthod is not currently used. ***
for wmobj in self.robot.world.world_map.objects.values():
if not wmobj.is_fixed:
wmobj.pose_confidence = -1
def show_objects(self):
objs = self.objects
print('%d object%s in the world map:' %
(len(objs), '' if len(objs) == 1 else 's'))
basics = ['Charger', 'Cube-1', 'Cube-2', 'Cube-3']
ordered_keys = []
for key in basics:
if key in objs:
ordered_keys.append(key)
customs = []
arucos = []
walls = []
misc = []
for (key,value) in objs.items():
if key in basics:
pass
elif isinstance(value, CustomMarkerObj):
customs.append(key)
elif isinstance(value, ArucoMarkerObj):
arucos.append(key)
elif isinstance(value, WallObj):
walls.append(key)
else:
misc.append(key)
arucos.sort()
walls.sort()
ordered_keys = ordered_keys + customs + arucos + walls + misc
for key in ordered_keys:
print(' ', objs[key])
print()
def show_pose(self):
print('robot.pose is: %6.1f %6.1f @ %6.1f deg.' %
(self.robot.pose.position.x,
self.robot.pose.position.y,
self.robot.pose_angle.degrees))
print('particle filter: %6.1f %6.1f @ %6.1f deg. [%s]' %
(*self.robot.world.particle_filter.pose[0:2],
self.robot.world.particle_filter.pose[2]*180/pi,
self.robot.world.particle_filter.state))
print()
def generate_doorway_list(self):
"Used by path-planner.py"
doorways = []
for (key,obj) in self.objects.items():
if isinstance(obj,DoorwayObj):
w = obj.door_width / 2
doorway_threshold_theta = obj.theta + pi/2
dx = w * cos(doorway_threshold_theta)
dy = w * sin(doorway_threshold_theta)
doorways.append((obj, ((obj.x-dx, obj.y-dy), (obj.x+dx, obj.y+dy))))
return doorways
#================ Event Handlers ================
def handle_object_observed(self, evt, **kwargs):
if isinstance(evt.obj, LightCube):
# print('observed: ',evt.obj)
self.update_cube(evt.obj)
elif isinstance(evt.obj, CustomObject):
self.update_custom_object(evt.obj)
elif isinstance(evt.obj, Face):
self.update_face(evt.obj)
def handle_object_move_started(self, evt, **kwargs):
cube = evt.obj
if (self.robot.carrying and self.robot.carrying.sdk_obj is cube) or \
(self.robot.fetching and self.robot.fetching.sdk_obj is cube):
return
cube.movement_start_time = time.time()
cube_id = 'Cube-' + str(cube.cube_id)
try: # wmobj may not have been created yet
wmobject = self.robot.world.world_map.objects[cube_id]
wmobject.pose_confidence = min(0, wmobject.pose_confidence)
except:
pass
def handle_object_move_stopped(self, evt, **kwargs):
cube = evt.obj
cube.movement_start_time = None
#================ Wall Specification ================
# WallSpec is used in wall_defs.py
wall_marker_dict = dict()
class WallSpec():
def __init__(self, label=None, length=100, height=210, door_width=77, door_height=105,
marker_specs=dict(), doorways=[], door_ids=[]):
self.length = length
self.height = height
self.door_width = door_width
self.door_height = door_height
self.marker_specs = marker_specs
self.doorways = doorways
self.door_ids = door_ids
marker_id_numbers = [int(marker_id[1+marker_id.rfind('-'):]) for marker_id in marker_specs.keys()]
if label and len(marker_id_numbers) == 0:
self.spec_id = 'Wall-' + label # 'Wall-A' for 'A'
label = 'Wall-' + label
elif len(marker_id_numbers) > 0 and not label:
lowest_marker_id = 'Aruco-%d' % min(marker_id_numbers)
self.spec_id = 'Wall-%d' % min(marker_id_numbers)
label = self.spec_id # 'Wall-37' for 'Aruco-37'
else:
raise ValueError("Don't know how to label wall '%s'" % label)
self.label = label
global wall_marker_dict
for id in marker_specs.keys():
wall_marker_dict[id] = self
wall_marker_dict[label] = self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,035
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/pilot.py
|
import math
import time
import sys
import asyncio
from .base import *
from .rrt import *
#from .nodes import ParentFails, ParentCompletes, DriveArc, DriveContinuous, Forward, Turn
from .nodes import *
from .events import PilotEvent
#from .transitions import CompletionTrans, FailureTrans, SuccessTrans, DataTrans, NullTrans
from .transitions import *
from .cozmo_kin import wheelbase, center_of_rotation_offset
from .worldmap import WorldObject, DoorwayObj
from .path_planner import PathPlannerProcess, PathPlanner
from .geometry import segment_intersect_test
from .doorpass import DoorPass
from .pilot0 import *
from cozmo.util import Pose, distance_mm, radians, degrees, speed_mmps
#---------------- Pilot Exceptions and Events ----------------
class PilotException(Exception):
def __str__(self):
return self.__repr__()
class InvalidPose(PilotException): pass
class CollisionDetected(PilotException): pass
# Note: StartCollides, GoalCollides, and MaxIterations exceptions are defined in rrt.py.
class ParentPilotEvent(StateNode):
"""Receive a PilotEvent and repost it from the receiver's parent. This allows
derived classes that use the Pilot to make its PilotEvents visible."""
def start(self,event):
super().start(event)
if not isinstance(event,PilotEvent):
raise TypeError("ParentPilotEvent must be invoked with a PilotEvent, not %s" % event)
if 'grid_display' in event.args:
self.robot.world.rrt.grid_display = event.args['grid_display']
event2 = PilotEvent(event.status)
event2.args = event.args
self.parent.post_event(event2)
#---------------- PilotBase ----------------
class PilotBase(StateNode):
"""Base class for PilotToObject, PilotToPose, etc."""
class ClearDisplays(StateNode):
def start(self,event=None):
super().start()
if self.robot.world.path_viewer:
self.robot.world.path_viewer.clear()
class SendObject(StateNode):
def start(self,event=None):
super().start()
object = self.parent.object
if object.pose_confidence < 0:
self.parent.post_event(PilotEvent(NotLocalized,object=object))
self.parent.post_failure()
return
self.post_event(DataEvent(self.parent.object))
class ReceivePlan(StateNode):
def start(self, event=None):
super().start(event)
if not isinstance(event, DataEvent):
raise ValueError(event)
(navplan, grid_display) = event.data
self.robot.world.rrt.draw_path = navplan.extract_path()
#print('ReceivePlan: draw_path=', self.robot.world.rrt.draw_path)
self.robot.world.rrt.grid_display = grid_display
self.post_event(DataEvent(navplan))
class PilotExecutePlan(StateNode):
def start(self, event=None):
if not isinstance(event, DataEvent) and isinstance(event.data, NavPlan):
raise ValueError(event)
self.navplan = event.data
self.index = 0
super().start(event)
class DispatchStep(StateNode):
def start(self, event=None):
super().start(event)
step = self.parent.navplan.steps[self.parent.index]
print('nav step', step)
self.post_event(DataEvent(step.type))
class ExecuteDrive(DriveContinuous):
def start(self, event=None):
step = self.parent.navplan.steps[self.parent.index]
super().start(DataEvent(step.param))
class ExecuteDoorPass(DoorPass):
def start(self, event=None):
step = self.parent.navplan.steps[self.parent.index]
super().start(DataEvent(step.param))
class ExecuteBackup(Forward):
def start(self, event=None):
step = self.parent.navplan.steps[self.parent.index]
if len(step.param) > 1:
print('***** WARNING: extra backup steps not being processed *****')
node = step.param[0]
dx = node.x - self.robot.world.particle_filter.pose[0]
dy = node.y - self.robot.world.particle_filter.pose[1]
self.distance = distance_mm(- sqrt(dx*dx + dy*dy))
super().start(event)
class NextStep(StateNode):
def start(self, event=None):
super().start(event)
self.parent.index += 1
if self.parent.index < len(self.parent.navplan.steps):
self.post_success()
else:
self.post_completion()
def setup(self):
# # PilotExecutePlan machine
#
# dispatch: self.DispatchStep()
# dispatch =D(NavStep.DRIVE)=> drive
# dispatch =D(NavStep.DOORPASS)=> doorpass
# dispatch =D(NavStep.BACKUP)=> backup
#
# drive: self.ExecuteDrive()
# drive =C=> next
# drive =F=> ParentFails()
#
# doorpass: self.ExecuteDoorPass()
# doorpass =C=> next
# doorpass =F=> ParentFails()
#
# backup: self.ExecuteBackup()
# backup =C=> next
# backup =F=> ParentFails()
#
# next: self.NextStep()
# next =S=> dispatch
# next =C=> ParentCompletes()
# Code generated by genfsm on Sat Feb 18 04:45:30 2023:
dispatch = self.DispatchStep() .set_name("dispatch") .set_parent(self)
drive = self.ExecuteDrive() .set_name("drive") .set_parent(self)
parentfails1 = ParentFails() .set_name("parentfails1") .set_parent(self)
doorpass = self.ExecuteDoorPass() .set_name("doorpass") .set_parent(self)
parentfails2 = ParentFails() .set_name("parentfails2") .set_parent(self)
backup = self.ExecuteBackup() .set_name("backup") .set_parent(self)
parentfails3 = ParentFails() .set_name("parentfails3") .set_parent(self)
next = self.NextStep() .set_name("next") .set_parent(self)
parentcompletes1 = ParentCompletes() .set_name("parentcompletes1") .set_parent(self)
datatrans1 = DataTrans(NavStep.DRIVE) .set_name("datatrans1")
datatrans1 .add_sources(dispatch) .add_destinations(drive)
datatrans2 = DataTrans(NavStep.DOORPASS) .set_name("datatrans2")
datatrans2 .add_sources(dispatch) .add_destinations(doorpass)
datatrans3 = DataTrans(NavStep.BACKUP) .set_name("datatrans3")
datatrans3 .add_sources(dispatch) .add_destinations(backup)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(drive) .add_destinations(next)
failuretrans1 = FailureTrans() .set_name("failuretrans1")
failuretrans1 .add_sources(drive) .add_destinations(parentfails1)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(doorpass) .add_destinations(next)
failuretrans2 = FailureTrans() .set_name("failuretrans2")
failuretrans2 .add_sources(doorpass) .add_destinations(parentfails2)
completiontrans3 = CompletionTrans() .set_name("completiontrans3")
completiontrans3 .add_sources(backup) .add_destinations(next)
failuretrans3 = FailureTrans() .set_name("failuretrans3")
failuretrans3 .add_sources(backup) .add_destinations(parentfails3)
successtrans1 = SuccessTrans() .set_name("successtrans1")
successtrans1 .add_sources(next) .add_destinations(dispatch)
completiontrans4 = CompletionTrans() .set_name("completiontrans4")
completiontrans4 .add_sources(next) .add_destinations(parentcompletes1)
return self
# End of PilotExecutePlan
# End of PilotBase
#---------------- PilotToObject ----------------
class PilotToObject(PilotBase):
"Use the wavefront planner to navigate to a distant object."
def __init__(self, object=None):
super().__init__()
self.object=object
def start(self, event=None):
if isinstance(event,DataEvent):
if isinstance(event.data, WorldObject):
self.object = event.data
else:
raise ValueError('DataEvent to PilotToObject must be a WorldObject', event.data)
if not isinstance(self.object, WorldObject):
if hasattr(self.object, 'wm_obj'):
self.object = self.object.wm_obj
else:
raise ValueError('Argument to PilotToObject constructor must be a WorldObject or SDK object', self.object)
super().start(event)
class CheckArrival(StateNode):
def start(self, event=None):
super().start(event)
pf_pose = self.robot.world.particle_filter.pose
if True: # *** TODO: check if we've arrived at the target shape
self.post_success()
else:
self.post_failure()
def setup(self):
# # PilotToObject machine
#
# launch: self.ClearDisplays() =N=> self.SendObject() =D=> planner
#
# planner: PathPlannerProcess() =D=> recv
# planner =PILOT=> ParentPilotEvent() =N=> Print('Path planner failed')
#
# recv: self.ReceivePlan() =D=> exec
#
# exec: self.PilotExecutePlan()
# exec =C=> check
# exec =F=> ParentFails()
#
# check: self.CheckArrival()
# check =S=> ParentCompletes()
# check =F=> planner
# Code generated by genfsm on Sat Feb 18 04:45:30 2023:
launch = self.ClearDisplays() .set_name("launch") .set_parent(self)
sendobject1 = self.SendObject() .set_name("sendobject1") .set_parent(self)
planner = PathPlannerProcess() .set_name("planner") .set_parent(self)
parentpilotevent1 = ParentPilotEvent() .set_name("parentpilotevent1") .set_parent(self)
print1 = Print('Path planner failed') .set_name("print1") .set_parent(self)
recv = self.ReceivePlan() .set_name("recv") .set_parent(self)
exec = self.PilotExecutePlan() .set_name("exec") .set_parent(self)
parentfails4 = ParentFails() .set_name("parentfails4") .set_parent(self)
check = self.CheckArrival() .set_name("check") .set_parent(self)
parentcompletes2 = ParentCompletes() .set_name("parentcompletes2") .set_parent(self)
nulltrans1 = NullTrans() .set_name("nulltrans1")
nulltrans1 .add_sources(launch) .add_destinations(sendobject1)
datatrans4 = DataTrans() .set_name("datatrans4")
datatrans4 .add_sources(sendobject1) .add_destinations(planner)
datatrans5 = DataTrans() .set_name("datatrans5")
datatrans5 .add_sources(planner) .add_destinations(recv)
pilottrans1 = PilotTrans() .set_name("pilottrans1")
pilottrans1 .add_sources(planner) .add_destinations(parentpilotevent1)
nulltrans2 = NullTrans() .set_name("nulltrans2")
nulltrans2 .add_sources(parentpilotevent1) .add_destinations(print1)
datatrans6 = DataTrans() .set_name("datatrans6")
datatrans6 .add_sources(recv) .add_destinations(exec)
completiontrans5 = CompletionTrans() .set_name("completiontrans5")
completiontrans5 .add_sources(exec) .add_destinations(check)
failuretrans4 = FailureTrans() .set_name("failuretrans4")
failuretrans4 .add_sources(exec) .add_destinations(parentfails4)
successtrans2 = SuccessTrans() .set_name("successtrans2")
successtrans2 .add_sources(check) .add_destinations(parentcompletes2)
failuretrans5 = FailureTrans() .set_name("failuretrans5")
failuretrans5 .add_sources(check) .add_destinations(planner)
return self
#---------------- PilotToPose ----------------
class PilotToPose(PilotBase):
"Use the rrt path planner for short-range navigation to a specific pose."
def __init__(self, target_pose=None, verbose=False, max_iter=RRT.DEFAULT_MAX_ITER):
super().__init__()
self.target_pose = target_pose
self.verbose = verbose
self.max_iter = max_iter
def start(self, event=None):
if isinstance(event, DataEvent) and isinstance(event.data, Pose):
self.target_pose = event.data
self.robot.world.rrt.max_iter = self.max_iter
super().start(self)
class PilotRRTPlanner(StateNode):
def planner(self,start_node,goal_node):
return self.robot.world.rrt.plan_path(start_node,goal_node)
def start(self,event=None):
super().start(event)
tpose = self.parent.target_pose
if tpose is None or (tpose.position.x == 0 and tpose.position.y == 0 and
tpose.rotation.angle_z.radians == 0 and not tpose.is_valid):
print("Pilot: target pose is invalid: %s" % tpose)
self.parent.post_event(PilotEvent(InvalidPose, pose=tpose))
self.parent.post_failure()
return
(pose_x, pose_y, pose_theta) = self.robot.world.particle_filter.pose
start_node = RRTNode(x=pose_x, y=pose_y, q=pose_theta)
goal_node = RRTNode(x=tpose.position.x, y=tpose.position.y,
q=tpose.rotation.angle_z.radians)
start_escape_move = None
try:
(treeA, treeB, path) = self.planner(start_node, goal_node)
except StartCollides as e:
# See if we can escape the start collision using canned headings.
# This could be made more sophisticated, e.g., using arcs.
#print('planner',e,'start',start_node)
escape_distance = 50 # mm
escape_headings = (0, +30/180.0*pi, -30/180.0*pi, pi, pi/2, -pi/2)
for phi in escape_headings:
if phi != pi:
new_q = wrap_angle(start_node.q + phi)
d = escape_distance
else:
new_q = start_node.q
d = -escape_distance
new_start = RRTNode(x=start_node.x + d*cos(new_q),
y=start_node.y + d*sin(new_q),
q=new_q)
# print('trying start escape', new_start)
if not self.robot.world.rrt.collides(new_start):
start_escape_move = (phi, start_node, new_start)
start_node = new_start
break
if start_escape_move is None:
print('PilotRRTPlanner: Start collides!',e)
self.parent.post_event(PilotEvent(StartCollides, args=e.args))
self.parent.post_failure()
return
try:
(treeA, treeB, path) = self.planner(start_node, goal_node)
except GoalCollides as e:
print('PilotRRTPlanner: Goal collides!',e)
self.parent.post_event(PilotEvent(GoalCollides, args=e.args))
self.parent.post_failure()
return
except MaxIterations as e:
print('PilotRRTPlanner: Max iterations %d exceeded!' % e.args[0])
self.parent.post_event(PilotEvent(MaxIterations, args=e.args))
self.parent.post_failure()
return
#print('replan',path)
except GoalCollides as e:
print('PilotRRTPlanner: Goal collides!',e)
self.parent.post_event(PilotEvent(GoalCollides, args=e.args))
self.parent.post_failure()
return
except MaxIterations as e:
print('PilotRRTPlanner: Max iterations %d exceeded!' % e.args[0])
self.parent.post_event(PilotEvent(MaxIterations, args=e.args))
self.parent.post_failure()
return
if self.parent.verbose:
print('Path planner generated',len(treeA)+len(treeB),'nodes.')
if self.parent.robot.world.path_viewer:
self.parent.robot.world.path_viewer.add_tree(path, (1,0,0,0.75))
self.robot.world.rrt.draw_path = path
# Construct the nav plan
if self.parent.verbose:
[print(' ',x) for x in path]
doors = self.robot.world.world_map.generate_doorway_list()
navplan = PathPlanner.from_path(path, doors)
print('navplan=',navplan, ' steps=',navplan.steps)
# Insert the StartCollides escape move if there is one
if start_escape_move:
phi, start, new_start = start_escape_move
if phi == pi:
escape_step = NavStep(NavStep.BACKUP, [new_start])
navplan.steps.insert(0, escape_step)
elif navplan.steps[0].type == NavStep.DRIVE:
# Insert at the beginning the original start node we replaced with new_start
navplan.steps[0].param.insert(0, start_node)
else:
# Shouldn't get here, but just in case
escape_step = NavStep(NavStep.DRIVE, (RRTNode(start.x,start.y), RRTNode(new_start.x,new_start.y)))
navplan.steps.insert(0, escape_step)
#print('finalnavplan steps:', navplan.steps)
# If no doorpass, we're good to go
last_step = navplan.steps[-1]
grid_display = None
if last_step.type != NavStep.DOORPASS:
self.post_data((navplan,grid_display))
return
# We planned for a doorpass as the last step; replan to the outer gate.
door = last_step.param
last_node = navplan.steps[-2].param[-1]
gate = DoorPass.calculate_gate((last_node.x, last_node.y), door, DoorPass.OUTER_GATE_DISTANCE)
goal_node = RRTNode(x=gate[0], y=gate[1], q=gate[2])
print('new goal is', goal_node)
try:
(_, _, path) = self.planner(start_node, goal_node)
except Exception as e:
print('Pilot replanning for door gateway failed!', e.args)
cpath = [(node.x,node.y) for node in path]
navplan = PathPlanner.from_path(cpath, [])
navplan.steps.append(last_step) # Add the doorpass step
self.post_data((navplan,grid_display))
# ----- End of PilotRRTPlanner -----
class CheckArrival(StateNode):
def start(self, event=None):
super().start(event)
pf_pose = self.robot.world.particle_filter.pose
current_pose = Pose(pf_pose[0], pf_pose[1], 0, angle_z=radians(pf_pose[2]))
pose_diff = current_pose - self.parent.target_pose
distance = (pose_diff.position.x**2 + pose_diff.position.y**2) ** 0.5
MAX_TARGET_DISTANCE = 50.0 # mm
if distance <= MAX_TARGET_DISTANCE:
self.post_success()
else:
self.post_failure()
def setup(self):
# # PilotToPose machine
#
# launch: self.ClearDisplays() =N=> planner
#
# planner: self.PilotRRTPlanner() =D=> recv
# planner =PILOT=> ParentPilotEvent() =N=> Print('Path planner failed')
#
# recv: self.ReceivePlan() =D=> exec
#
# exec: self.PilotExecutePlan()
# exec =C=> check
# exec =F=> ParentFails()
#
# check: self.CheckArrival()
# check =S=> ParentCompletes()
# check =F=> planner
# Code generated by genfsm on Sat Feb 18 04:45:30 2023:
launch = self.ClearDisplays() .set_name("launch") .set_parent(self)
planner = self.PilotRRTPlanner() .set_name("planner") .set_parent(self)
parentpilotevent2 = ParentPilotEvent() .set_name("parentpilotevent2") .set_parent(self)
print2 = Print('Path planner failed') .set_name("print2") .set_parent(self)
recv = self.ReceivePlan() .set_name("recv") .set_parent(self)
exec = self.PilotExecutePlan() .set_name("exec") .set_parent(self)
parentfails5 = ParentFails() .set_name("parentfails5") .set_parent(self)
check = self.CheckArrival() .set_name("check") .set_parent(self)
parentcompletes3 = ParentCompletes() .set_name("parentcompletes3") .set_parent(self)
nulltrans3 = NullTrans() .set_name("nulltrans3")
nulltrans3 .add_sources(launch) .add_destinations(planner)
datatrans7 = DataTrans() .set_name("datatrans7")
datatrans7 .add_sources(planner) .add_destinations(recv)
pilottrans2 = PilotTrans() .set_name("pilottrans2")
pilottrans2 .add_sources(planner) .add_destinations(parentpilotevent2)
nulltrans4 = NullTrans() .set_name("nulltrans4")
nulltrans4 .add_sources(parentpilotevent2) .add_destinations(print2)
datatrans8 = DataTrans() .set_name("datatrans8")
datatrans8 .add_sources(recv) .add_destinations(exec)
completiontrans6 = CompletionTrans() .set_name("completiontrans6")
completiontrans6 .add_sources(exec) .add_destinations(check)
failuretrans6 = FailureTrans() .set_name("failuretrans6")
failuretrans6 .add_sources(exec) .add_destinations(parentfails5)
successtrans3 = SuccessTrans() .set_name("successtrans3")
successtrans3 .add_sources(check) .add_destinations(parentcompletes3)
failuretrans7 = FailureTrans() .set_name("failuretrans7")
failuretrans7 .add_sources(check) .add_destinations(planner)
return self
class PilotPushToPose(PilotToPose):
def __init__(self,pose):
super().__init__(pose)
self.max_turn = 20*(pi/180)
def planner(self,start_node,goal_node):
self.robot.world.rrt.step_size=20
return self.robot.world.rrt.plan_push_chip(start_node,goal_node)
class PilotFrustration(StateNode):
def __init__(self, text_template=None):
super().__init__()
self.text_template = text_template # contains at most one '%s'
class SayObject(Say):
def start(self, event=None):
text_template = self.parent.text_template
try:
object_name = self.parent.parent.object.name # for rooms
except:
try:
object_name = self.parent.parent.object.id # for cubes
except:
object_name = None
if text_template is not None:
if '%' in text_template:
self.text = text_template % object_name
else:
self.text = text_template
elif object_name is not None:
self.text = 'Can\'t reach %s' % object_name
else:
self.text = 'stuck'
self.robot.world.rrt.text = self.text
super().start(event)
def setup(self):
# launcher: AbortAllActions() =N=> StopAllMotors() =N=> {speak, turn}
#
# speak: self.SayObject()
#
# turn: StateNode() =RND=> {left, right}
#
# left: Turn(5) =C=> left2: Turn(-5)
#
# right: Turn(-5) =C=> right2: Turn(5)
#
# {speak, left2, right2} =C(2)=> animate
#
# animate: AnimationTriggerNode(trigger=cozmo.anim.Triggers.FrustratedByFailure,
# ignore_body_track=True,
# ignore_head_track=True,
# ignore_lift_track=True)
# animate =C=> done
# animate =F=> done
#
# done: ParentCompletes()
# Code generated by genfsm on Sat Feb 18 04:45:30 2023:
launcher = AbortAllActions() .set_name("launcher") .set_parent(self)
stopallmotors1 = StopAllMotors() .set_name("stopallmotors1") .set_parent(self)
speak = self.SayObject() .set_name("speak") .set_parent(self)
turn = StateNode() .set_name("turn") .set_parent(self)
left = Turn(5) .set_name("left") .set_parent(self)
left2 = Turn(-5) .set_name("left2") .set_parent(self)
right = Turn(-5) .set_name("right") .set_parent(self)
right2 = Turn(5) .set_name("right2") .set_parent(self)
animate = AnimationTriggerNode(trigger=cozmo.anim.Triggers.FrustratedByFailure,
ignore_body_track=True,
ignore_head_track=True,
ignore_lift_track=True) .set_name("animate") .set_parent(self)
done = ParentCompletes() .set_name("done") .set_parent(self)
nulltrans5 = NullTrans() .set_name("nulltrans5")
nulltrans5 .add_sources(launcher) .add_destinations(stopallmotors1)
nulltrans6 = NullTrans() .set_name("nulltrans6")
nulltrans6 .add_sources(stopallmotors1) .add_destinations(speak,turn)
randomtrans1 = RandomTrans() .set_name("randomtrans1")
randomtrans1 .add_sources(turn) .add_destinations(left,right)
completiontrans7 = CompletionTrans() .set_name("completiontrans7")
completiontrans7 .add_sources(left) .add_destinations(left2)
completiontrans8 = CompletionTrans() .set_name("completiontrans8")
completiontrans8 .add_sources(right) .add_destinations(right2)
completiontrans9 = CompletionTrans(2) .set_name("completiontrans9")
completiontrans9 .add_sources(speak,left2,right2) .add_destinations(animate)
completiontrans10 = CompletionTrans() .set_name("completiontrans10")
completiontrans10 .add_sources(animate) .add_destinations(done)
failuretrans8 = FailureTrans() .set_name("failuretrans8")
failuretrans8 .add_sources(animate) .add_destinations(done)
return self
"""
class PilotBase(StateNode):
def __init__(self, verbose=False):
super().__init__()
self.verbose = verbose
self.handle = None
self.arc_radius = 40
self.max_turn = pi
def stop(self):
if self.handle:
self.handle.cancel()
self.handle = None
super().stop()
def planner(self):
raise ValueError('No planner specified')
def calculate_arc(self, cur_x, cur_y, cur_q, dest_x, dest_y):
# Compute arc node parameters to get us on a heading toward node_j.
direct_turn_angle = wrap_angle(atan2(dest_y-cur_y, dest_x-cur_x) - cur_q)
# find center of arc we'll be moving along
dir = +1 if direct_turn_angle >=0 else -1
cx = cur_x + self.arc_radius * cos(cur_q + dir*pi/2)
cy = cur_y + self.arc_radius * sin(cur_q + dir*pi/2)
dx = cx - dest_x
dy = cy - dest_y
center_dist = sqrt(dx*dx + dy*dy)
if center_dist < self.arc_radius: # turn would be too wide: punt
if self.verbose:
print('*** TURN TOO WIDE ***, center_dist =',center_dist)
center_dist = self.arc_radius
# tangent points on arc: outer tangent formula from Wikipedia with r=0
gamma = atan2(dy, dx)
beta = asin(self.arc_radius / center_dist)
alpha1 = gamma + beta
tang_x1 = cx + self.arc_radius * cos(alpha1 + pi/2)
tang_y1 = cy + self.arc_radius * sin(alpha1 + pi/2)
tang_q1 = (atan2(tang_y1-cy, tang_x1-cx) + dir*pi/2)
turn1 = tang_q1 - cur_q
if dir * turn1 < 0:
turn1 += dir * 2 * pi
alpha2 = gamma - beta
tang_x2 = cx + self.arc_radius * cos(alpha2 - pi/2)
tang_y2 = cy + self.arc_radius * sin(alpha2 - pi/2)
tang_q2 = (atan2(tang_y2-cy, tang_x2-cx) + dir*pi/2)
turn2 = tang_q2 - cur_q
if dir * turn2 < 0:
turn2 += dir * 2 * pi
# Correct tangent point has shortest turn.
if abs(turn1) < abs(turn2):
(tang_x,tang_y,tang_q,turn) = (tang_x1,tang_y1,tang_q1,turn1)
else:
(tang_x,tang_y,tang_q,turn) = (tang_x2,tang_y2,tang_q2,turn2)
return (dir*self.arc_radius, turn)
async def drive_arc(self,radius,angle):
speed = 50
l_wheel_speed = speed * (1 - wheelbase / radius)
r_wheel_speed = speed * (1 + wheelbase / radius)
last_heading = self.robot.pose.rotation.angle_z.degrees
traveled = 0
cor = self.robot.drive_wheels(l_wheel_speed, r_wheel_speed)
self.handle = self.robot.loop.create_task(cor)
while abs(traveled) < abs(angle):
await asyncio.sleep(0.05)
p0 = last_heading
p1 = self.robot.pose.rotation.angle_z.degrees
last_heading = p1
diff = p1 - p0
if diff < -90.0:
diff += 360.0
elif diff > 90.0:
diff -= 360.0
traveled += diff
self.handle.cancel()
self.handle = None
self.robot.stop_all_motors()
if self.verbose:
print('drive_arc angle=',angle,'deg., traveled=',traveled,'deg.')
class PilotToPoseOld(PilotBase):
def __init__(self, target_pose=None, verbose=False):
super().__init__(verbose)
self.target_pose = target_pose
def planner(self,start_node,goal_node):
return self.robot.world.rrt.plan_path(start_node,goal_node)
def start(self,event=None):
super().start(event)
if self.target_pose is None:
self.post_failure()
return
(pose_x, pose_y, pose_theta) = self.robot.world.particle_filter.pose
start_node = RRTNode(x=pose_x, y=pose_y, q=pose_theta)
tpose = self.target_pose
goal_node = RRTNode(x=tpose.position.x, y=tpose.position.y,
q=tpose.rotation.angle_z.radians)
if self.robot.world.path_viewer:
self.robot.world.path_viewer.clear()
try:
(treeA, treeB, path) = self.planner(start_node, goal_node)
except StartCollides as e:
print('Start collides!',e)
self.post_event(PilotEvent(StartCollides, e.args))
self.post_failure()
return
except GoalCollides as e:
print('Goal collides!',e)
self.post_event(PilotEvent(GoalCollides, e.args))
self.post_failure()
return
except MaxIterations as e:
print('Max iterations %d exceeded!' % e.args[0])
self.post_event(PilotEvent(MaxIterations, e.args))
self.post_failure()
return
if self.verbose:
print(len(treeA)+len(treeB),'nodes')
if self.robot.world.path_viewer:
self.robot.world.path_viewer.add_tree(path, (1,0,0,0.75))
# Construct and execute nav plan
if self.verbose:
[print(x) for x in path]
self.plan = PathPlanner.from_path(path)
if self.verbose:
print('Navigation Plan:')
[print(y) for y in self.plan.steps]
self.robot.loop.create_task(self.execute_plan())
async def execute_plan(self):
print('-------- Executing Nav Plan --------')
for step in self.plan.steps[1:]:
if not self.running: return
self.robot.world.particle_filter.variance_estimate()
(cur_x,cur_y,cur_hdg) = self.robot.world.particle_filter.pose
if step.type == NavStep.HEADING:
(targ_x, targ_y, targ_hdg) = step.params
# Equation of the line y=ax+c through the target pose
a = min(1000, max(-1000, math.tan(targ_hdg)))
c = targ_y - a * targ_x
# Equation of the line y=bx+d through the present pose
b = min(1000, max(-1000, math.tan(cur_hdg)))
d = cur_y - b * cur_x
# Intersection point
int_x = (d-c) / (a-b) if abs(a-b) > 1e-5 else math.nan
int_y = a * int_x + c
dx = int_x - cur_x
dy = int_y - cur_y
dist = sqrt(dx*dx + dy*dy)
if abs(wrap_angle(atan2(dy,dx) - cur_hdg)) > pi/2:
dist = - dist
dist += -center_of_rotation_offset
if self.verbose:
print('PRE-TURN: cur=(%.1f,%.1f) @ %.1f deg., int=(%.1f, %.1f) dist=%.1f' %
(cur_x, cur_y, cur_hdg*180/pi, int_x, int_y, dist))
if abs(dist) < 2:
if self.verbose:
print(' ** SKIPPED **')
else:
await self.robot.drive_straight(distance_mm(dist),
speed_mmps(50)).wait_for_completed()
(cur_x,cur_y,cur_hdg) = self.robot.world.particle_filter.pose
turn_angle = wrap_angle(targ_hdg - cur_hdg)
if self.verbose:
print('TURN: cur=(%.1f,%.1f) @ %.1f deg., targ=(%.1f,%.1f) @ %.1f deg, turn_angle=%.1f deg.' %
(cur_x, cur_y, cur_hdg*180/pi,
targ_x, targ_y, targ_hdg*180/pi, turn_angle*180/pi))
await self.robot.turn_in_place(cozmo.util.radians(turn_angle)).wait_for_completed()
continue
elif step.type == NavStep.FORWARD:
(targ_x, targ_y, targ_hdg) = step.params
dx = targ_x - cur_x
dy = targ_y - cur_y
course = atan2(dy,dx)
turn_angle = wrap_angle(course - cur_hdg)
if self.verbose:
print('FWD: cur=(%.1f,%.1f)@%.1f\N{degree sign} targ=(%.1f,%.1f)@%.1f\N{degree sign} turn=%.1f\N{degree sign}' %
(cur_x,cur_y,cur_hdg*180/pi,
targ_x,targ_y,targ_hdg*180/pi,turn_angle*180/pi),
end='')
sys.stdout.flush()
if abs(turn_angle) > self.max_turn:
turn_angle = self.max_turn if turn_angle > 0 else -self.max_turn
if self.verbose:
print(' ** TURN ANGLE SET TO', turn_angle*180/pi)
# *** HACK: skip node if it requires unreasonable turn
if abs(turn_angle) < 2*pi/180 or abs(wrap_angle(course-targ_hdg)) > pi/2:
if self.verbose:
print(' ** SKIPPED TURN **')
else:
await self.robot.turn_in_place(cozmo.util.radians(turn_angle)).wait_for_completed()
if not self.running: return
(cur_x,cur_y,cur_hdg) = self.robot.world.particle_filter.pose
dx = targ_x - cur_x
dy = targ_y - cur_y
dist = sqrt(dx**2 + dy**2)
if self.verbose:
print(' dist=%.1f' % dist)
await self.robot.drive_straight(distance_mm(dist),
speed_mmps(50)).wait_for_completed()
elif step.type == NavStep.ARC:
(targ_x, targ_y, targ_hdg, radius) = step.params
if self.verbose:
print('ARC: cur=(%.1f,%.1f) @ %.1f deg., targ=(%.1f,%.1f), targ_hdg=%.1f deg., radius=%.1f' %
(cur_x,cur_y,cur_hdg*180/pi,targ_x,targ_y,targ_hdg*180/pi,radius))
(actual_radius, actual_angle) = \
self.calculate_arc(cur_x, cur_y, cur_hdg, targ_x, targ_y)
if self.verbose:
print(' ** actual_radius =', actual_radius, ' actual_angle=', actual_angle*180/pi)
await self.drive_arc(actual_radius, math.degrees(abs(actual_angle)))
else:
raise ValueError('Invalid NavStep',step)
if self.verbose:
print('done executing')
self.post_completion()
"""
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,036
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/BackItUp.py
|
"""
The BackItUp demo illustrates the use of fork/join to launch
parallel actions and synchronize them again. The fork is performed
by the NullTrans transition with two destinations, while the join is
performed by the CompletionTrans transition with two sources.
Behavior: Cozmo backs up by 100 mm while simultaneously beeping. He
uses DriveForward instead of Forward to avoid conflict with the Say
action. When he's done backing up, he stops beeping and says 'Safety first'.
"""
from cozmo_fsm import *
class BackItUp(StateMachineProgram):
def setup(self):
"""
launcher: StateNode() =N=> {driver, speaker}
driver: Forward(-100,10)
speaker: Say('beep',duration_scalar=0.8,abort_on_stop=True) =C=> speaker
{driver,speaker} =C=> finisher: Say('Safety first!')
"""
# Code generated by genfsm on Mon Feb 17 03:10:16 2020:
launcher = StateNode() .set_name("launcher") .set_parent(self)
driver = Forward(-100,10) .set_name("driver") .set_parent(self)
speaker = Say('beep',duration_scalar=0.8,abort_on_stop=True) .set_name("speaker") .set_parent(self)
finisher = Say('Safety first!') .set_name("finisher") .set_parent(self)
nulltrans1 = NullTrans() .set_name("nulltrans1")
nulltrans1 .add_sources(launcher) .add_destinations(driver,speaker)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(speaker) .add_destinations(speaker)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(driver,speaker) .add_destinations(finisher)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,037
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/aruco.py
|
try: import cv2
except: pass
import math
from numpy import sqrt, arctan2, array, multiply
ARUCO_MARKER_SIZE = 44
class ArucoMarker(object):
def __init__(self, aruco_parent, marker_id, bbox, translation, rotation):
self.id = marker_id
self.id_string = 'Aruco-' + str(marker_id)
self.bbox = bbox
self.aruco_parent = aruco_parent
# OpenCV Pose information
self.opencv_translation = translation
self.opencv_rotation = (180/math.pi)*rotation
# Marker coordinates in robot's camera reference frame
self.camera_coords = (-translation[0], -translation[1], translation[2])
# Distance in the x-y plane; particle filter ignores height so don't include it
self.camera_distance = math.sqrt(translation[0]*translation[0] +
# translation[1]*translation[1] +
translation[2]*translation[2])
# Conversion to euler angles
self.euler_rotation = self.rotationMatrixToEulerAngles(
cv2.Rodrigues(rotation)[0])*(180/math.pi)
def __str__(self):
return "<ArucoMarker id=%d trans=(%d,%d,%d) rot=(%d,%d,%d) erot=(%d,%d,%d)>" % \
(self.id, *self.opencv_translation, *self.opencv_rotation, *self.euler_rotation)
def __repr__(self):
return self.__str__()
@staticmethod
def rotationMatrixToEulerAngles(R) :
sy = sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
singular = sy < 1e-6
if not singular:
x = arctan2(R[2,1] , R[2,2])
y = arctan2(-R[2,0], sy)
z = arctan2(R[1,0], R[0,0])
else:
x = arctan2(-R[1,2], R[1,1])
y = arctan2(-R[2,0], sy)
z = 0
return array([x, y, z])
class Aruco(object):
def __init__(self, robot, arucolibname, marker_size=ARUCO_MARKER_SIZE, disabled_ids=[]):
self.arucolibname = arucolibname
if arucolibname is not None:
self.aruco_lib = cv2.aruco.getPredefinedDictionary(arucolibname)
self.seen_marker_ids = []
self.seen_marker_objects = dict()
self.disabled_ids = disabled_ids # disable markers with high false detection rates
self.ids = []
self.corners = []
if robot.camera is None: return # robot is a SimRobot
# Added for pose estimation
self.marker_size = marker_size #these units will be pose est units!!
self.image_size = (320,240)
focal_len = robot.camera._config._focal_length
self.camera_matrix = \
array([[focal_len.x , 0, self.image_size[0]/2],
[0, -focal_len.y, self.image_size[1]/2],
[0, 0, 1]]).astype(float)
self.distortion_array = array([[0,0,0,0,0]]).astype(float)
def process_image(self,gray):
self.seen_marker_ids = []
self.seen_marker_objects = dict()
(self.corners,self.ids,_) = \
cv2.aruco.detectMarkers(gray, self.aruco_lib)
if self.ids is None: return
# Estimate poses
# Warning: OpenCV 3.2 estimate returns a pair; 3.3 returns a triplet
estimate = \
cv2.aruco.estimatePoseSingleMarkers(self.corners,
self.marker_size,
self.camera_matrix,
self.distortion_array)
self.rvecs = estimate[0]
self.tvecs = estimate[1]
for i in range(len(self.ids)):
id = int(self.ids[i][0])
if id in self.disabled_ids: continue
tvec = self.tvecs[i][0]
rvec = self.rvecs[i][0]
if rvec[2] > math.pi/2 or rvec[2] < -math.pi/2:
# can't see a marker facing away from us, so bogus
print('Marker rejected! id=', id, 'tvec=', tvec, 'rvec=', rvec)
continue
marker = ArucoMarker(self, id,
self.corners[i], self.tvecs[i][0], self.rvecs[i][0])
self.seen_marker_ids.append(marker.id)
self.seen_marker_objects[marker.id] = marker
def annotate(self, image, scale_factor):
scaled_corners = [ multiply(corner, scale_factor) for corner in self.corners ]
displayim = cv2.aruco.drawDetectedMarkers(image, scaled_corners, self.ids)
#add poses currently fails since image is already scaled. How to scale camMat?
#if(self.ids is not None):
# for i in range(len(self.ids)):
# displayim = cv2.aruco.drawAxis(displayim,self.cameraMatrix,
# self.distortionArray,self.rvecs[i],self.tvecs[i]*scale_factor,self.axisLength*scale_factor)
return displayim
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,038
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/cam_viewer.py
|
"""
OpenGL based CamViewer
"""
import numpy as np
import math
import random
import time
import cozmo
from cozmo.util import degrees, distance_mm, speed_mmps
try:
import cv2
from PIL import Image
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
pass
from . import opengl
from . import program
#For capturing images
global snapno, path
snapno = 0
path = 'snap/'
WINDOW = None
class CamViewer():
def __init__(self, robot, width=640, height=480,
windowName="Cozmo's World",
bgcolor=(0, 0, 0)):
self.robot = robot
self.width = width
self.height = height
self.aspect = self.width/self.height
self.windowName = windowName
self.bgcolor = bgcolor
self.scale = 1
self.show_axes = True
self.show_memory_map = False
def process_image(self):
raw = self.robot.world.latest_image.raw_image
curim = np.array(raw)
gray = cv2.cvtColor(curim,cv2.COLOR_BGR2GRAY)
running_fsm = program.running_fsm
# Aruco image processing
if running_fsm.aruco:
running_fsm.robot.world.aruco.process_image(gray)
# Other image processors can run here if the user supplies them.
running_fsm.user_image(curim,gray)
# Done with image processing
# Annotate and display image if requested
if running_fsm.force_annotation or running_fsm.cam_viewer is not None:
scale = running_fsm.annotated_scale_factor
# Apply Cozmo SDK annotations and rescale.
if running_fsm.annotate_sdk:
coz_ann = self.robot.world.latest_image.annotate_image(scale=scale)
annotated_im = np.array(coz_ann)
elif scale != 1:
shape = curim.shape
dsize = (scale*shape[1], scale*shape[0])
annotated_im = cv2.resize(curim, dsize)
else:
annotated_im = curim
# Aruco annotation
if running_fsm.aruco and \
len(running_fsm.robot.world.aruco.seen_marker_ids) > 0:
annotated_im = running_fsm.robot.world.aruco.annotate(annotated_im,scale)
# Other annotators can run here if the user supplies them.
annotated_im = running_fsm.user_annotate(annotated_im)
# Done with annotation
# Yellow viewer crosshairs
if running_fsm.viewer_crosshairs:
shape = annotated_im.shape
cv2.line(annotated_im, (int(shape[1]/2),0), (int(shape[1]/2),shape[0]), (0,255,255), 1)
cv2.line(annotated_im, (0,int(shape[0]/2)), (shape[1],int(shape[0]/2)), (0,255,255), 1)
image = annotated_im
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.width, self.height,0,GL_RGB, GL_UNSIGNED_BYTE, image)
glutPostRedisplay()
# ================ Window Setup ================
def window_creator(self):
global WINDOW
#glutInit(sys.argv)
WINDOW = opengl.create_window(
bytes(self.windowName, 'utf-8'), (self.width, self.height))
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(self.width, self.height)
glutInitWindowPosition(100, 100)
glClearColor(0.0, 0.0, 0.0, 1.0)
glutDisplayFunc(self.display)
glutReshapeFunc(self.reshape)
glutKeyboardFunc(self.keyPressed)
glutSpecialFunc(self.specialKeyPressed)
glutSpecialUpFunc(self.specialKeyUp)
def start(self): # Displays in background
if not WINDOW:
opengl.init()
opengl.CREATION_QUEUE.append(self.window_creator)
def display(self):
self.process_image()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glEnable(GL_TEXTURE_2D)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
# Set Projection Matrix
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, self.width, 0, self.height)
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glScalef(1.0, -1.0, 1.0)
glMatrixMode(GL_MODELVIEW)
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0)
glVertex2f(0.0, 0.0)
glTexCoord2f(1.0, 0.0)
glVertex2f(self.width, 0.0)
glTexCoord2f(1.0, 1.0)
glVertex2f(self.width, self.height)
glTexCoord2f(0.0, 1.0)
glVertex2f(0.0, self.height)
glEnd()
glFlush()
glutSwapBuffers()
def reshape(self, w, h):
if h == 0:
h = 1
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
nRange = 1.0
if w <= h:
glOrtho(-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange)
else:
glOrtho(-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def keyPressed(self, key, x, y):
if ord(key) == 27:
print("Use 'exit' to quit.")
#return
if key == b'c':
print("Taking a snap")
self.capture()
self.display()
def specialKeyPressed(self, key, x, y):
global leftorrightindicate, globthres
if key == GLUT_KEY_LEFT:
self.robot.drive_wheels(-100, 100)
leftorrightindicate = True
globthres=100
elif key == GLUT_KEY_RIGHT:
self.robot.drive_wheels(100, -100)
leftorrightindicate = True
globthres = 100
elif key == GLUT_KEY_UP:
self.robot.drive_wheels(200, 200)
leftorrightindicate = False
globthres = 100
elif key == GLUT_KEY_DOWN:
self.robot.drive_wheels(-200, -200)
leftorrightindicate = True
globthres = 100
glutPostRedisplay()
def specialKeyUp(self, key, x, y):
global leftorrightindicate, go_forward
self.robot.drive_wheels(0, 0)
leftorrightindicate = True
go_forward = GLUT_KEY_UP
glutPostRedisplay()
def capture(self, name='cozmo_snap'):
global snapno, path
if not os.path.exists(path):
os.makedirs(path)
image = np.array(self.robot.world.latest_image.raw_image)
Image.fromarray(image).save(path + '/' + name + str(snapno) + '.jpg')
snapno +=1
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,039
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/program.py
|
import asyncio
import functools
import inspect
import os
import time
import numpy
import numpy as np
try:
import cv2
ARUCO_DICT_4x4_100 = cv2.aruco.DICT_4X4_100
except:
ARUCO_DICT_4x4_100 = None
import cozmo
from cozmo.util import degrees, distance_mm, speed_mmps
from .evbase import EventRouter
from .base import StateNode
from .aruco import *
from .particle import *
from .cozmo_kin import *
from .particle_viewer import ParticleViewer
from .worldmap import WorldMap
from .rrt import RRT
from .path_viewer import PathViewer
from .worldmap_viewer import WorldMapViewer
from .cam_viewer import CamViewer
from .speech import SpeechListener, Thesaurus
from . import opengl
from . import custom_objs
from .perched import *
from .sharedmap import *
from .cam_viewer import CamViewer
running_fsm = None
charger_warned = False
class StateMachineProgram(StateNode):
def __init__(self,
kine_class = CozmoKinematics,
cam_viewer = True,
force_annotation = False, # set to True for annotation even without cam_viewer
annotate_sdk = True, # include SDK's own image annotations
annotated_scale_factor = 2, # set to 1 to avoid cost of resizing images
viewer_crosshairs = False, # set to True to draw viewer crosshairs
particle_filter = True,
landmark_test = SLAMSensorModel.is_solo_aruco_landmark,
particle_viewer = False,
particle_viewer_scale = 1.0,
aruco = True,
arucolibname = ARUCO_DICT_4x4_100,
aruco_disabled_ids = (17, 37),
aruco_marker_size = ARUCO_MARKER_SIZE,
perched_cameras = False,
world_map = None,
worldmap_viewer = False,
rrt = None,
path_viewer = False,
speech = False,
speech_debug = False,
thesaurus = Thesaurus(),
simple_cli_callback = None
):
super().__init__()
self.name = self.__class__.__name__.lower()
self.parent = None
self.simple_cli_callback = simple_cli_callback
if not hasattr(self.robot, 'erouter'):
self.robot.erouter = EventRouter()
self.robot.erouter.robot = self.robot
self.robot.erouter.start()
else:
self.robot.erouter.clear()
# Reset custom objects
cor = self.robot.world.undefine_all_custom_marker_objects()
if inspect.iscoroutine(cor):
asyncio.ensure_future(cor)
self.robot.loop.create_task(custom_objs.declare_objects(self.robot))
time.sleep(0.25) # need time for custom objects to be transmitted
self.kine_class = kine_class
self.cam_viewer = cam_viewer
self.viewer = None
self.annotate_sdk = annotate_sdk
self.force_annotation = force_annotation
self.annotated_scale_factor = annotated_scale_factor
self.viewer_crosshairs = viewer_crosshairs
self.particle_filter = particle_filter
self.landmark_test = landmark_test
self.particle_viewer = particle_viewer
self.particle_viewer_scale = particle_viewer_scale
self.picked_up_callback = self.robot_picked_up
self.put_down_handler = self.robot_put_down
self.aruco = aruco
self.aruco_marker_size = aruco_marker_size
if self.aruco:
self.robot.world.aruco = \
Aruco(self.robot, arucolibname, aruco_marker_size, aruco_disabled_ids)
self.perched_cameras = perched_cameras
if self.perched_cameras:
self.robot.world.perched = PerchedCameraThread(self.robot)
self.robot.aruco_id = -1
self.robot.use_shared_map = False
self.robot.world.server = ServerThread(self.robot)
self.robot.world.client = ClientThread(self.robot)
self.robot.world.is_server = True # Writes directly into perched.camera_pool
self.world_map = world_map
self.worldmap_viewer = worldmap_viewer
self.rrt = rrt
self.path_viewer = path_viewer
self.speech = speech
self.speech_debug = speech_debug
self.thesaurus = thesaurus
def start(self):
global running_fsm
running_fsm = self
# Create a particle filter
if not isinstance(self.particle_filter,ParticleFilter):
self.particle_filter = SLAMParticleFilter(self.robot, landmark_test=self.landmark_test)
elif isinstance(self.particle_filter,SLAMParticleFilter):
self.particle_filter.clear_landmarks()
pf = self.particle_filter
self.robot.world.particle_filter = pf
# Set up kinematics
self.robot.kine = self.kine_class(self.robot)
self.robot.was_picked_up = False
self.robot.carrying = None
self.robot.fetching = None
# robot.is_picked_up uses just the cliff detector, and can be fooled.
# robot.pose.rotation does not encode pitch or roll, only yaw.
# So use accelerometer data as our backup method.
self.robot.really_picked_up = \
(lambda robot :
(lambda :
robot.is_picked_up
or (not robot.is_moving
and (robot.accelerometer.z < 5000
or robot.accelerometer.z > 13000))))(self.robot)
# and (robot.accelerometer.z < 5000
# or robot.accelerometer.z > 10300))))(self.robot)
# World map and path planner
self.robot.enable_facial_expression_estimation(True)
self.robot.world.world_map = \
self.world_map or WorldMap(self.robot)
self.robot.world.world_map.clear()
self.robot.world.rrt = self.rrt or RRT(self.robot)
if self.simple_cli_callback:
self.make_cubes_available()
# Polling
self.set_polling_interval(0.025) # for kine and motion model update
# Launch viewers
if self.cam_viewer:
if self.cam_viewer is True:
self.cam_viewer = CamViewer(self.robot)
self.cam_viewer.start()
self.robot.world.cam_viewer = self.cam_viewer
if self.particle_viewer:
if self.particle_viewer is True:
self.particle_viewer = \
ParticleViewer(self.robot, scale=self.particle_viewer_scale)
self.particle_viewer.start()
self.robot.world.particle_viewer = self.particle_viewer
if self.path_viewer:
if self.path_viewer is True:
self.path_viewer = PathViewer(self.robot, self.robot.world.rrt)
else:
self.path_viewer.set_rrt(self.robot.world.rrt)
self.path_viewer.start()
self.robot.world.path_viewer = self.path_viewer
if self.worldmap_viewer:
if self.worldmap_viewer is True:
self.worldmap_viewer = WorldMapViewer(self.robot)
self.worldmap_viewer.start()
self.robot.world.worldmap_viewer = self.worldmap_viewer
# Request camera image and object recognition streams
self.robot.camera.image_stream_enabled = True
self.robot.world.add_event_handler(cozmo.world.EvtNewCameraImage,
self.process_image)
self.robot.world.add_event_handler(
cozmo.objects.EvtObjectObserved,
self.robot.world.world_map.handle_object_observed)
# Set up cube motion detection
cubes = self.robot.world.light_cubes
for i in cubes:
cubes[i].movement_start_time = None
self.robot.world.add_event_handler(
cozmo.objects.EvtObjectMovingStarted,
self.robot.world.world_map.handle_object_move_started)
self.robot.world.add_event_handler(
cozmo.objects.EvtObjectMovingStopped,
self.robot.world.world_map.handle_object_move_stopped)
# Start speech recognition if requested
if self.speech:
self.speech_listener = SpeechListener(self.robot,self.thesaurus,debug=self.speech_debug)
self.speech_listener.start()
# Call parent's start() to launch the state machine by invoking the start node.
super().start()
def make_cubes_available(self):
# Make worldmap cubes and charger accessible to simple_cli
cubes = self.robot.world.light_cubes
wc1 = wc2 = wc3 = wcharger = None
if 1 in cubes:
wc1 = self.robot.world.world_map.update_cube(cubes[1])
if 2 in cubes:
wc2 = self.robot.world.world_map.update_cube(cubes[2])
if 3 in cubes:
wc3 = self.robot.world.world_map.update_cube(cubes[3])
if self.robot.world.charger is not None:
wcharger = self.robot.world.world_map.update_charger()
self.simple_cli_callback(wc1, wc2, wc3, wcharger)
def robot_picked_up(self):
print('** Robot was picked up!', self.robot.accelerometer)
self.robot.stop_all_motors()
self.run_picked_up_handler(self)
def run_picked_up_handler(self,node):
"""Complex state machines use a picked_up_handler to abort the machine
gracefully, usually by posting a failure event from the parent."""
if node.running and hasattr(node,'picked_up_handler'):
node.picked_up_handler()
else:
for child in node.children.values():
self.run_picked_up_handler(child)
def robot_put_down(self):
print('** Robot was put down.')
pf = self.robot.world.particle_filter
pf.delocalize()
def stop(self):
super().stop()
self.robot.erouter.clear()
try:
self.robot.world.remove_event_handler(cozmo.world.EvtNewCameraImage,
self.process_image)
except: pass
def poll(self):
global charger_warned
# Invalidate cube pose if cube has been moving and isn't seen
move_duration_regular_threshold = 0.5 # seconds
move_duration_fetch_threshold = 1 # seconds
cubes = self.robot.world.light_cubes
now = None
for i in cubes:
cube = cubes[i]
if self.robot.carrying and self.robot.carrying.sdk_obj is cube:
continue
if cube.movement_start_time is not None and not cube.is_visible:
now = now or time.time()
if self.robot.fetching and self.robot.fetching.sdk_obj is cube:
threshold = move_duration_fetch_threshold
else:
threshold = move_duration_regular_threshold
if (now - cube.movement_start_time) > threshold:
cube_id = 'Cube-' + str(i)
wcube = self.robot.world.world_map.objects[cube_id]
print('Invalidating pose of', wcube)
wcube.pose_confidence = -1
cube.movement_start_time = None
if self.simple_cli_callback:
self.make_cubes_available()
# Update robot kinematic description
self.robot.kine.get_pose()
# Handle robot being picked up or put down
if self.robot.really_picked_up():
# robot is in the air
if self.robot.was_picked_up:
pass # we already knew that
else:
self.picked_up_callback()
else: # robot is on the ground
pf = self.robot.world.particle_filter
if pf:
if self.robot.was_picked_up:
self.put_down_handler()
else:
pf.move()
self.robot.was_picked_up = self.robot.really_picked_up()
# Handle robot being placed on the charger
if self.robot.is_on_charger:
if not charger_warned:
print("\n** On charger. Type robot.drive_off_charger_contacts() to enable motion.")
charger_warned = True
else:
charger_warned = False
def user_image(self,image,gray): pass
def user_annotate(self,image):
return image
def process_image(self,event,**kwargs):
if self.cam_viewer:
# if show cam_viewer, run the process_image under cam_viewer
pass
else:
curim = numpy.array(event.image.raw_image) #cozmo-raw image
gray = cv2.cvtColor(curim,cv2.COLOR_BGR2GRAY)
# Aruco image processing
if self.aruco:
self.robot.world.aruco.process_image(gray)
# Other image processors can run here if the user supplies them.
self.user_image(curim,gray)
# Done with image processing
# Annotate and display image if requested
if self.force_annotation or self.viewer is not None:
scale = self.annotated_scale_factor
# Apply Cozmo SDK annotations and rescale.
if self.annotate_sdk:
coz_ann = event.image.annotate_image(scale=scale)
annotated_im = numpy.array(coz_ann)
elif scale != 1:
shape = curim.shape
dsize = (scale*shape[1], scale*shape[0])
annotated_im = cv2.resize(curim, dsize)
else:
annotated_im = curim
# Aruco annotation
if self.aruco and \
len(self.robot.world.aruco.seen_marker_ids) > 0:
annotated_im = self.robot.world.aruco.annotate(annotated_im,scale)
# Other annotators can run here if the user supplies them.
annotated_im = self.user_annotate(annotated_im)
# Done with annotation
annotated_im = cv2.cvtColor(annotated_im,cv2.COLOR_RGB2BGR)
# Use this heartbeat signal to look for new landmarks
pf = self.robot.world.particle_filter
if pf and not self.robot.really_picked_up():
pf.look_for_new_landmarks()
# Finally update the world map
self.robot.world.world_map.update_map()
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,040
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/CV_Canny.py
|
"""
CV_Canny demonstrates image thresholding in OpenCV, and
independently, the Canny edge detector.
"""
import cv2
import numpy as np
from cozmo_fsm import *
class CV_Canny(StateMachineProgram):
def __init__(self):
super().__init__(aruco=False, particle_filter=False, cam_viewer=False,
annotate_sdk=False)
def start(self):
dummy = numpy.array([[0]], dtype='uint8')
super().start()
cv2.namedWindow('edges')
cv2.imshow('edges',dummy)
cv2.namedWindow('threshold')
cv2.imshow('threshold',dummy)
cv2.createTrackbar('thresh','threshold',0,255,lambda self: None)
cv2.setTrackbarPos('thresh', 'threshold', 100)
cv2.createTrackbar('thresh1','edges',0,255,lambda self: None)
cv2.createTrackbar('thresh2','edges',0,255,lambda self: None)
cv2.setTrackbarPos('thresh1', 'edges', 50)
cv2.setTrackbarPos('thresh2', 'edges', 150)
def user_image(self,image,gray):
cv2.waitKey(1)
# Thresholding
self.thresh = cv2.getTrackbarPos('thresh','threshold')
ret, self.im_thresh = cv2.threshold(gray, self.thresh, 255, cv2.THRESH_BINARY)
# Canny edge detection
self.thresh1 = cv2.getTrackbarPos('thresh1','edges')
self.thresh2 = cv2.getTrackbarPos('thresh2','edges')
self.im_edges = cv2.Canny(gray, self.thresh1, self.thresh2, apertureSize=3)
cv2.imshow('threshold',self.im_thresh)
cv2.imshow('edges',self.im_edges)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,041
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/particle_viewer.py
|
"""
Particle filter display in OpenGL.
"""
try:
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
pass
import time
import math
from math import sin, cos, pi, atan2, sqrt
import array
import numpy as np
import platform
import cozmo
from cozmo.util import distance_mm, speed_mmps, degrees
from . import opengl
from .worldmap import ArucoMarkerObj
REDISPLAY = True # toggle this to suspend constant redisplay
WINDOW = None
help_text = """
Particle viewer commands:
w/a/s/d Drive robot +/- 10 mm or turn +/- 22.5 degrees
W/A/S/D Drive robot +/- 40 mm or turn +/- 90 degrees
i/k/I/K Head up/down 5 or 20 degrees
u/j/U/J Lift up/down 5 or max degrees
e Evaluate particles using current sensor info
r Resample particles (evaluates first)
z Reset particle positions (randomize, or all 0 for SLAM)
c Clear landmarks (for SLAM)
o Show objects
p Show best particle
arrows Translate the view up/down/left/right
Home Center the view (zero translation)
< Zoom in
> Zoom out
$ Toggle redisplay (for debugging)
v Toggle verbosity
V Display weight variance
h Print this help text
"""
help_text_mac = """
Particle viewer commands:
option + w/a/s/d Drive robot +/- 10 mm or turn +/- 22.5 degrees
option + W/A/S/D Drive robot +/- 40 mm or turn +/- 90 degrees
option + i/k Head up/down 5 degrees
option + I/K Head up/down 20 degrees
option + e Evaluate particles using current sensor info
option + r Resample particles (evaluates first)
option + z Reset particle positions (randomize, or all 0 for SLAM)
option + c Clear landmarks (for SLAM)
option + o Show objects
option + p Show best particle
arrows Translate the view up/down/left/right
fn + left-arrow Center the view (zero translation)
option + < Zoom in
option + > Zoom out
option + $ Toggle redisplay (for debugging)
option + v Toggle verbosity
option + V Display weight variance
option + h Print this help text
"""
class ParticleViewer():
def __init__(self, robot,
width=512, height=512, scale=0.64,
windowName = "particle viewer",
bgcolor = (0,0,0)):
self.robot=robot
self.width = width
self.height = height
self.bgcolor = bgcolor
self.aspect = self.width/self.height
self.translation = [200., 0.] # Translation in mm
self.scale = scale
self.verbose = False
self.windowName = windowName
def window_creator(self):
global WINDOW
WINDOW = opengl.create_window(bytes(self.windowName, 'utf-8'), (self.width,self.height))
glutDisplayFunc(self.display)
glutReshapeFunc(self.reshape)
glutKeyboardFunc(self.keyPressed)
glutSpecialFunc(self.specialKeyPressed)
glViewport(0,0,self.width,self.height)
glClearColor(*self.bgcolor, 0)
# Enable transparency
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
def start(self): # Displays in background
if not WINDOW:
opengl.init()
opengl.CREATION_QUEUE.append(self.window_creator)
if platform.system() == 'Darwin':
print("Type 'option' + 'h' in the particle viewer window for help.")
else:
print("Type 'h' in the particle viewer window for help.")
def draw_rectangle(self, center, size=(10,10),
angle=0, color=(1,1,1), fill=True):
# Default to solid color and square window
if len(color)==3:
color = (*color,1)
# Calculate vertices as offsets from center
w = size[0]/2; h = size[1]/2
v1 = (-w,-h); v2 = (w,-h); v3 = (w,h); v4 = (-w,h)
# Draw the rectangle
glPushMatrix()
if fill:
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)
else:
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE)
glColor4f(color[0],color[1],color[2],color[3])
glTranslatef(*center,0)
glRotatef(angle,0,0,1)
glBegin(GL_QUADS)
glVertex2f(*v1)
glVertex2f(*v2)
glVertex2f(*v3)
glVertex2f(*v4)
glEnd()
glPopMatrix()
def draw_triangle(self, center, height=1, angle=0, tip_offset=0,
color=(1,1,1), fill=True):
half = height / 2
aspect = 3/5
if len(color) == 3:
color = (*color,1)
glPushMatrix()
if fill:
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)
else:
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE)
glColor4f(*color)
glTranslatef(*center,0)
glRotatef(angle,0,0,1)
glTranslatef(tip_offset,0,0)
glBegin(GL_TRIANGLES)
glVertex2f( half, 0.)
glVertex2f(-half, -aspect*half)
glVertex2f(-half, aspect*half)
glEnd()
glPopMatrix()
def draw_ellipse(self, center, scale, orient=0, color=(1,1,1), fill=False):
if len(color) == 3:
color = (*color,1)
glPushMatrix()
glTranslatef(*center,0)
glRotatef(orient,0,0,1)
glColor4f(*color)
if fill:
glBegin(GL_TRIANGLE_FAN)
glVertex2f(0,0)
else:
glBegin(GL_LINE_LOOP)
for t in range(0,361):
theta = t/180*pi
glVertex2f(scale[0]*cos(theta), scale[1]*sin(theta))
glEnd()
glPopMatrix()
def draw_wedge(self, center, radius, orient, span, color=(1,1,1), fill=True):
if len(color) == 3:
color = (*color,1)
glPushMatrix()
glTranslatef(*center,0)
glRotatef(orient,0,0,1)
glColor4f(*color)
if fill:
glBegin(GL_TRIANGLE_FAN)
else:
glBegin(GL_LINE_LOOP)
glVertex2f(0,0)
for t in range(round(-span/2), round(span/2)):
theta = t/180*pi
glVertex2f(radius*cos(theta), radius*sin(theta))
glEnd()
glPopMatrix()
def draw_landmarks(self):
landmarks = self.robot.world.particle_filter.sensor_model.landmarks.copy()
if not landmarks: return
# Extract values as quickly as we can because
# dictionary can change while we're iterating.
objs = self.robot.world.world_map.objects.copy()
arucos = [(marker.id, (np.array([[marker.x], [marker.y]]), marker.theta, None))
for marker in objs.values()
if isinstance(marker, ArucoMarkerObj)]
all_specs = list(landmarks.items()) + \
[marker for marker in arucos if marker[0] not in landmarks]
for (id,specs) in all_specs:
if not isinstance(id,str):
raise TypeError("Landmark id's must be strings: %r" % id)
color = None
if id.startswith('Aruco-'):
label = id[6:]
num = int(label)
seen = num in self.robot.world.aruco.seen_marker_ids
elif id.startswith('Cube-'):
label = id[5:]
num = int(label)
cube = self.robot.world.light_cubes[num]
seen = cube.is_visible
if seen:
color = (0.5, 0.3, 1, 0.75)
else:
color = (0, 0, 0.5, 0.75)
elif id.startswith('Wall-'):
label = 'W' + id[id.find('-')+1:]
try:
seen = self.robot.world.world_map.objects[id].is_visible
except:
seen = False
if seen:
color = (1, 0.5, 0.3, 0.75)
else:
color = (0.5, 0, 0, 0.75)
elif id.startswith('Video'):
seen = self.robot.aruco_id in self.robot.world.perched.camera_pool and \
id in self.robot.world.perched.camera_pool[self.robot.aruco_id]
label = id
if color is None:
if seen:
color = (0.5, 1, 0.3, 0.75)
else:
color = (0, 0.5, 0, 0.75)
if isinstance(specs, cozmo.util.Pose):
self.draw_landmark_from_pose(id, specs, label, color)
else:
self.draw_landmark_from_particle(id, specs, label, color)
def draw_landmark_from_pose(self, id, specs, label, color):
coords = (specs.position.x, specs.position.y)
angle = specs.rotation.angle_z.degrees
if id.startswith('LightCube'):
size = (44,44)
angle_adjust = 0
else: # Aruco
size = (20,50)
angle_adjust = 90
glPushMatrix()
glColor4f(*color)
self.draw_rectangle(coords, size=size, angle=angle, color=color)
glColor4f(0., 0., 0., 1.)
glTranslatef(*coords,0)
glRotatef(angle + angle_adjust, 0., 0., 1.)
glTranslatef(3.-7*len(label), -5., 0.)
glScalef(0.1,0.1,0.1)
for char in label:
glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, ord(char))
glPopMatrix()
def draw_landmark_from_particle(self, id, specs, label, color):
(lm_mu, lm_orient, lm_sigma) = specs
coords = (lm_mu[0,0], lm_mu[1,0])
glPushMatrix()
glColor4f(*color)
if id.startswith('Cube'):
size = (44,44)
angle_offset = -90
translate = 0
elif id.startswith('Wall'):
try:
wall = self.robot.world.world_map.objects[id]
except KeyError: # race condition: not in worldmap yet
return
size = (20, wall.length)
angle_offset = 90
translate = 0
else: # Aruco
size = (20,50)
angle_offset = 90
translate = 15
if id.startswith('Video'):
self.draw_triangle(coords, height=75, angle=lm_orient[1]*(180/pi),
color=color, fill=True)
glColor4f(0., 0., 0., 1.)
glTranslatef(*coords,0)
glRotatef(lm_orient[1]*(180/pi)+angle_offset, 0., 0., 1.)
else:
glTranslatef(*coords,0.)
glRotatef(lm_orient*180/pi, 0., 0., 1.)
glTranslatef(translate, 0., 0.)
self.draw_rectangle([0,0], size=size, angle=0, color=color)
#self.draw_rectangle(coords, size=size, angle=lm_orient*(180/pi), color=color)
glColor4f(0., 0., 0., 1.)
#glTranslatef(*coords,0)
#glRotatef(lm_orient*(180/pi)+angle_offset, 0., 0., 1.)
glRotatef(angle_offset, 0., 0., 1.)
glTranslatef(3.0-7*len(label), -5.0, 0.0)
glScalef(0.1, 0.1, 0.1)
for char in label:
glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, ord(char))
glPopMatrix()
ellipse_color = (color[1], color[2], color[0], 1)
self.draw_particle_landmark_ellipse(lm_mu, lm_sigma, ellipse_color)
def draw_particle_landmark_ellipse(self, coords, sigma, color):
if sigma is None: return # Arucos that are not solo landmarks
(w,v) = np.linalg.eigh(sigma[0:2,0:2])
alpha = atan2(v[1,0],v[0,0])
self.draw_ellipse(coords, abs(w)**0.5, alpha*(180/pi), color=color)
def display(self):
global REDISPLAY
if not REDISPLAY: return
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
w = self.width / 2
glOrtho(-w, w, -w, w, 1, -1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glRotatef(90,0,0,1)
glScalef(self.scale, self.scale, self.scale)
glTranslatef(-self.translation[0], -self.translation[1], 0.)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Draw the particles
for p in self.robot.world.particle_filter.particles:
pscale = 1 - p.weight
color=(1,pscale,pscale)
self.draw_triangle((p.x,p.y), height=10, angle=math.degrees(p.theta),
color=color, fill=True)
# Draw the robot at the best particle location
(rx,ry,theta) = self.robot.world.particle_filter.pose
(xy_var, theta_var) = self.robot.world.particle_filter.variance
hdg = math.degrees(theta)
self.draw_triangle((rx,ry), height=100, angle=hdg, tip_offset=-10,
color=(1,1,0,0.7))
# Draw the error ellipse and heading error wedge
(w,v) = np.linalg.eigh(xy_var)
alpha = atan2(v[1,0],v[0,0])
self.draw_ellipse((rx,ry), abs(w)**0.5, alpha/pi*180, color=(0,1,1))
self.draw_wedge((rx,ry), 75, hdg, max(5, sqrt(theta_var)*360),
color=(0,1,1,0.4))
# Draw the landmarks last, so they go on top of the particles
self.draw_landmarks()
glutSwapBuffers()
def reshape(self,width,height):
glViewport(0,0,width,height)
self.width = width
self.height = height
self.aspect = self.width/self.height
self.display()
glutPostRedisplay()
def report_variance(self,pf):
weights = np.empty(pf.num_particles)
for i in range(pf.num_particles):
weights[i] = pf.particles[i].weight
weights.sort()
var = np.var(weights)
print('weights: min = %3.3e max = %3.3e med = %3.3e variance = %3.3e' %
(weights[0], weights[-1], weights[pf.num_particles//2], var))
(xy_var, theta_var) = pf.variance
print ('xy_var=', xy_var, ' theta_var=', theta_var)
def report_pose(self):
(x,y,theta) = self.robot.world.particle_filter.pose
hdg = math.degrees(theta)
if self.verbose:
print('Pose = (%5.1f, %5.1f) @ %3d deg.' % (x, y, hdg))
async def forward(self,distance):
handle = self.robot.drive_straight(distance_mm(distance), speed_mmps(50),
in_parallel=True,
should_play_anim=False)
await handle.wait_for_completed()
pf = self.robot.world.particle_filter
self.robot.loop.call_later(0.1, pf.look_for_new_landmarks)
self.report_pose()
async def turn(self,angle):
handle = self.robot.turn_in_place(degrees(angle), in_parallel=True)
await handle.wait_for_completed()
pf = self.robot.world.particle_filter
self.robot.loop.call_later(0.1, pf.look_for_new_landmarks)
self.report_pose()
async def look(self,angle):
handle = self.robot.set_head_angle(degrees(angle), in_parallel=True)
await handle.wait_for_completed()
pf = self.robot.world.particle_filter
self.robot.loop.call_later(0.1, pf.look_for_new_landmarks)
self.report_pose()
async def lift_to(self,angle):
min_theta = cozmo.robot.MIN_LIFT_ANGLE.degrees
max_theta = cozmo.robot.MAX_LIFT_ANGLE.degrees
angle_range = max_theta - min_theta
raw_height = (angle - min_theta) / angle_range
height = min(1.0, max(0.0, raw_height))
handle = self.robot.set_lift_height(height, in_parallel=True)
await handle.wait_for_completed()
pf = self.robot.world.particle_filter
self.robot.loop.call_later(0.1, pf.look_for_new_landmarks)
self.report_pose()
def keyPressed(self,key,mouseX,mouseY):
pf = self.robot.world.particle_filter
translate_wasd = 10 # millimeters
translate_WASD = 40
rotate_wasd = 22.5 # degrees
rotate_WASD = 90
global particles
if key == b'e': # evaluate
pf.sensor_model.evaluate(pf.particles,force=True)
pf.update_weights()
elif key == b'r': # resample
pf.sensor_model.evaluate(pf.particles,force=True)
pf.update_weights()
pf.resample()
elif key == b'w': # forward
self.robot.loop.create_task(self.forward(translate_wasd))
elif key == b'W': # forward
self.robot.loop.create_task(self.forward(translate_WASD))
elif key == b's': # back
self.robot.loop.create_task(self.forward(-translate_wasd))
elif key == b'S': # back
self.robot.loop.create_task(self.forward(-translate_WASD))
elif key == b'a': # left
self.robot.loop.create_task(self.turn(rotate_wasd))
elif key == b'A': # left
self.robot.loop.create_task(self.turn(rotate_WASD))
elif key == b'd': # right
self.robot.loop.create_task(self.turn(-rotate_wasd))
elif key == b'D': # right
self.robot.loop.create_task(self.turn(-rotate_WASD))
elif key == b'i': # head up
ang = self.robot.head_angle.degrees + 5
self.robot.loop.create_task(self.look(ang))
elif key == b'k': # head down
ang = self.robot.head_angle.degrees - 5
self.robot.loop.create_task(self.look(ang))
elif key == b'I': # head up
ang = self.robot.head_angle.degrees + 20
self.robot.loop.create_task(self.look(ang))
elif key == b'K': # head down
ang = self.robot.head_angle.degrees - 20
self.robot.loop.create_task(self.look(ang))
elif key == b'u': # lift up
ang = self.robot.lift_angle.degrees + 5
self.robot.loop.create_task(self.lift_to(ang))
elif key == b'j': # lift down
ang = self.robot.lift_angle.degrees - 5
self.robot.loop.create_task(self.lift_to(ang))
elif key == b'U': # lift up
ang = self.robot.lift_angle.degrees + 60
self.robot.loop.create_task(self.lift_to(ang))
elif key == b'J': # lift down
ang = self.robot.lift_angle.degrees - 60
self.robot.loop.create_task(self.lift_to(ang))
elif key == b'z': # delocalize
pf.delocalize()
#pf.initializer.initialize(self.robot)
elif key == b'Z': # randomize
pf.increase_variance()
elif key == b'c': # clear landmarks
pf.clear_landmarks()
print('Landmarks cleared.')
elif key == b'o': # show objects
self.robot.world.world_map.show_objects()
elif key == b'p': # show particle
self.robot.world.particle_filter.show_particle()
elif key == b'l': # show landmarks
self.robot.world.particle_filter.show_landmarks()
elif key == b'V': # display weight variance
self.report_variance(pf)
elif key == b'<': # zoom in
self.scale *= 1.25
self.print_display_params()
return
elif key == b'>': # zoom out
self.scale /= 1.25
self.print_display_params()
return
elif key == b'v': # toggle verbose mode
self.verbose = not self.verbose
self.report_pose()
return
elif key == b'h': # print help
self.print_help()
return
elif key == b'$': # toggle redisplay for debugging
global REDISPLAY
REDISPLAY = not REDISPLAY
print('Redisplay ',('off','on')[REDISPLAY],'.',sep='')
elif key == b'q': #kill window
global WINDOW
glutDestroyWindow(WINDOW)
glutLeaveMainLoop()
glutPostRedisplay()
self.report_pose()
def specialKeyPressed(self, key, mouseX, mouseY):
pf = self.robot.world.particle_filter
# arrow keys for translation
incr = 25.0 # millimeters
if key == GLUT_KEY_UP:
self.translation[0] += incr / self.scale
elif key == GLUT_KEY_DOWN:
self.translation[0] -= incr / self.scale
elif key == GLUT_KEY_LEFT:
self.translation[1] += incr / self.scale
elif key == GLUT_KEY_RIGHT:
self.translation[1] -= incr / self.scale
elif key == GLUT_KEY_HOME:
self.translation = [0., 0.]
self.print_display_params()
glutPostRedisplay()
def print_display_params(self):
if self.verbose:
print('scale=%.2f translation=[%.1f, %.1f]' %
(self.scale, *self.translation))
glutPostRedisplay()
def print_help(self):
if platform.system() == 'Darwin':
print(help_text_mac)
else:
print(help_text)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,042
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/__init__.py
|
"""
Example demos for the cozmo_fsm finite state machine package
"""
from . import BackItUp
from . import Boo
from . import Greet
from . import Look5
from . import Nested
from . import TapSpeak
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,043
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/opengl.py
|
"""
Common code for OpenGL window management
"""
try:
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
pass
import time
from threading import Thread # for backgrounding window
INIT_DONE = False
MAIN_LOOP_LAUNCHED = False
# Maintain a registry of display functions for our windows
WINDOW_REGISTRY = []
# List of window creation requests that need to be satisfied
CREATION_QUEUE = []
def init():
global INIT_DONE, robot
if not INIT_DONE:
INIT_DONE = True
glutInit()
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH)
# Killing window should not directly kill main program
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION)
launch_event_loop()
def create_window(name,size=(500,500)):
global WINDOW_REGISTRY
glutInitWindowSize(*size)
w = glutCreateWindow(name)
#print('request creation of window',w)
WINDOW_REGISTRY.append(w)
return w
def event_loop():
while True:
for window in WINDOW_REGISTRY:
glutSetWindow(window)
glutPostRedisplay()
glutMainLoopEvent()
process_requests()
time.sleep(0.1)
def process_requests():
global CREATION_QUEUE
# Process any requests for new windows
queue = CREATION_QUEUE
CREATION_QUEUE = []
for req in queue:
req() # invoke the window creator
def launch_event_loop():
global MAIN_LOOP_LAUNCHED
if MAIN_LOOP_LAUNCHED: return
MAIN_LOOP_LAUNCHED = True
print('launching opengl event loop')
thread = Thread(target=event_loop)
thread.daemon = True #ending fg program will kill bg program
thread.start()
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,044
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/rrt.py
|
from math import pi, sin, cos, inf, asin, atan2, nan, isnan, ceil
import numpy as np
import random
import time
import math
import cozmo_fsm.geometry
from .geometry import wrap_angle
from .rrt_shapes import *
from .cozmo_kin import center_of_rotation_offset
from .worldmap import WallObj, wall_marker_dict, RoomObj, LightCubeObj, MapFaceObj
from .worldmap import CustomCubeObj, ChargerObj, CustomMarkerObj, ChipObj, RobotForeignObj
# *** TODO: Collision checking needs to use opposite headings
# for treeB nodes because robot is asymmetric.
#---------------- RRTNode ----------------
class RRTNode():
def __init__(self, parent=None, x=0, y=0, q=0, radius=None):
self.parent = parent
self.x = x
self.y = y
self.q = q
self.radius = radius # arc radius
def copy(self):
return RRTNode(self.parent, self.x, self.y, self.q, self.radius)
def __repr__(self):
if isnan(self.q):
return '<RRTNode (%.1f,%.1f)>' % (self.x, self.y)
elif not self.parent:
return '<RRTNode (%.1f,%.1f)@%d deg>' % \
(self.x, self.y, round(self.q/pi*180))
elif self.radius is None:
return '<RRTNode line to (%.1f,%.1f)@%d deg>' % \
(self.x, self.y, round(self.q/pi*180))
else:
return '<RRTNode arc to (%.1f,%.1f)@%d deg, rad=%d>' % \
(self.x, self.y, round(self.q/pi*180), self.radius)
#---------------- RRT Path Planner ----------------
class RRTException(Exception):
def __str__(self):
return self.__repr__()
class StartCollides(RRTException): pass
class GoalCollides(RRTException): pass
class MaxIterations(RRTException): pass
class GoalUnreachable(RRTException): pass
class NotLocalized(RRTException): pass
class RRT():
DEFAULT_MAX_ITER = 2000
def __init__(self, robot=None, robot_parts=None, bbox=None,
max_iter=DEFAULT_MAX_ITER, step_size=10, arc_radius=40,
xy_tolsq=90, q_tol=5*pi/180,
obstacles=[], auto_obstacles=True,
bounds=(range(-500,500), range(-500,500))):
self.robot = robot
self.max_iter = max_iter
self.step_size = step_size
self.max_turn = pi
self.arc_radius = arc_radius
self.xy_tolsq = xy_tolsq
self.q_tol = q_tol
self.robot_parts = robot_parts if robot_parts is not None else self.make_robot_parts(robot)
self.bounds = bounds
self.obstacles = obstacles
self.auto_obstacles = auto_obstacles
self.treeA = []
self.treeB = []
self.start = None
self.goal = None
self.bbox = bbox
self.path = []
self.draw_path = []
self.grid_display = None # *** HACK to display wavefront grid
self.text = None # *** HACK to display unreachable text
REACHED = 'reached'
COLLISION = 'collision'
INTERPOLATE = 'interpolate'
def set_obstacles(self,obstacles):
self.obstacles = obstacles
def nearest_node(self, tree, target_node):
best_distance = inf
closest_node = None
x = target_node.x
y = target_node.y
for this_node in tree:
distx = this_node.x - x
disty = this_node.y - y
distsq = distx*distx + disty*disty
if distsq < best_distance:
best_distance = distsq
closest_node = this_node
return closest_node
def random_node(self):
return RRTNode(x=random.choice(self.bounds[0]),
y=random.choice(self.bounds[1]))
def extend(self, tree, target):
nearest = self.nearest_node(tree, target)
status, new_node = self.interpolate(nearest, target)
if status is not self.COLLISION:
tree.append(new_node)
#time.sleep(0.01) # *** FOR ANIMATION PURPOSES
return (status, new_node)
def interpolate(self, node, target):
dx = target.x - node.x
dy = target.y - node.y
distsq = dx*dx + dy*dy
q = atan2(dy,dx)
dq = wrap_angle(q - node.q)
if abs(dq) > self.max_turn:
dq = self.max_turn if dq > 0 else -self.max_turn
q = wrap_angle(node.q + dq)
if abs(dq) >= self.q_tol:
# Must be able to turn to the new heading without colliding
turn_dir = +1 if dq >= 0 else -1
q_inc = turn_dir * self.q_tol
while abs(q_inc - dq) > self.q_tol:
if self.collides(RRTNode(x=node.x, y=node.y, q=node.q+q_inc)):
return (self.COLLISION, None)
q_inc += turn_dir * self.q_tol
if distsq < self.xy_tolsq:
return (self.REACHED, RRTNode(parent=node, x=target.x, y=target.y,q=q))
xstep = self.step_size * cos(q)
ystep = self.step_size * sin(q)
new_node = RRTNode(parent=node, x=node.x+xstep, y=node.y+ystep, q=q)
if self.collides(new_node):
return (self.COLLISION, None)
else:
return (self.INTERPOLATE, new_node)
def robot_parts_to_node(self,node):
parts = []
for part in self.robot_parts:
tmat = geometry.aboutZ(part.orient)
tmat = geometry.translate(part.center[0,0], part.center[1,0]).dot(tmat)
tmat = geometry.aboutZ(node.q).dot(tmat)
tmat = geometry.translate(node.x, node.y).dot(tmat)
this_part = part.instantiate(tmat)
parts.append(this_part)
return parts
def collides(self, node):
for part in self.robot_parts_to_node(node):
for obstacle in self.obstacles:
if part.collides(obstacle):
return obstacle
return False
def all_colliders(self, node):
result = []
for part in self.robot_parts_to_node(node):
for obstacle in self.obstacles:
if part.collides(obstacle):
result.append(part)
return result
def plan_push_chip(self, start, goal, max_turn=20*(pi/180), arc_radius=40.):
return self.plan_path(start, goal, max_turn, arc_radius)
def plan_path(self, start, goal, max_turn=pi, arc_radius=40):
self.max_turn = max_turn
self.arc_radius = arc_radius
if self.auto_obstacles:
obstacle_inflation = 5
doorway_adjustment = 20 # widen doorways for RRT
self.generate_obstacles(obstacle_inflation, doorway_adjustment)
self.start = start
self.goal = goal
self.target_heading = goal.q
self.compute_bounding_box()
# Check for StartCollides
collider = self.collides(start)
if collider:
raise StartCollides(start,collider,collider.obstacle_id)
# Set up treeA with start node
treeA = [start.copy()]
self.treeA = treeA
# Set up treeB with goal node(s)
if not isnan(self.target_heading):
offset_x = goal.x + center_of_rotation_offset * cos(goal.q)
offset_y = goal.y + center_of_rotation_offset * sin(goal.q)
offset_goal = RRTNode(x=offset_x, y=offset_y, q=goal.q)
collider = self.collides(offset_goal)
if collider:
raise GoalCollides(goal,collider,collider.obstacle_id)
treeB = [offset_goal]
self.treeB = treeB
else: # target_heading is nan
treeB = [goal.copy()]
self.treeB = treeB
temp_goal = goal.copy()
offset_goal = goal.copy()
for theta in range(0,360,10):
q = theta/180*pi
step = max(self.step_size, abs(center_of_rotation_offset))
temp_goal.x = goal.x + step*cos(q)
temp_goal.y = goal.y + step*sin(q)
temp_goal.q = wrap_angle(q+pi)
collider = self.collides(temp_goal)
if collider: continue
offset_goal.x = temp_goal.x + center_of_rotation_offset * cos(q)
offset_goal.y = temp_goal.y + center_of_rotation_offset * sin(q)
offset_goal.q = temp_goal.q
collider = self.collides(offset_goal)
if not collider:
treeB.append(RRTNode(parent=treeB[0], x=temp_goal.x, y=temp_goal.y, q=temp_goal.q))
if len(treeB) == 1:
raise GoalCollides(goal,collider,collider.obstacle_id)
# Set bounds for search area
self.compute_world_bounds(start,goal)
# Grow the RRT until trees meet or max_iter exceeded
swapped = False
for i in range(self.max_iter):
r = self.random_node()
(status, new_node) = self.extend(treeA, r)
if status is not self.COLLISION:
(status, new_node) = self.extend(treeB, treeA[-1])
if status is self.REACHED:
break
(treeA, treeB) = (treeB, treeA)
swapped = not swapped
# Search terminated. Check for success.
if swapped:
(treeA, treeB) = (treeB, treeA)
if status is self.REACHED:
return self.get_path(treeA, treeB)
else:
raise MaxIterations(self.max_iter)
def compute_world_bounds(self,start,goal):
xmin = min(start.x, goal.x)
xmax = max(start.x, goal.x)
ymin = min(start.y, goal.y)
ymax = max(start.y, goal.y)
for obst in self.obstacles:
if isinstance(obst,Circle):
xmin = obst.center[0] - obst.radius
xmax = obst.center[0] + obst.radius
ymin = obst.center[1] - obst.radius
ymax = obst.center[1] + obst.radius
else:
xmin = min(xmin, np.min(obst.vertices[0]))
xmax = max(xmax, np.max(obst.vertices[0]))
ymin = min(ymin, np.min(obst.vertices[1]))
ymax = max(ymax, np.max(obst.vertices[1]))
xmin = xmin - 500
xmax = xmax + 500
ymin = ymin - 500
ymax = ymax + 500
self.bounds = (range(int(xmin), int(xmax)), range(int(ymin), int(ymax)))
def get_path(self, treeA, treeB):
nodeA = treeA[-1]
pathA = [nodeA.copy()]
while nodeA.parent is not None:
nodeA = nodeA.parent
pathA.append(nodeA.copy())
pathA.reverse()
# treeB was built backwards from the goal, so headings
# need to be reversed
nodeB = treeB[-1]
prev_heading = wrap_angle(nodeB.q + pi)
if nodeB.parent is None:
pathB = [nodeB.copy()]
else:
pathB = []
while nodeB.parent is not None:
nodeB = nodeB.parent
(nodeB.q, prev_heading) = (prev_heading, wrap_angle(nodeB.q+pi))
pathB.append(nodeB.copy())
(pathA,pathB) = self.join_paths(pathA,pathB)
self.path = pathA + pathB
self.smooth_path()
target_q = self.target_heading
if not isnan(target_q):
# Last nodes turn to desired final heading
last = self.path[-1]
goal = RRTNode(parent=last, x=self.goal.x, y=self.goal.y,
q=target_q, radius=0)
self.path.append(goal)
return (treeA, treeB, self.path)
def join_paths(self,pathA,pathB):
turn_angle = wrap_angle(pathB[0].q - pathA[-1].q)
if abs(turn_angle) <= self.max_turn:
return (pathA,pathB)
print('*** JOIN PATHS EXCEEDED MAX TURN ANGLE: ', turn_angle*180/pi)
return (pathA,pathB)
def smooth_path(self):
"""Smooth a path by picking random subsequences and replacing
them with a direct link if there is no collision."""
smoothed_path = self.path
for _ in range(0,len(smoothed_path)):
L = len(smoothed_path)
if L <= 2: break
i = random.randrange(0,L-2)
cur_x = smoothed_path[i].x
cur_y = smoothed_path[i].y
cur_q = smoothed_path[i].q
j = random.randrange(i+2, L)
if j < L-1 and smoothed_path[j+1].radius != None:
continue # j is parent node of an arc segment: don't touch
dx = smoothed_path[j].x - cur_x
dy = smoothed_path[j].y - cur_y
new_q = atan2(dy,dx)
dist = sqrt(dx**2 + dy**2)
turn_angle = wrap_angle(new_q - cur_q)
if abs(turn_angle) <= self.max_turn:
result = self.try_linear_smooth(smoothed_path,i,j,cur_x,cur_y,new_q,dist)
else:
result = self.try_arc_smooth(smoothed_path,i,j,cur_x,cur_y,cur_q)
smoothed_path = result or smoothed_path
self.path = smoothed_path
def try_linear_smooth(self,smoothed_path,i,j,cur_x,cur_y,new_q,dist):
step_x = self.step_size * cos(new_q)
step_y = self.step_size * sin(new_q)
traveled = 0
while traveled < dist:
traveled += self.step_size
cur_x += step_x
cur_y += step_y
if self.collides(RRTNode(None, cur_x, cur_y, new_q)):
return None
# Since we're arriving at node j via a different heading than
# before, see if we need to add an arc to get us to node k=j+1
node_i = smoothed_path[i]
end_spec = self.calculate_end(smoothed_path, node_i, new_q, j)
if end_spec is None:
return None
# no collision, so snip out nodes i+1 ... j-1
# print('linear: stitching','%d:'%i,smoothed_path[i],'to %d:'%j,smoothed_path[j])
if not end_spec:
smoothed_path[j].parent = smoothed_path[i]
smoothed_path[j].q = new_q
smoothed_path[j].radius = None
smoothed_path = smoothed_path[:i+1] + smoothed_path[j:]
else:
(next_node,turn_node) = end_spec
smoothed_path[j+1].parent = turn_node
smoothed_path = smoothed_path[:i+1] + \
[next_node, turn_node] + \
smoothed_path[j+1:]
return smoothed_path
def try_arc_smooth(self,smoothed_path,i,j,cur_x,cur_y,cur_q):
if j == i+2 and smoothed_path[i+1].radius != None:
return None # would be replacing an arc node with itself
arc_spec = self.calculate_arc(smoothed_path[i], smoothed_path[j])
if arc_spec is None:
return None
(tang_x, tang_y, tang_q, radius) = arc_spec
ni = smoothed_path[i]
turn_node1 = RRTNode(ni, tang_x, tang_y, tang_q, radius=radius)
# Since we're arriving at node j via a different heading than
# before, see if we need to add an arc at the end to allow us
# to smoothly proceed to node k=j+1
end_spec = self.calculate_end(smoothed_path, turn_node1, tang_q, j)
if end_spec is None:
return None
# no collision, so snip out nodes i+1 ... j-1 and insert new node(s)
# print('arc: stitching','%d:'%i,smoothed_path[i],'to %d:'%j,smoothed_path[j])
if not end_spec:
smoothed_path[j].parent = turn_node1
smoothed_path[j].q = tang_q
smoothed_path[j].radius = None
smoothed_path = smoothed_path[:i+1] + [turn_node1] + smoothed_path[j:]
else:
(next_node, turn_node2) = end_spec
smoothed_path[j+1].parent = turn_node2
smoothed_path = smoothed_path[:i+1] + \
[turn_node1, next_node, turn_node2] + \
smoothed_path[j+1:]
return smoothed_path
def calculate_arc(self, node_i, node_j):
# Compute arc node parameters to get us on a heading toward node_j.
cur_x = node_i.x
cur_y = node_i.y
cur_q = node_i.q
dest_x = node_j.x
dest_y = node_j.y
direct_turn_angle = wrap_angle(atan2(dest_y-cur_y, dest_x-cur_x) - cur_q)
# find center of arc we'll be moving along
dir = +1 if direct_turn_angle >=0 else -1
cx = cur_x + self.arc_radius * cos(cur_q + dir*pi/2)
cy = cur_y + self.arc_radius * sin(cur_q + dir*pi/2)
dx = cx - dest_x
dy = cy - dest_y
center_dist = sqrt(dx*dx + dy*dy)
if center_dist < self.arc_radius: # turn would be too wide: punt
return None
# tangent points on arc: outer tangent formula from Wikipedia with r=0
gamma = atan2(dy, dx)
beta = asin(self.arc_radius / center_dist)
alpha1 = gamma + beta
tang_x1 = cx + self.arc_radius * cos(alpha1 + pi/2)
tang_y1 = cy + self.arc_radius * sin(alpha1 + pi/2)
tang_q1 = (atan2(tang_y1-cy, tang_x1-cx) + dir*pi/2)
turn1 = tang_q1 - cur_q
if dir * turn1 < 0:
turn1 += dir * 2 * pi
alpha2 = gamma - beta
tang_x2 = cx + self.arc_radius * cos(alpha2 - pi/2)
tang_y2 = cy + self.arc_radius * sin(alpha2 - pi/2)
tang_q2 = (atan2(tang_y2-cy, tang_x2-cx) + dir*pi/2)
turn2 = tang_q2 - cur_q
if dir * turn2 < 0:
turn2 += dir * 2 * pi
# Correct tangent point has shortest turn.
if abs(turn1) < abs(turn2):
(tang_x,tang_y,tang_q,turn) = (tang_x1,tang_y1,tang_q1,turn1)
else:
(tang_x,tang_y,tang_q,turn) = (tang_x2,tang_y2,tang_q2,turn2)
# Interpolate along the arc and check for collision.
q_traveled = 0
while abs(q_traveled) < abs(turn):
cur_x = cx + self.arc_radius * cos(cur_q + q_traveled)
cur_y = cy + self.arc_radius * sin(cur_q + q_traveled)
if self.collides(RRTNode(None, cur_x, cur_y, cur_q+q_traveled)):
return None
q_traveled += dir * self.q_tol
# Now interpolate from the tangent point to the target.
cur_x = tang_x
cur_y = tang_y
dx = dest_x - cur_x
dy = dest_y - cur_y
new_q = atan2(dy, dx)
dist = sqrt(dx*dx + dy*dy)
step_x = self.step_size * cos(new_q)
step_y = self.step_size * sin(new_q)
traveled = 0
while traveled < dist:
traveled += self.step_size
cur_x += step_x
cur_y += step_y
if self.collides(RRTNode(None, cur_x, cur_y, new_q)):
return None
# No collision, so arc is good.
return (tang_x, tang_y, tang_q, dir*self.arc_radius)
def calculate_end(self, smoothed_path, parent, new_q, j):
# Return False if arc not needed, None if arc not possible,
# or pair of new nodes if arc is required.
if j == len(smoothed_path)-1:
return False
node_j = smoothed_path[j]
node_k = smoothed_path[j+1]
next_turn = wrap_angle(node_k.q - new_q)
if abs(next_turn) <= self.max_turn:
return False
dist = sqrt((node_k.x-node_j.x)**2 + (node_k.y-node_j.y)**2)
if False and dist < self.arc_radius:
return None
next_x = node_j.x - self.arc_radius * cos(new_q)
next_y = node_j.y - self.arc_radius * sin(new_q)
next_node = RRTNode(parent, next_x, next_y, new_q)
arc_spec = self.calculate_arc(next_node, node_k)
if arc_spec is None:
return None
(tang_x, tang_y, tang_q, radius) = arc_spec
turn_node = RRTNode(next_node, tang_x, tang_y, tang_q, radius=radius)
return (next_node, turn_node)
def coords_to_path(self, coords_pairs):
"""
Transform a path of coordinates pairs to RRTNodes.
"""
path = []
for (x,y) in coords_pairs:
node = RRTNode(x=x, y=y, q=math.nan)
if path:
node.parent = path[-1]
path[-1].q = atan2(y - path[-1].y, x - path[-1].x)
path.append(node)
return path
#---------------- Obstacle Representation ----------------
def generate_obstacles(self, obstacle_inflation=0, wall_inflation=0, doorway_adjustment=0):
self.robot.world.world_map.update_map()
obstacles = []
for obj in self.robot.world.world_map.objects.values():
if not obj.is_obstacle: continue
if self.robot.carrying is obj: continue
if obj.pose_confidence < 0: continue
if 'unseen' in obj.__dict__ and obj.unseen: continue
if isinstance(obj, WallObj):
obstacles = obstacles + \
self.generate_wall_obstacles(obj, wall_inflation, doorway_adjustment)
elif isinstance(obj, (LightCubeObj,CustomCubeObj,ChargerObj)):
obstacles.append(self.generate_cube_obstacle(obj, obstacle_inflation))
elif isinstance(obj, CustomMarkerObj):
obstacles.append(self.generate_marker_obstacle(obj,obstacle_inflation))
elif isinstance(obj, ChipObj):
obstacles.append(self.generate_chip_obstacle(obj,obstacle_inflation))
elif isinstance(obj, RobotForeignObj):
obstacles.append(self.generate_foreign_obstacle(obj))
self.obstacles = obstacles
@staticmethod
def generate_wall_obstacles(wall, wall_inflation, doorway_adjustment):
wall_spec = wall_marker_dict[wall.spec_id]
wall_half_length = wall.length / 2
widths = []
edges = [ [0, -wall_half_length - wall_inflation, 0., 1.] ]
last_x = -wall_half_length - wall_inflation
for (door_center, door_width) in wall_spec.doorways:
door_width += doorway_adjustment # widen doorways for RRT, narrow for WaveFront
left_edge = door_center - door_width/2 - wall_half_length
edges.append([0., left_edge, 0., 1.])
widths.append(left_edge - last_x)
right_edge = door_center + door_width/2 - wall_half_length
edges.append([0., right_edge, 0., 1.])
last_x = right_edge
edges.append([0., wall_half_length + wall_inflation, 0., 1.])
widths.append(wall_half_length + wall_inflation - last_x)
edges = np.array(edges).T
edges = geometry.aboutZ(wall.theta).dot(edges)
edges = geometry.translate(wall.x,wall.y).dot(edges)
obst = []
for i in range(0,len(widths)):
center = edges[:,2*i:2*i+2].mean(1).reshape(4,1)
dimensions=(4.0+2*wall_inflation, widths[i])
r = Rectangle(center=center,
dimensions=dimensions,
orient=wall.theta )
r.obstacle_id = wall.id
obst.append(r)
return obst
@staticmethod
def generate_cube_obstacle(obj, obstacle_inflation=0):
r = Rectangle(center=geometry.point(obj.x, obj.y),
dimensions=[obj.size[0]+2*obstacle_inflation, obj.size[1]+2*obstacle_inflation],
orient=obj.theta)
r.obstacle_id = obj.id
return r
@staticmethod
def generate_marker_obstacle(obj, obstacle_inflation=0):
sx,sy,sz = obj.size
r = Rectangle(center=geometry.point(obj.x+sx/2, obj.y),
dimensions=(sx+2*obstacle_inflation,sy+2*obstacle_inflation),
orient=obj.theta)
r.obstacle_id = obj.id
return r
@staticmethod
def generate_room_obstacle(obj):
"""Rooms aren't really obstacles, but this is used by PathPlanner to encode goal locations."""
r = Polygon(vertices=obj.points)
r.obstacle_id = obj.id
return r
@staticmethod
def generate_chip_obstacle(obj, obstacle_inflation=0):
r = Circle(center=geometry.point(obj.x,obj.y),
radius=obj.radius+obstacle_inflation)
r.obstacle_id = obj.id
return r
@staticmethod
def generate_foreign_obstacle(obj):
r = Rectangle(center=geometry.point(obj.x, obj.y),
dimensions=(obj.size[0:2]),
orient=obj.theta)
r.obstacle_id = obj.id
return r
@staticmethod
def generate_mapFace_obstacle(obj, obstacle_inflation=0):
r = Rectangle(center=geometry.point(obj.x,obj.y),
dimensions=[obj.size[0]+2*obstacle_inflation, obj.size[1]+2*obstacle_inflation])
r.obstacle_id = obj.id
return r
@staticmethod
def make_robot_parts(robot):
result = []
for joint in robot.kine.joints.values():
if joint.collision_model:
tmat = robot.kine.link_to_base(joint)
robot_obst = joint.collision_model.instantiate(tmat)
result.append(robot_obst)
return result
def compute_bounding_box(self):
xmin = self.robot.world.particle_filter.pose[0]
ymin = self.robot.world.particle_filter.pose[1]
xmax = xmin
ymax = ymin
objs = self.robot.world.world_map.objects.values()
# Rooms aren't obstacles, so include them separately.
rooms = [obj for obj in objs if isinstance(obj,RoomObj)]
# Cubes and markers may not be obstacles if they are goal locations, so include them again.
goals = [ obj for obj in objs if
(isinstance(obj,(LightCubeObj,CustomMarkerObj)) and obj.pose_confidence >= 0) or
isinstance(obj,MapFaceObj) ]
for obj in self.obstacles + rooms + goals:
((x0,y0),(x1,y1)) = obj.get_bounding_box()
xmin = min(xmin, x0)
ymin = min(ymin, y0)
xmax = max(xmax, x1)
ymax = max(ymax, y1)
self.bbox = ((xmin,ymin), (xmax,ymax))
return self.bbox
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,045
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/kine.py
|
import math
import numpy as np
from . import geometry
from . import rrt_shapes
class Joint():
def __init__(self, name, parent=None, type='fixed', getter=(lambda:0),
description='A kinematic joint',
qmin=-math.inf, qmax=math.inf,
d=0, theta=0, r=0, alpha=0,
collision_model=None, ctransform=geometry.identity()):
self.name = name
self.parent = parent
self.type = type
if type == 'fixed':
self.apply_q = self.fixed
elif type == 'revolute':
self.apply_q = self.revolute
elif type == 'prismatic':
self.apply_q = self.prismatic
elif type == 'world':
self.apply_q = self.world_joint
else:
raise ValueError("Type must be 'fixed', 'revolute', 'prismatic', or 'world'.")
self.getter = getter
self.description = description
self.children = []
self.d = d
self.theta = theta
self.r = r
self.alpha = alpha
self.children = []
self.collision_model = collision_model
self.q = 0
self.qmin = qmin
self.qmax = qmax
self.parent_link_to_this_joint = geometry.dh_matrix(-d,-theta,-r,-alpha)
self.this_joint_to_parent_link = np.linalg.inv(self.parent_link_to_this_joint)
self.solver = None
def __repr__(self):
if self.type == 'fixed':
qval = 'fixed'
elif isinstance(self.q, (int,float)):
qval = "q=%.2f deg." % (self.q*180/math.pi)
else:
qval = ("q=%s" % repr(self.q))
return "<Joint '%s' %s>" % (self.name, qval)
def this_joint_to_this_link(self):
"The link moves by q in the joint's reference frame."
return self.apply_q()
def this_link_to_this_joint(self):
return np.linalg.inv(self.this_joint_to_this_link())
def revolute(self):
return geometry.aboutZ(-self.q)
def prismatic(self):
return geometry.translate(0.,0.,-self.q)
def fixed(self):
return geometry.identity()
def world_joint(self):
return geometry.translate(self.q[0],self.q[1]).dot(geometry.aboutZ(self.q[2]))
class Kinematics():
def __init__(self,joint_list,robot):
self.joints = dict()
for j in joint_list:
self.joints[j.name] = j
if j.parent:
j.parent.children.append(j)
self.base = self.joints[joint_list[0].name]
self.robot = robot
robot.kine = self
self.get_pose()
def joint_to_base(self,joint):
if isinstance(joint,str):
joint = self.joints[joint]
Tinv = geometry.identity()
j = joint
while j is not self.base and j.parent is not None:
Tinv = j.parent.this_link_to_this_joint().dot(
j.this_joint_to_parent_link.dot(Tinv)
)
j = j.parent
if j:
return Tinv
else:
raise Exception('Joint %s has no path to base frame' % joint)
def base_to_joint(self,joint):
return np.linalg.inv(self.joint_to_base(joint))
def joint_to_joint(self,joint1,joint2):
return self.base_to_joint(joint2).dot(self.joint_to_base(joint1))
def link_to_base(self,joint):
if isinstance(joint,str):
joint = self.joints[joint]
return self.joint_to_base(joint).dot(joint.this_link_to_this_joint())
def base_to_link(self,joint):
return np.linalg.inv(self.link_to_base(joint))
def link_to_link(self,joint1,joint2):
return self.base_to_link(joint2).dot(self.link_to_base(joint1))
def get_pose(self):
for j in self.joints.values():
j.q = j.getter()
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,046
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/custom_objs.py
|
import cozmo
from cozmo.objects import CustomObject, CustomObjectMarkers, CustomObjectTypes
custom_marker_types = []
custom_container_types = []
custom_cube_types = []
async def declare_objects(robot):
"""
await robot.world.define_custom_box(
CustomObjectTypes.CustomType00,
CustomObjectMarkers.Hexagons4, # front
CustomObjectMarkers.Triangles5, # back
CustomObjectMarkers.Circles2, # top
CustomObjectMarkers.Diamonds3, # bottom
CustomObjectMarkers.Circles4, # left
CustomObjectMarkers.Diamonds5, # right
50, 20, 1, # depth, width, height
40, 40, # marker width and height
True) # is_unique
return
"""
global custom_marker_types, custom_cube_types
decl_marker = robot.world.define_custom_wall
custom_marker_types = [
CustomObjectTypes.CustomType00,
CustomObjectTypes.CustomType01,
CustomObjectTypes.CustomType02,
CustomObjectTypes.CustomType03
]
await decl_marker(CustomObjectTypes.CustomType00,
CustomObjectMarkers.Circles2,
40, 40, 40, 40, True)
await decl_marker(CustomObjectTypes.CustomType01,
CustomObjectMarkers.Triangles2,
40, 40, 40, 40, True)
await decl_marker(CustomObjectTypes.CustomType02,
CustomObjectMarkers.Diamonds2,
40, 40, 40, 40, True)
await decl_marker(CustomObjectTypes.CustomType03,
CustomObjectMarkers.Hexagons2,
40, 40, 40, 40, True)
# Markers for containers
custom_container_types = [
CustomObjectTypes.CustomType04,
CustomObjectTypes.CustomType05
]
await decl_marker(CustomObjectTypes.CustomType04,
CustomObjectMarkers.Circles3,
40, 40, 40, 40, False)
await decl_marker(CustomObjectTypes.CustomType05,
CustomObjectMarkers.Triangles3,
40, 40, 40, 40, False)
# Markers for cubes
decl_cube = robot.world.define_custom_cube
custom_cube_types = [
CustomObjectTypes.CustomType10,
CustomObjectTypes.CustomType11,
CustomObjectTypes.CustomType12,
CustomObjectTypes.CustomType13,
CustomObjectTypes.CustomType14,
CustomObjectTypes.CustomType15
]
await decl_cube(CustomObjectTypes.CustomType10,
CustomObjectMarkers.Circles5,
50, 40, 40, True)
await decl_cube(CustomObjectTypes.CustomType11,
CustomObjectMarkers.Diamonds5,
50, 40, 40, True)
await decl_cube(CustomObjectTypes.CustomType12,
CustomObjectMarkers.Hexagons5,
50, 40, 40, True)
await decl_cube(CustomObjectTypes.CustomType13,
CustomObjectMarkers.Triangles4,
50, 40, 40, True)
await decl_cube(CustomObjectTypes.CustomType14,
CustomObjectMarkers.Circles4,
50, 40, 40, True)
await decl_cube(CustomObjectTypes.CustomType15,
CustomObjectMarkers.Diamonds4,
50, 40, 40, True)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,047
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/doorpass.py
|
from cozmo.util import Pose
from numpy import matrix, tan, arctan2
from math import sin, cos, atan2, pi, sqrt
try: from cv2 import Rodrigues
except: pass
from .nodes import *
from .transitions import *
from .geometry import wrap_angle
from .pilot0 import *
from .worldmap import WallObj, DoorwayObj
from time import sleep
class DoorPass(StateNode):
"""Pass through a doorway. Assumes the doorway is nearby and unobstructed."""
OUTER_GATE_DISTANCE = 150 # mm
INNER_GATE_DISTANCE = 70 # mm
def __init__(self, door=None):
self.door = door
super().__init__()
def start(self, event=None):
door = self.door
if isinstance(event,DataEvent):
door = event.data
if isinstance(door, int):
door ='Doorway-%d' % door
if isinstance(door, str):
doorway = self.robot.world.world_map.objects.get(door)
elif isinstance(door, DoorwayObj):
doorway = door
else:
doorway = None
if isinstance(doorway, DoorwayObj):
self.object = doorway
else:
print("Error in DoorPass: no doorway named %s" % repr(door))
raise ValueError(door,doorway)
super().start(event)
@staticmethod
def calculate_gate(start_point, door, offset):
"""Returns closest gate point (gx, gy)"""
(rx,ry) = start_point
dx = door.x
dy = door.y
dtheta = door.theta
pt1x = dx + offset * cos(dtheta)
pt1y = dy + offset * sin(dtheta)
pt2x = dx + offset * cos(dtheta+pi)
pt2y = dy + offset * sin(dtheta+pi)
dist1sq = (pt1x-rx)**2 + (pt1y-ry)**2
dist2sq = (pt2x-rx)**2 + (pt2y-ry)**2
if dist1sq < dist2sq:
return (pt1x, pt1y, wrap_angle(dtheta+pi))
else:
return (pt2x, pt2y, dtheta)
class AdjustLiftHeight(SetLiftHeight):
# TODO: If lift is high, push it higher (we're carrying something).
# If lift isn't high, drop it to zero
def start(self, event=None):
self.height = 0
super().start(event)
class AwayFromCollide(Forward):
def start(self, event=None):
# super().start(event)
if isinstance(event,DataEvent):
startNode = event.data[0]
collideObj = event.data[1]
(rx, ry, rtheta) = self.robot.world.particle_filter.pose_estimate()
cx, cy = collideObj.center[0,0],collideObj.center[1,0]
ctheta = atan2(cy-ry, cx-rx)
delta_angle = wrap_angle(ctheta - rtheta)
delta_angle = delta_angle/pi*180
if -90 < delta_angle and delta_angle < 90:
self.distance = distance_mm(-40)
else:
self.distance = distance_mm(40)
self.speed = speed_mmps(50)
super().start(event)
else:
raise ValueError('DataEvent to AwayFromCollide must be a StartCollides.args', event.data)
self.post_failure()
class TurnToGate(Turn):
"""Turn to the approach gate, or post success if we're already there."""
def __init__(self,offset):
self.offset = offset
super().__init__(speed=Angle(radians=2.0))
def start(self,event=None):
(rx, ry, rtheta) = self.robot.world.particle_filter.pose_estimate()
(gate_x, gate_y, _) = DoorPass.calculate_gate((rx,ry), self.parent.object, self.offset)
bearing = atan2(gate_y-ry, gate_x-rx)
turn = wrap_angle(bearing - rtheta)
print('^^ TurnToGate: gate=(%.1f, %.1f) offset=%.1f rtheta=%.1f bearing=%.1f turn=%.1f' %
(gate_x, gate_y, self.offset, rtheta*180/pi, bearing*180/pi, turn*180/pi))
if False and abs(turn) < 0.1:
self.angle = Angle(0)
super().start(event)
self.post_success()
else:
self.angle = Angle(radians=turn)
super().start(event)
class ForwardToGate(Forward):
"""Travel forward to reach the approach gate."""
def __init__(self,offset):
self.offset = offset
super().__init__()
def start(self,event=None):
(rx, ry, rtheta) = self.robot.world.particle_filter.pose_estimate()
(gate_x, gate_y, _) = DoorPass.calculate_gate((rx,ry), self.parent.object, self.offset)
dist = sqrt((gate_x-rx)**2 + (gate_y-ry)**2)
self.distance = distance_mm(dist)
self.speed = speed_mmps(50)
super().start(event)
class TurnToMarker(Turn):
"""Use camera image and native pose to center the door marker."""
def start(self,event=None):
marker_ids = self.parent.object.marker_ids
marker = self.robot.world.aruco.seen_marker_objects.get(marker_ids[0], None) or \
self.robot.world.aruco.seen_marker_objects.get(marker_ids[1], None)
if not marker:
self.angle = Angle(0)
super().start(event)
print("TurnToMarker failed to find marker %s or %s!" % marker_ids)
self.post_failure()
return
else:
print('TurnToMarker saw marker', marker)
sensor_dist = marker.camera_distance
sensor_bearing = atan2(marker.camera_coords[0],
marker.camera_coords[2])
x = self.robot.pose.position.x
y = self.robot.pose.position.y
theta = self.robot.pose.rotation.angle_z.radians
direction = theta + sensor_bearing
dx = sensor_dist * cos(direction)
dy = sensor_dist * sin(direction)
turn = wrap_angle(atan2(dy,dx) - self.robot.pose.rotation.angle_z.radians)
if abs(turn) < 0.5*pi/180:
self.angle = Angle(0)
else:
self.angle = Angle(radians=turn)
print("TurnToMarker %s turning by %.1f degrees" % (self.name, self.angle.degrees))
super().start(event)
class CheckCarrying(SetLiftHeight):
def __init__(self):
super().__init__()
def start(self,event=None):
if self.robot.carrying:
self.height = 0.4 if self.robot.lift_ratio > 0.5 else 1
super().start(event)
class DriveThrough(Forward):
"""Travel forward to drive through the gate."""
def __init__(self):
super().__init__()
def start(self,event=None):
(rx, ry, rtheta) = self.robot.world.particle_filter.pose_estimate()
(gate_x, gate_y, gate_theta) = DoorPass.calculate_gate((rx,ry), self.parent.object, 5)
dist = sqrt((gate_x-rx)**2 + (gate_y-ry)**2)
offset = 120
delta_theta = wrap_angle(rtheta-(gate_theta+pi/2))
delta_dist = abs(offset/sin(delta_theta))
dist += delta_dist
self.distance = distance_mm(dist)
self.speed = speed_mmps(50)
super().start(event)
def setup(self):
# droplift: self.AdjustLiftHeight() =N=>
# SetHeadAngle(0) =T(0.2)=> check_start # Time for vision to process
#
# check_start: PilotCheckStartDetail()
# check_start =S=> turn_to_gate1
# check_start =D=> away_from_collide
# check_start =F=> Forward(-80) =C=> check_start2
#
# check_start2: PilotCheckStartDetail()
# check_start2 =S=> turn_to_gate1
# check_start2 =D=> away_from_collide2
# check_start2 =F=> ParentFails()
#
# check_start3: PilotCheckStart()
# check_start3 =S=> turn_to_gate1
# check_start3 =F=> ParentFails()
#
# turn_to_gate1: self.TurnToGate(DoorPass.OUTER_GATE_DISTANCE) =C=>
# StateNode() =T(0.2)=> forward_to_gate1
#
# away_from_collide: self.AwayFromCollide() =C=> StateNode() =T(0.2)=> check_start2
# away_from_collide =F=> check_start2
#
# away_from_collide2: self.AwayFromCollide() =C=> StateNode() =T(0.2)=> check_start3
# away_from_collide2 =F=> check_start3
#
# forward_to_gate1: self.ForwardToGate(DoorPass.OUTER_GATE_DISTANCE) =C=>
# StateNode() =T(0.2)=> {look_up, turn_to_gate2}
#
# # If we're carrying a cube, we lower the lift so we can see
# look_up: SetHeadAngle(35)
#
# turn_to_gate2: self.TurnToGate(DoorPass.INNER_GATE_DISTANCE) =C=>
# StateNode() =T(0.2)=> self.CheckCarrying() =C=> turn_to_marker1
#
# turn_to_marker1: self.TurnToMarker()
# turn_to_marker1 =C=> marker_forward1
# turn_to_marker1 =F=> marker_forward1
#
# marker_forward1: self.ForwardToGate(DoorPass.INNER_GATE_DISTANCE) =C=>
# SetHeadAngle(40) =C=> StateNode() =T(0.2)=> turn_to_marker2
#
# turn_to_marker2: self.TurnToMarker()
# turn_to_marker2 =C=> marker_forward2
# turn_to_marker2 =F=> marker_forward2
#
# marker_forward2: StateNode() =T(0.2)=> {lower_head, through_door}
#
# lower_head: SetHeadAngle(0)
#
# through_door: self.DriveThrough()
#
# {lower_head, through_door} =C=> self.CheckCarrying() =C=> ParentCompletes()
#
# Code generated by genfsm on Sat Feb 25 01:50:55 2023:
droplift = self.AdjustLiftHeight() .set_name("droplift") .set_parent(self)
setheadangle1 = SetHeadAngle(0) .set_name("setheadangle1") .set_parent(self)
check_start = PilotCheckStartDetail() .set_name("check_start") .set_parent(self)
forward1 = Forward(-80) .set_name("forward1") .set_parent(self)
check_start2 = PilotCheckStartDetail() .set_name("check_start2") .set_parent(self)
parentfails1 = ParentFails() .set_name("parentfails1") .set_parent(self)
check_start3 = PilotCheckStart() .set_name("check_start3") .set_parent(self)
parentfails2 = ParentFails() .set_name("parentfails2") .set_parent(self)
turn_to_gate1 = self.TurnToGate(DoorPass.OUTER_GATE_DISTANCE) .set_name("turn_to_gate1") .set_parent(self)
statenode1 = StateNode() .set_name("statenode1") .set_parent(self)
away_from_collide = self.AwayFromCollide() .set_name("away_from_collide") .set_parent(self)
statenode2 = StateNode() .set_name("statenode2") .set_parent(self)
away_from_collide2 = self.AwayFromCollide() .set_name("away_from_collide2") .set_parent(self)
statenode3 = StateNode() .set_name("statenode3") .set_parent(self)
forward_to_gate1 = self.ForwardToGate(DoorPass.OUTER_GATE_DISTANCE) .set_name("forward_to_gate1") .set_parent(self)
statenode4 = StateNode() .set_name("statenode4") .set_parent(self)
look_up = SetHeadAngle(35) .set_name("look_up") .set_parent(self)
turn_to_gate2 = self.TurnToGate(DoorPass.INNER_GATE_DISTANCE) .set_name("turn_to_gate2") .set_parent(self)
statenode5 = StateNode() .set_name("statenode5") .set_parent(self)
checkcarrying1 = self.CheckCarrying() .set_name("checkcarrying1") .set_parent(self)
turn_to_marker1 = self.TurnToMarker() .set_name("turn_to_marker1") .set_parent(self)
marker_forward1 = self.ForwardToGate(DoorPass.INNER_GATE_DISTANCE) .set_name("marker_forward1") .set_parent(self)
setheadangle2 = SetHeadAngle(40) .set_name("setheadangle2") .set_parent(self)
statenode6 = StateNode() .set_name("statenode6") .set_parent(self)
turn_to_marker2 = self.TurnToMarker() .set_name("turn_to_marker2") .set_parent(self)
marker_forward2 = StateNode() .set_name("marker_forward2") .set_parent(self)
lower_head = SetHeadAngle(0) .set_name("lower_head") .set_parent(self)
through_door = self.DriveThrough() .set_name("through_door") .set_parent(self)
checkcarrying2 = self.CheckCarrying() .set_name("checkcarrying2") .set_parent(self)
parentcompletes1 = ParentCompletes() .set_name("parentcompletes1") .set_parent(self)
nulltrans1 = NullTrans() .set_name("nulltrans1")
nulltrans1 .add_sources(droplift) .add_destinations(setheadangle1)
timertrans1 = TimerTrans(0.2) .set_name("timertrans1")
timertrans1 .add_sources(setheadangle1) .add_destinations(check_start)
successtrans1 = SuccessTrans() .set_name("successtrans1")
successtrans1 .add_sources(check_start) .add_destinations(turn_to_gate1)
datatrans1 = DataTrans() .set_name("datatrans1")
datatrans1 .add_sources(check_start) .add_destinations(away_from_collide)
failuretrans1 = FailureTrans() .set_name("failuretrans1")
failuretrans1 .add_sources(check_start) .add_destinations(forward1)
completiontrans1 = CompletionTrans() .set_name("completiontrans1")
completiontrans1 .add_sources(forward1) .add_destinations(check_start2)
successtrans2 = SuccessTrans() .set_name("successtrans2")
successtrans2 .add_sources(check_start2) .add_destinations(turn_to_gate1)
datatrans2 = DataTrans() .set_name("datatrans2")
datatrans2 .add_sources(check_start2) .add_destinations(away_from_collide2)
failuretrans2 = FailureTrans() .set_name("failuretrans2")
failuretrans2 .add_sources(check_start2) .add_destinations(parentfails1)
successtrans3 = SuccessTrans() .set_name("successtrans3")
successtrans3 .add_sources(check_start3) .add_destinations(turn_to_gate1)
failuretrans3 = FailureTrans() .set_name("failuretrans3")
failuretrans3 .add_sources(check_start3) .add_destinations(parentfails2)
completiontrans2 = CompletionTrans() .set_name("completiontrans2")
completiontrans2 .add_sources(turn_to_gate1) .add_destinations(statenode1)
timertrans2 = TimerTrans(0.2) .set_name("timertrans2")
timertrans2 .add_sources(statenode1) .add_destinations(forward_to_gate1)
completiontrans3 = CompletionTrans() .set_name("completiontrans3")
completiontrans3 .add_sources(away_from_collide) .add_destinations(statenode2)
timertrans3 = TimerTrans(0.2) .set_name("timertrans3")
timertrans3 .add_sources(statenode2) .add_destinations(check_start2)
failuretrans4 = FailureTrans() .set_name("failuretrans4")
failuretrans4 .add_sources(away_from_collide) .add_destinations(check_start2)
completiontrans4 = CompletionTrans() .set_name("completiontrans4")
completiontrans4 .add_sources(away_from_collide2) .add_destinations(statenode3)
timertrans4 = TimerTrans(0.2) .set_name("timertrans4")
timertrans4 .add_sources(statenode3) .add_destinations(check_start3)
failuretrans5 = FailureTrans() .set_name("failuretrans5")
failuretrans5 .add_sources(away_from_collide2) .add_destinations(check_start3)
completiontrans5 = CompletionTrans() .set_name("completiontrans5")
completiontrans5 .add_sources(forward_to_gate1) .add_destinations(statenode4)
timertrans5 = TimerTrans(0.2) .set_name("timertrans5")
timertrans5 .add_sources(statenode4) .add_destinations(look_up,turn_to_gate2)
completiontrans6 = CompletionTrans() .set_name("completiontrans6")
completiontrans6 .add_sources(turn_to_gate2) .add_destinations(statenode5)
timertrans6 = TimerTrans(0.2) .set_name("timertrans6")
timertrans6 .add_sources(statenode5) .add_destinations(checkcarrying1)
completiontrans7 = CompletionTrans() .set_name("completiontrans7")
completiontrans7 .add_sources(checkcarrying1) .add_destinations(turn_to_marker1)
completiontrans8 = CompletionTrans() .set_name("completiontrans8")
completiontrans8 .add_sources(turn_to_marker1) .add_destinations(marker_forward1)
failuretrans6 = FailureTrans() .set_name("failuretrans6")
failuretrans6 .add_sources(turn_to_marker1) .add_destinations(marker_forward1)
completiontrans9 = CompletionTrans() .set_name("completiontrans9")
completiontrans9 .add_sources(marker_forward1) .add_destinations(setheadangle2)
completiontrans10 = CompletionTrans() .set_name("completiontrans10")
completiontrans10 .add_sources(setheadangle2) .add_destinations(statenode6)
timertrans7 = TimerTrans(0.2) .set_name("timertrans7")
timertrans7 .add_sources(statenode6) .add_destinations(turn_to_marker2)
completiontrans11 = CompletionTrans() .set_name("completiontrans11")
completiontrans11 .add_sources(turn_to_marker2) .add_destinations(marker_forward2)
failuretrans7 = FailureTrans() .set_name("failuretrans7")
failuretrans7 .add_sources(turn_to_marker2) .add_destinations(marker_forward2)
timertrans8 = TimerTrans(0.2) .set_name("timertrans8")
timertrans8 .add_sources(marker_forward2) .add_destinations(lower_head,through_door)
completiontrans12 = CompletionTrans() .set_name("completiontrans12")
completiontrans12 .add_sources(lower_head,through_door) .add_destinations(checkcarrying2)
completiontrans13 = CompletionTrans() .set_name("completiontrans13")
completiontrans13 .add_sources(checkcarrying2) .add_destinations(parentcompletes1)
return self
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,048
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/geometry.py
|
"""
Geometry calculations, including transformation matrices for
kinematics.
"""
import numpy as np
from math import sin, cos, tan, pi, atan2, asin, sqrt, floor, ceil
from fractions import Fraction
import copy
def point(x=0,y=0,z=0):
return np.array([ [x], [y], [z], [1.] ])
def norm(pt):
return pt[0][0:3].norm()
def aboutX(theta):
c = cos(theta)
s = sin(theta)
return np.array([
[ 1, 0, 0, 0],
[ 0, c, -s, 0],
[ 0, s, c, 0],
[ 0, 0, 0, 1]])
def aboutY(theta):
c = cos(theta)
s = sin(theta)
return np.array([
[ c, 0, s, 0],
[ 0, 1, 0, 0],
[-s, 0, c, 0],
[ 0, 0, 0, 1]])
def aboutZ(theta):
c = cos(theta)
s = sin(theta)
return np.array([
[ c, -s, 0, 0],
[ s, c, 0, 0],
[ 0, 0, 1, 0],
[ 0, 0, 0, 1.]])
def translate(x,y,z=0):
return np.array([
[ 1, 0, 0, x],
[ 0, 1, 0, y],
[ 0, 0, 1, z],
[ 0, 0, 0, 1.]])
def normalize(v):
s = v[3,0]
if s == 0:
return v
else:
return v/s
def identity():
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1.]])
def dh_matrix(d,theta,r,alpha):
"""Denavit-Hartenberg transformation from joint i to joint i+1."""
return aboutX(alpha).dot(translate(r,0,d).dot(aboutZ(theta)))
def translation_part(t):
return np.array([ [t[0,3]], [t[1,3]], [t[2,3]], [0] ]) / t[3,3]
def rotation_part(t):
r = t.copy()
r[0:3,3] = 0
return r
def wrap_angle(angle_rads):
"""Keep angle between -pi and pi."""
if isinstance(angle_rads, np.ndarray):
raise ValueError("Argument not a scalar: %s", angle_rads)
while angle_rads <= -pi:
angle_rads += 2*pi
while angle_rads > pi:
angle_rads -= 2*pi
return angle_rads
def wrap_selected_angles(angle_rads, index):
"""Keep angle between -pi and pi for column vector of angles"""
for i in index:
angle_rads[i,0] = wrap_angle(angle_rads[i,0])
return angle_rads
def tprint(t):
number_format = "%7.3f"
def tprint_vector(t):
for i in range(t.shape[0]):
if i == 0:
print('[ ',end='')
else:
print(' ',end='')
print(number_format % t[i],end='')
if i+1 == t.shape[0]:
print(' ]')
else:
print()
def tprint_matrix(t):
for i in range(t.shape[0]):
if i == 0:
print('[ ',end='')
else:
print(' ',end='')
for j in range(t.shape[1]):
if j>0: print(' ',end='')
print(number_format % t[i][j], end='')
if i+1 == t.shape[0]:
print(' ]')
else:
print()
if isinstance(t, np.ndarray) and t.ndim == 1:
tprint_vector(t)
elif isinstance(t, np.ndarray) and t.ndim == 2:
tprint_matrix(t)
elif isinstance(t, (int,float)):
print(number_format % t)
else:
print(t)
def rotate_point(point, center, angle):
pointX, pointY = point
centerX, centerY = center
rotatedX = cos(angle) * (pointX - centerX) - sin(angle) * (pointY-centerY) + centerX
rotatedY = sin(angle) * (pointX - centerX) + cos(angle) * (pointY - centerY) + centerY
return rotatedX, rotatedY
#---------------- Quaternions ----------------
def quat2rot(q0,q1,q2,q3):
# formula from http://stackoverflow.com/questions/7938373/from-quaternions-to-opengl-rotations
q0_sq = q0*q0; q1_sq = q1*q1; q2_sq = q2*q2; q3_sq = q3*q3
t_q0q1 = 2. * q0 * q1
t_q0q2 = 2. * q0 * q2
t_q0q3 = 2. * q0 * q3
t_q1q2 = 2. * q1 * q2
t_q1q3 = 2. * q1 * q3
t_q2q3 = 2. * q2 * q3
return np.array([
[ q0_sq+q1_sq-q2_sq-q3_sq, t_q1q2-t_q0q3, t_q1q3+t_q0q2, 0. ],
[ t_q1q2+t_q0q3, q0_sq-q1_sq+q2_sq-q3_sq, t_q2q3-t_q0q1, 0. ],
[ t_q1q3-t_q0q2, t_q2q3+t_q0q1, q0_sq-q1_sq-q2_sq+q3_sq, 0. ],
[ 0., 0., 0., 1. ]])
def quat2rot33(q0,q1,q2,q3):
# formula from http://stackoverflow.com/questions/7938373/from-quaternions-to-opengl-rotations
q0_sq = q0*q0; q1_sq = q1*q1; q2_sq = q2*q2; q3_sq = q3*q3
t_q0q1 = 2. * q0 * q1
t_q0q2 = 2. * q0 * q2
t_q0q3 = 2. * q0 * q3
t_q1q2 = 2. * q1 * q2
t_q1q3 = 2. * q1 * q3
t_q2q3 = 2. * q2 * q3
return np.array([
[ q0_sq+q1_sq-q2_sq-q3_sq, t_q1q2-t_q0q3, t_q1q3+t_q0q2, ],
[ t_q1q2+t_q0q3, q0_sq-q1_sq+q2_sq-q3_sq, t_q2q3-t_q0q1, ],
[ t_q1q3-t_q0q2, t_q2q3+t_q0q1, q0_sq-q1_sq-q2_sq+q3_sq]])
def quaternion_to_euler_angle(quaternion):
# source: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
w, x, y, z = quaternion
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
X = atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
Y = asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
Z = atan2(t3, t4)
return X, Y, Z
#---------------- Orientation state from quaternion ----------------
ORIENTATION_UPRIGHT = 'upright'
ORIENTATION_INVERTED = 'inverted'
ORIENTATION_SIDEWAYS = 'sideways'
ORIENTATION_TILTED = 'tilted'
ORIENTATION_LEFT = 'left'
ORIENTATION_RIGHT = 'right'
def get_orientation_state(quaternion, isPlanar=False):
"""Utility used by light cubes, charger, and custom markers."""
q0, q1, q2, q3 = quaternion
mat_arr = quat2rot(q0, q1, q2, q3)
z_vec = np.array([0, 0, 1, 1])
z_dot = mat_arr.dot(z_vec)[:3]
dot_product = np.round(z_dot.dot(np.array([0, 0, 1])), decimals=2)
x, y, z = quaternion_to_euler_angle(quaternion)
if isPlanar:
perpendicular = True if -0.5 < y < 0.5 else False
if not perpendicular:
dot_product = np.round(z_dot.dot(np.array([1, 0, 0])), decimals=2)
x, y, z = quaternion_to_euler_angle([q0, q2, q3, q1])
x = -y if x>0 else y+pi
x = x if x < pi else (x - 2*pi)
if dot_product >= 0.9:
orientation = ORIENTATION_UPRIGHT
elif dot_product <= -0.9:
orientation = ORIENTATION_INVERTED
z -= pi
elif -0.15 <= dot_product <= 0.15:
if isPlanar:
# Markers
if 0 < x < pi:
orientation = ORIENTATION_RIGHT
else:
orientation = ORIENTATION_LEFT
else:
# Cubes
isSideways = abs(y) < 0.2 or abs(abs(y)-pi/2) < 0.2
orientation = ORIENTATION_SIDEWAYS if isSideways else ORIENTATION_TILTED
if round(y, 1) == 0:
z = z-pi/2 if x>0 else z+pi/2
else:
#w, x, y, z = quaternion
#x, y, z = quaternion_to_euler_angle([w, y, x, z])
x, y, _ = quaternion_to_euler_angle([q0, q2, q1, q3])
z = -y if x>0 else y+pi
else:
orientation = ORIENTATION_TILTED
return orientation, x, y, z
# return orientation, x, y, wrap_angle(z)
def same_orientation(old_object, new_object):
q1 = old_object.pose.rotation.q0_q1_q2_q3
q2 = new_object.pose.rotation.q0_q1_q2_q3
old_orientation, _, _, _ = get_orientation_state(q1)
new_orientation, _, _, _ = get_orientation_state(q2)
if old_orientation != new_orientation:
return False
elif old_orientation == ORIENTATION_SIDEWAYS:
old_pattern_number = get_pattern_number(old_object.pose.rotation.euler_angles)
new_pattern_number = get_pattern_number(new_object.pose.rotation.euler_angles)
if old_pattern_number == new_pattern_number:
return True
else:
return False
else:
return True
def get_pattern_number(eulerAngles):
x, y, z = eulerAngles
pattern = -1
z = min([pi/2, 0, -pi/2], key=lambda val:abs(val-z))
if z == -pi/2:
pattern = 1
elif z == pi/2:
pattern = 3
else:
if min([0, -pi, pi], key=lambda val:abs(val-x)) == 0:
pattern = 2
else:
pattern = 4
return pattern
#---------------- General Geometric Calculations ----------------
def project_to_line(x0,y0,theta0,x1,y1):
"""Returns the projection of the point (x1,y1) onto the
line through (x0,y0) with orientation theta0."""
bigvalue = 1e6
m0 = max(-bigvalue, min(bigvalue, tan(theta0)))
if abs(m0) < 1/bigvalue:
return (x1,y0)
m1 = -1 / m0
b0 = y0 - m0*x0
b1 = y1 - m1*x1
x2 = (b0-b1) / (m1-m0)
y2 = m0 * x2 + b0
return (x2,y2)
def line_equation(p1, p2):
"Returns the line equation used by line_intersection."
A = (p1[1] - p2[1])
B = (p2[0] - p1[0])
C = (p1[0]*p2[1] - p2[0]*p1[1])
return (A, B, -C)
def line_extrapolate(L, x):
(A,B,C) = L
s = +1 if B > 0 else -1
return C if B == 0 else (-A/B)*x + C*s
def line_intersection(L1,L2):
"Intersection point of two lines defined by line equations"
D = L1[0] * L2[1] - L1[1] * L2[0]
if D == 0: return False
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
x = Dx / D
y = Dy / D
return (x,y)
def segment_intersect_test(p1, p2, p3, p4):
"""Returns True if the line segment from p1 to p2
intersects the line segment from p3 to p4. Formula from
http://www.cs.swan.ac.uk/~cssimon/line_intersection.html"""
(x1,y1) = p1
(x2,y2) = p2
(x3,y3) = p3
(x4,y4) = p4
denom = (x4-x3)*(y1-y2) - (x1-x2)*(y4-y3)
if abs(denom) < 0.0001:
return False
numa = (y3-y4)*(x1-x3) + (x4-x3)*(y1-y3)
numb = (y1-y2)*(x1-x3) + (x2-x1)*(y1-y3)
ta = numa / denom
tb = numb / denom
if (0 <= ta <= 1) and (0 <= tb <= 1):
return True
else:
return False
def rotation_matrix_to_euler_angles(R):
"Input R is a 3x3 rotation matrix."
sy = sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
singular = sy < 1e-6
if not singular:
x = atan2(R[2,1] , R[2,2])
y = atan2(-R[2,0], sy)
z = atan2(R[1,0], R[0,0])
else:
x = atan2(-R[1,2], R[1,1])
y = atan2(-R[2,0], sy)
z = 0
return np.array([x, y, z])
def polygon_fill(polygon, offset):
"""
Implement the scanline polygon fill algorithm
Input a polygon (rrt shape) and return points inside the polygon
"""
class Edge:
def __init__(self, ymax, x, sign, dx, dy, sum):
self.ymax = ymax
self.xval = x
self.sign = sign
self.dx = dx
self.dy = dy
self.sum = sum
def __repr__(self):
return '<Edge (ymax= %s, xval= %s, sign= %s, dx= %s, dy= %s, sum= %s )>' % \
(self.ymax, self.xval, self.sign, self.dx, self.dy, self.sum)
[xCenter, yCenter, _, _] = polygon.vertices.mean(1)
edges = polygon.edges
((xmin,ymin), (xmax,ymax)) = polygon.get_bounding_box()
xmin, ymin, xmax, ymax = floor(xmin), floor(ymin), ceil(xmax), ceil(ymax)
xdelta = abs(xmin) if xmin < 0 else 0
xmin += xdelta
xmax += xdelta
xCenter += xdelta
ydelta = abs(ymin) if ymin < 0 else 0
ymin += ydelta
ymax += ydelta
yCenter += ydelta
edge_table = [[] for i in range(ymax+1)]
active_list, points = [], []
for edge in edges:
([[p1x], [p1y], _, _], [[p2x], [p2y], _, _]) = edge
if (p1y-p2y) != 0: # Don't need to consider horizontal edges
p1x, p1y, p2x, p2y = p1x+xdelta, p1y+ydelta, p2x+xdelta, p2y+ydelta
end_points = [[p1x, p1y], [p2x, p2y]]
end_points = sorted(end_points, key = lambda pt: pt[1]) # Sort on y value
_xval, _ymin, _ymax = int(round(end_points[0][0])), int(round(end_points[0][1])), int(round(end_points[1][1]))
slope = Fraction((p1x-p2x)/(p1y-p2y)).limit_denominator(10)
_dx = slope.numerator
_dy = slope.denominator
_sign = 1 if (_dx > 0) == (_dy > 0) else -1
_edge = Edge(_ymax, _xval, _sign, abs(_dx), abs(_dy), 0)
edge_table[_ymin].append(_edge)
for scanline in range(ymin, ymax+1):
# Add match (ymin==scanline) edges to the active_list
if len(edge_table[scanline]) > 0:
for edge in edge_table[scanline]:
active_list.append(edge)
if len(active_list) > 0:
y_lower_bound = (ymin - offset) if (offset < 0) else (yCenter - offset)
y_upper_bound = (ymax + offset) if (offset < 0) else (yCenter + offset)
if y_lower_bound < scanline < y_upper_bound:
# Sort active_list on x value; if same x value, sort on slope (1/m)
active_list = sorted(active_list, key = lambda x: (x.xval, x.sign*x.dx/x.dy))
for _x in range(active_list[0].xval, active_list[1].xval):
x_lower_bound = (active_list[0].xval - offset) if (offset < 0) else (xCenter - offset)
x_upper_bound = (active_list[1].xval + offset) if (offset < 0) else (xCenter + offset)
if x_lower_bound < _x < x_upper_bound:
points.append([_x-xdelta, scanline-ydelta])
if len(active_list) > 3:
y_lower_bound = (ymin - offset) if (offset < 0) else (yCenter - offset)
y_upper_bound = (ymax + offset) if (offset < 0) else (yCenter + offset)
if y_lower_bound < scanline < y_upper_bound:
for _x in range(active_list[2].xval, active_list[3].xval):
x_lower_bound = (active_list[2].xval - offset) if (offset < 0) else (xCenter - offset)
x_upper_bound = (active_list[3].xval + offset) if (offset < 0) else (xCenter + offset)
if x_lower_bound < _x < x_upper_bound:
points.append([_x-xdelta, scanline-ydelta])
# Remove form active_list if edge.ymax = scanline
active_list = [edge for edge in active_list if scanline < edge.ymax]
# Increase x-value
for edge in active_list:
# Add dx to sum
edge.sum += edge.dx
# While sum ≥ dy, adjust x, subtract dy from sum
while edge.sum >= edge.dy:
edge.xval += edge.sign
edge.sum -= edge.dy
return points
def check_concave(polygon):
"""
Input a polygon (rrt shape)
Return a boolean(is concave or not) and
a list of triangle vertices divided from the concave polygon
"""
# Currently only works for quadrilateral
vertices = np.transpose(polygon.vertices).tolist()
edges = [[p1x-p2x, p1y-p2y] for [[p1x], [p1y], _, _], [[p2x], [p2y], _, _] in polygon.edges]
crossProducts = [np.cross(edges[i], edges[i-1]) > 0 for i in range(len(edges))]
if all(crossProducts) or not any(crossProducts):
return False, None
else:
trues = [i for i in range(len(crossProducts)) if crossProducts[i] == True]
falses = [i for i in range(len(crossProducts)) if crossProducts[i] == False]
idx = trues[0] if len(trues) < len(falses) else falses[0]
vertices += vertices
tri1 = vertices[:][idx:idx+3]
tri2 = vertices[:][idx+2:idx+5]
return True, [np.transpose(tri1), np.transpose(tri2)]
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,049
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/__init__.py
|
from cozmo.util import radians, degrees, Pose, Rotation
from . import base
from . import program
base.program = program
from .nodes import *
from .transitions import *
from .program import *
from .trace import tracefsm
from .particle import *
from .particle_viewer import ParticleViewer
from .path_planner import PathPlanner
from .cozmo_kin import *
from .rrt import *
from .path_viewer import PathViewer
from .speech import *
from .worldmap import WorldMap
from .worldmap_viewer import WorldMapViewer
from .cam_viewer import CamViewer
from .pilot import *
from .pickup import *
from .doorpass import *
from . import wall_defs
from . import custom_objs
from .sim_robot import SimRobot
del base
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,050
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/examples/PF_Aruco.py
|
"""
PF_Aruco demonstrates a particle filter using ArUco markers.
There are three sensor models provided:
ArucoDistanceSensorModel -- distances only
ArucoBearingSensorModel -- bearings only
ArucoCombinedSensorModel -- combined distances + bearings
In the particle viewer window:
the WASD keys move the robot
'e' forces an evaluation step
'r' forces a resampling
'v' displays the weight statistics
'z' re-randomizes the particles.
"""
from cozmo_fsm import *
from cozmo.util import degrees, Pose
class PF_Aruco(StateMachineProgram):
def __init__(self):
landmarks = {
'Aruco-0' : Pose(-55, 160, 0, angle_z=degrees(90)),
'Aruco-1' : Pose( 55, 160, 0, angle_z=degrees(90)),
'Aruco-2' : Pose(160, 55, 0, angle_z=degrees( 0)),
'Aurco-3' : Pose(160, -55, 0, angle_z=degrees( 0))
}
pf = ParticleFilter(robot,
landmarks = landmarks,
sensor_model = ArucoCombinedSensorModel(robot))
super().__init__(particle_filter=pf, particle_viewer=True)
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,051
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/aruco/generatetags.py
|
import numpy as np
import cv2,os,sys,time
import cv2.aruco as aruco
def make_folder(name):
try:
os.system("mkdir "+name)
except:
pass
def getBottomLeftWhite(im):
(width,height) = im.shape
for y in range(height-1,-1,-1):
for x in range(width):
if(im[y][x] == 255):
return (x,y)
return None
def getTag(num,aruco_dict=aruco.Dictionary_get(aruco.DICT_4X4_100),size=500):
return aruco.drawMarker(aruco_dict,num,size)
def save_tags(aruco_dict,name,num,size=500,flip=False,label=False):
for i in range(num):
if i%20==0: print("tag %d generated." % (i))
im = getTag(i,aruco_dict,size)
if flip:
im = cv2.flip(im,1)
pos = getBottomLeftWhite(im)
pos = (pos[0]+5,pos[1]-5) #shift up a little
final=cv2.putText(im,str(i),pos,cv2.FONT_HERSHEY_COMPLEX_SMALL,1,128) #write num in gray
if label:
#add label
final = np.concatenate((final,255*np.ones((int(size/10),size))))
msg = "Tag %d" % (i)
pos = (int(size/2)-20*int(len(msg)/2),size+int(size/20))
final = cv2.putText(final,"Tag %d" % (i),pos,cv2.FONT_HERSHEY_COMPLEX_SMALL,1,0)
cv2.imwrite(name+str(i)+".jpg",final)
def generate_tags(dict_name,outfilename,quantity=100,flip=False,label=False):
aruco_dict = aruco.Dictionary_get(dict_name)
save_tags(aruco_dict,outfilename,quantity,flip=flip,label=label)
if(__name__ == "__main__"):
print("you are running this file as a standalone program.")
label = len(sys.argv)>1
if(label):
print("You have chosen to label images of all tags.")
print("tags being outputed will be saved to autogenerated folders in your current directory. Press enter to continue?")
input() #wait for user to press enter
make_folder("aruco_4x4_100")
#make_folder("aruco_4x4_1000")
#make_folder("aruco_5x5_100")
#make_folder("aruco_5x5_1000"),
generate_tags(aruco.DICT_4X4_100,"aruco_4x4_100/aruco4x4_100_",flip=False)
#generate_tags(aruco.DICT_4X4_1000,"aruco_4x4_1000/aruco4x4_1000_",1000,flip=flip)
#generate_tags(aruco.DICT_5X5_100,"aruco_5x5_100/aruco5x5_100_",flip=flip)
#generate_tags(aruco.DICT_5X5_1000,"aruco_5x5_1000/aruco5x5_1000_",1000,flip=flip)
print("complete!")
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,052
|
touretzkyds/cozmo-tools
|
refs/heads/master
|
/cozmo_fsm/wavefront.py
|
"""
Wavefront path planning algorithm.
"""
import numpy as np
import heapq
from math import floor, ceil, cos, sin
from .geometry import wrap_angle, rotate_point, polygon_fill, check_concave
from .rrt import StartCollides
from .rrt_shapes import *
from .worldmap import LightCubeObj, ChargerObj, CustomMarkerObj, MapFaceObj
class WaveFront():
goal_marker = 2**31 - 1
def __init__(self, square_size=5, bbox=None, grid_shape=(150,150), inflate_size=50):
self.square_size = square_size # in mm
self.bbox = bbox # in mm
self.inflate_size = inflate_size # in mm
self.grid_shape = grid_shape # array shape
self.initialize_grid(bbox=bbox)
self.obstacles = dict()
def initialize_grid(self,bbox=None):
if bbox:
self.bbox = bbox
self.grid_shape = (ceil((bbox[1][0] - bbox[0][0] + 4*self.inflate_size)/self.square_size),
ceil((bbox[1][1] - bbox[0][1] + 4*self.inflate_size)/self.square_size))
self.grid = np.zeros(self.grid_shape, dtype=np.int32)
self.maxdist = 1
def coords_to_grid(self,xcoord,ycoord):
"Convert world map coordinates to grid subscripts."
x = int(round((xcoord-self.bbox[0][0]+2*self.inflate_size)/self.square_size))
y = int(round((ycoord-self.bbox[0][1]+2*self.inflate_size)/self.square_size))
if x >= 0 and x < self.grid_shape[0] and \
y >= 0 and y < self.grid_shape[1]:
return (x,y)
else:
return (None,None)
def grid_to_coords(self,gridx,gridy):
xmin = self.bbox[0][0]
ymin = self.bbox[0][1]
x = gridx*self.square_size + xmin - 2*self.inflate_size
y = gridy*self.square_size + ymin - 2*self.inflate_size
return (x,y)
def set_obstacle_cell(self, xcoord, ycoord, obstacle_id):
(x,y) = self.coords_to_grid(xcoord,ycoord)
if x is not None:
self.grid[x,y] = obstacle_id
def add_obstacle(self, obstacle):
obstacle_id = -(1 + len(self.obstacles))
self.obstacles[obstacle_id] = obstacle
if isinstance(obstacle, Rectangle):
centerX, centerY = obstacle.center[0,0], obstacle.center[1,0]
width, height = obstacle.dimensions[0], obstacle.dimensions[1]
theta = wrap_angle(obstacle.orient)
for x in range(floor(centerX-width/2),
ceil(centerX+width/2),
int(self.square_size/2)):
for y in range(floor(centerY-height/2),
ceil(centerY+height/2),
int(self.square_size/2)):
new_x = ((x - centerX) * cos(theta) - (y - centerY) * sin(theta)) + centerX
new_y = ((x - centerX) * sin(theta) + (y - centerY) * cos(theta)) + centerY
self.set_obstacle_cell(new_x, new_y, obstacle_id)
elif isinstance(obstacle, Polygon):
raise NotImplemented(obstacle)
elif isinstance(obstacle, Circle):
raise NotImplemented(obstacle)
elif isinstance(obstacle, Compound):
raise NotImplemented(obstacle)
else:
raise Exception("%s has no add_obstacle() method defined for %s." % (self, obstacle))
def set_goal_cell(self,xcoord,ycoord):
self.set_cell_contents(xcoord,ycoord,self.goal_marker)
def set_empty_cell(self,xcoord,ycoord):
self.set_cell_contents(xcoord, ycoord, 0)
def set_cell_contents(self,xcoord,ycoord,contents):
(x,y) = self.coords_to_grid(xcoord,ycoord)
if x is not None:
self.grid[x,y] = contents
else:
print('**** bbox=', self.bbox, ' grid_shape=', self.grid_shape,
' x,y=', (x,y), ' xcoord,ycoord=', (xcoord,ycoord))
print(ValueError('Coordinates (%s, %s) are outside the wavefront grid' % ((xcoord,ycoord))))
def set_goal_shape(self, shape, default_offset=None, obstacle_inflation=0):
goal_points = []
if shape.obstacle_id.startswith('Room'):
empty_points, goal_points = self.generate_room_goal_points(shape, default_offset)
else: # cubes, charger, markers, mapFace
empty_points, goal_points = self.generate_cube_goal_points(shape, obstacle_inflation)
for point in empty_points:
self.set_empty_cell(*rotate_point(point, shape.center[0:2,0], shape.orient))
for point in goal_points:
self.set_goal_cell(*rotate_point(point, shape.center[0:2,0], shape.orient))
def generate_room_goal_points(self, shape, default_offset):
offset = -1 if default_offset is None else default_offset
if offset > 0:
isConcave, vertices_lst = check_concave(shape)
else:
isConcave, vertices_lst = False, []
if isConcave:
for vertices in vertices_lst:
goal_points += polygon_fill(Polygon(vertices), offset)
else:
goal_points = polygon_fill(shape, offset)
empty_points = []
return (empty_points, goal_points)
def generate_cube_goal_points(self,shape,obstacle_inflation):
# Generate points for cubes, charger, markers, mapFace in
# standard orientation. Will rotate these later.
if shape.obstacle_id.startswith('Cube'):
(xsize,ysize,_) = LightCubeObj.light_cube_size
goal_offset = 25 # distance from edge in mm
elif shape.obstacle_id.startswith('Charger'):
(xsize,ysize,_) = ChargerObj.charger_size
goal_offset = 15 # distance from edge in mm
elif shape.obstacle_id.startswith('CustomMarkerObj'):
(xsize,ysize,_) = CustomMarkerObj.custom_marker_size
goal_offset = 15 # distance from edge in mm
elif shape.obstacle_id == 'MapFace':
(xsize,ysize) = MapFaceObj.mapFace_size
goal_offset = 15 # distance from edge in mm
else:
raise ValueError('Unrecognized goal shape', shape)
((xmin,ymin), (xmax,ymax)) = shape.get_bounding_box()
goal_points, empty_points = [], []
for offset in range(floor(xsize/2), ceil(xsize/2)+obstacle_inflation+2):
empty_points.append([shape.center[0,0]-offset, shape.center[1,0]])
empty_points.append([shape.center[0,0]+offset, shape.center[1,0]])
for offset in range(floor(ysize/2), ceil(ysize/2)+obstacle_inflation+2):
empty_points.append([shape.center[0,0], shape.center[1,0]-offset])
empty_points.append([shape.center[0,0], shape.center[1,0]+offset])
goal_points.append([shape.center[0,0]-xsize/2-goal_offset, shape.center[1,0]])
goal_points.append([shape.center[0,0]+xsize/2+goal_offset, shape.center[1,0]])
goal_points.append([shape.center[0,0], shape.center[1,0]-ysize/2-goal_offset])
goal_points.append([shape.center[0,0], shape.center[1,0]+ysize/2+goal_offset])
return (empty_points, goal_points)
def check_start_collides(self,xstart,ystart):
(x,y) = self.coords_to_grid(xstart,ystart)
contents = self.grid[x,y]
if contents == 0 or contents == self.goal_marker:
return False
else:
collider = self.obstacles[contents]
print('start collides:', (xstart,ystart), (x,y), collider)
return collider
def propagate(self,xstart,ystart):
"""
Propagate the wavefront in eight directions from the starting coordinates
until a goal cell is reached or we fill up the grid.
"""
if self.check_start_collides(xstart,ystart):
raise StartCollides()
grid = self.grid
(x,y) = self.coords_to_grid(xstart,ystart)
goal_marker = self.goal_marker
if grid[x,y] == goal_marker:
return (x,y)
fringe = [(1,(x,y))]
heapq.heapify(fringe)
xmax = self.grid_shape[0] - 1
ymax = self.grid_shape[1] - 1
while fringe:
dist,(x,y) = heapq.heappop(fringe)
if grid[x,y] == 0:
grid[x,y] = dist
else:
continue
dist10 = dist + 10
dist14 = dist + 14
self.maxdist = dist14
if x > 0:
cell = grid[x-1,y]
if cell == goal_marker: return (x-1,y)
elif cell == 0:
heapq.heappush(fringe, (dist10,(x-1,y)))
if y > 0:
cell = grid[x-1,y-1]
if cell == goal_marker: return (x-1,y-1)
elif cell == 0:
heapq.heappush(fringe, (dist14,(x-1,y-1)))
if y < ymax:
cell = grid[x-1,y+1]
if cell == goal_marker: return (x-1,y+1)
elif cell == 0:
heapq.heappush(fringe, (dist14,(x-1,y+1)))
if x < xmax:
cell = grid[x+1,y]
if cell == goal_marker: return (x+1,y)
elif cell == 0:
heapq.heappush(fringe, (dist10,(x+1,y)))
if y > 0:
cell = grid[x+1,y-1]
if cell == goal_marker: return (x+1,y-1)
elif cell == 0:
heapq.heappush(fringe, (dist14,(x+1,y-1)))
if y < ymax:
cell = grid[x+1,y+1]
if cell == goal_marker: return (x+1,y+1)
elif cell == 0:
heapq.heappush(fringe, (dist14,(x+1,y+1)))
if y > 0:
cell = grid[x,y-1]
if cell == goal_marker: return (x,y-1)
elif cell == 0:
heapq.heappush(fringe, (dist10,(x,y-1)))
if y < ymax:
cell = grid[x,y+1]
if cell == goal_marker: return (x,y+1)
elif cell == 0:
heapq.heappush(fringe, (dist10,(x,y+1)))
return None
def extract(self, search_result, wf_start):
"Extract the path once the goal is found, and convert back to worldmap coordinates."
start_coords = self.coords_to_grid(*wf_start)
if search_result == start_coords:
return [self.grid_to_coords(*search_result)]
(x,y) = search_result
maxdist = self.goal_marker + 1
grid = self.grid
xmax = self.grid_shape[0] - 1
ymax = self.grid_shape[1] - 1
path = []
while maxdist > 1:
path.append((x,y))
if x > 0:
if 0 < grid[x-1,y] < maxdist:
maxdist = grid[x-1,y]
(newx,newy) = (x-1,y)
if y > 0:
if 0 < grid[x-1,y-1] < maxdist:
maxdist = grid[x-1,y-1]
(newx,newy) = (x-1,y-1)
if y < ymax:
if 0 < grid[x-1,y+1] < maxdist:
maxdist = grid[x-1,y+1]
(newx,newy) = (x-1,y+1)
if x < xmax:
if 0 < grid[x+1,y] < maxdist:
maxdist = grid[x+1,y]
(newx,newy) = (x+1,y)
if y > 0:
if 0 < grid[x+1,y-1] < maxdist:
maxdist = grid[x+1,y-1]
(newx,newy) = (x+1,y-1)
if y < ymax:
if 0 < grid[x+1,y+1] < maxdist:
maxdist = grid[x+1,y+1]
(newx,newy) = (x+1,y+1)
if y > 0:
if 0 < grid[x,y-1] < maxdist:
maxdist = grid[x,y-1]
(newx,newy) = (x,y-1)
if y < ymax:
if 0 < grid[x,y+1] < maxdist:
maxdist = grid[x,y+1]
(newx,newy) = (x,y+1)
(x,y) = (newx,newy)
path.append((x,y))
path.reverse()
square_size = self.square_size
xmin = self.bbox[0][0]
ymin = self.bbox[0][1]
path_coords = [self.grid_to_coords(x,y) for (x,y) in path]
return path_coords
def wf_test():
start = (261,263)
goal = (402,454)
#
wf = WaveFront()
wf.grid[:,:] = 0
wf.set_goal_cell(*goal)
wf.set_obstacle_cell(280,280)
wf.set_obstacle_cell(280,290)
wf.set_obstacle_cell(290,280)
wf.set_obstacle_cell(290,290)
result1 = wf.propagate(*start)
result2 = wf.extract(result1)
print('path length =', len(result2))
print(result2)
print(wf.grid[75:85, 75:85])
return result2
# wf_test()
|
{"/cozmo_fsm/examples/Boo.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/events.py": ["/cozmo_fsm/evbase.py"], "/cozmo_fsm/examples/CV_GoodFeatures.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Greet.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_OpticalFlow.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/pilot0.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/evbase.py": ["/cozmo_fsm/trace.py"], "/cozmo_fsm/perched.py": ["/cozmo_fsm/geometry.py"], "/cozmo_fsm/pickup.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/CV_Hough.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/worldmap_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/PF_Cube.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/sim_robot.py": ["/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/examples/TapSpeak.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/perched.py"], "/cozmo_fsm/examples/Nested.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/CV_Contour.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Look5.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Texting.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/speech.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/nodes.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/obstavoidance.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/path_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/sharedmap.py": ["/cozmo_fsm/worldmap.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/path_planner.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/wavefront.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/__init__.py"], "/cozmo_fsm/base.py": ["/cozmo_fsm/trace.py", "/cozmo_fsm/evbase.py", "/cozmo_fsm/events.py"], "/cozmo_fsm/cozmo_kin.py": ["/cozmo_fsm/kine.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py"], "/cozmo_fsm/examples/Iteration.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/examples/Randomness.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/rrt_shapes.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/transitions.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/events.py", "/cozmo_fsm/nodes.py"], "/cozmo_fsm/worldmap.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/geometry.py"], "/cozmo_fsm/pilot.py": ["/cozmo_fsm/base.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/nodes.py", "/cozmo_fsm/events.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/pilot0.py"], "/cozmo_fsm/examples/BackItUp.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/cam_viewer.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/program.py": ["/cozmo_fsm/evbase.py", "/cozmo_fsm/base.py", "/cozmo_fsm/aruco.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/__init__.py", "/cozmo_fsm/perched.py", "/cozmo_fsm/sharedmap.py"], "/cozmo_fsm/examples/CV_Canny.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/particle_viewer.py": ["/cozmo_fsm/__init__.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/rrt.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/kine.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/doorpass.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/geometry.py", "/cozmo_fsm/pilot0.py", "/cozmo_fsm/worldmap.py"], "/cozmo_fsm/__init__.py": ["/cozmo_fsm/nodes.py", "/cozmo_fsm/transitions.py", "/cozmo_fsm/program.py", "/cozmo_fsm/trace.py", "/cozmo_fsm/particle.py", "/cozmo_fsm/particle_viewer.py", "/cozmo_fsm/path_planner.py", "/cozmo_fsm/cozmo_kin.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/path_viewer.py", "/cozmo_fsm/speech.py", "/cozmo_fsm/worldmap.py", "/cozmo_fsm/worldmap_viewer.py", "/cozmo_fsm/cam_viewer.py", "/cozmo_fsm/pilot.py", "/cozmo_fsm/pickup.py", "/cozmo_fsm/doorpass.py", "/cozmo_fsm/sim_robot.py"], "/cozmo_fsm/examples/PF_Aruco.py": ["/cozmo_fsm/__init__.py"], "/cozmo_fsm/wavefront.py": ["/cozmo_fsm/geometry.py", "/cozmo_fsm/rrt.py", "/cozmo_fsm/rrt_shapes.py", "/cozmo_fsm/worldmap.py"]}
|
19,053
|
polyg314/smartAPI
|
refs/heads/master
|
/src/web/api/es.py
|
#pylint: disable=unexpected-keyword-arg
# non-essential parameters are declared with decorators in es.py
# https://github.com/elastic/elasticsearch-py/issues/274
import json
import logging
import string
import sys
from datetime import date, datetime
from shlex import shlex
import boto3
from elasticsearch import Elasticsearch, RequestError, helpers
from .mapping import smart_api_mapping
from .transform import (SWAGGER2_INDEXED_ITEMS, APIMetadata, decode_raw,
get_api_metadata_by_url, polite_requests)
ES_HOST = 'localhost:9200'
ES_INDEX_NAME = 'smartapi_oas3'
ES_DOC_TYPE = 'api'
def ask(prompt, options='YN'):
'''Prompt Yes or No,return the upper case 'Y' or 'N'.'''
options = options.upper()
while 1:
s = input(prompt+'[%s]' % '|'.join(list(options))).strip().upper()
if s in options:
break
return s
def get_datestamp():
d = date.today()
return d.strftime('%Y%m%d')
def get_es(es_host=None):
es_host = es_host or ES_HOST
es = Elasticsearch(es_host, timeout=120)
return es
def split_ids(q):
'''split input query string into list of ids.
any of " \t\n\x0b\x0c\r|,+" as the separator,
but perserving a phrase if quoted
(either single or double quoted)
more detailed rules see:
http://docs.python.org/2/library/shlex.html#parsing-rules
e.g. split_ids('CDK2 CDK3') --> ['CDK2', 'CDK3']
split_ids('"CDK2 CDK3"\n CDk4') --> ['CDK2 CDK3', 'CDK4']
'''
# Python3 strings are already unicode, .encode
# now returns a bytearray, which cannot be searched with
# shlex. For now, do this terrible thing until we discuss
if sys.version_info.major == 3:
lex = shlex(q, posix=True)
else:
lex = shlex(q.encode('utf8'), posix=True)
lex.whitespace = ' \t\n\x0b\x0c\r|,+'
lex.whitespace_split = True
lex.commenters = ''
if sys.version_info.major == 3:
ids = [x.strip() for x in list(lex)]
else:
ids = [x.decode('utf8').strip() for x in list(lex)]
ids = [x for x in ids if x]
return ids
def create_index(index_name=None, es=None):
index_name = index_name or ES_INDEX_NAME
body = {}
mapping = {"mappings": smart_api_mapping}
body.update(mapping)
_es = es or get_es()
print(_es.indices.create(index=index_name, body=body), end=" ")
def _get_hit_object(hit):
obj = hit.get('fields', hit.get('_source', {}))
if '_id' in hit:
obj['_id'] = hit['_id']
return obj
class ESQuery():
def __init__(self, index=None, doc_type=None, es_host=None):
self._es = get_es(es_host)
self._index = index or ES_INDEX_NAME
self._doc_type = doc_type or ES_DOC_TYPE
def exists(self, api_id):
'''return True/False if the input api_doc has existing metadata
object in the index.
'''
return self._es.exists(index=self._index, doc_type=self._doc_type, id=api_id)
# used in APIHandler [POST]
def save_api(self, api_doc, save_v2=False, overwrite=False, user_name=None,
override_owner=False, warn_on_identical=False, dryrun=False):
'''Adds or updates a compatible-format API document in the SmartAPI index, making it searchable.
:param save_v2: allow a swagger v2 document pass validation when set to True
:param overwrite: allow overwriting an existing document if the user_name provided matches the record
:param user_name: when overwrite is set to to true, and override_owner not,
to allow overwriting the existing document user_name must match that of the document.
:param override_owner: allow overwriting regardless of ownership when overwrite is also set to True
:param warn_on_identical: consider rewriting the existing docuement with an identical one unsuccessful
used in refresh_all() to exclude APIs with no change from update count
:param dryrun: only validate the schema and test the overwrite settings, do not actually save.
'''
metadata = APIMetadata(api_doc)
# validate document schema
valid = metadata.validate(raise_error_on_v2=not save_v2)
if not valid['valid']:
valid['success'] = False
valid['error'] = '[Validation] ' + valid['error']
return valid
# avoid unintended overwrite
api_id = metadata.encode_api_id()
doc_exists = self.exists(api_id)
if doc_exists:
if not overwrite:
is_archived = self._es.get(
index=self._index, doc_type=self._doc_type, id=api_id, _source=["_meta"]).get(
'_source', {}).get(
'_meta', {}).get(
'_archived', False) == 'true'
if not is_archived:
return {"success": False, "error": "[Conflict] API exists. Not saved."}
elif not override_owner:
_owner = self._es.get(
index=self._index, doc_type=self._doc_type, id=api_id, _source=["_meta"]).get(
'_source', {}).get(
'_meta', {}).get(
'github_username', '')
if _owner != user_name:
return {"success": False, "error": "[Conflict] User mismatch. Not Saved."}
# identical document
_doc = metadata.convert_es()
if doc_exists:
_raw_stored = self._es.get(
index=self._index, doc_type=self._doc_type, id=api_id, _source=["~raw"]).get(
'_source', {})['~raw']
if decode_raw(
_raw_stored, as_string=True) == decode_raw(
_doc.get('~raw'),
as_string=True):
if warn_on_identical:
return {"success": True, '_id': api_id, "warning": "[Conflict] No change in document."}
else:
return {"success": True, '_id': api_id}
# save to es index
if dryrun:
return {"success": True, '_id': "[Dryrun] this is a dryrun. API is not saved.", "dryrun": True}
try:
self._es.index(index=self._index, doc_type=self._doc_type,
body=_doc, id=api_id, refresh=True)
except RequestError as e:
return {"success": False, "error": "[ES]" + str(e)}
return {"success": True, '_id': api_id}
def _get_api_doc(self, api_doc, with_meta=True):
doc = decode_raw(api_doc.get('~raw', ''))
if with_meta:
doc["_meta"] = api_doc.get('_meta', {})
doc["_id"] = api_doc["_id"]
return doc
# used in APIMetaDataHandler [GET]
def get_api(self, api_name, fields=None, with_meta=True, return_raw=False, size=None, from_=0):
if api_name == 'all':
query = {'query': {"bool": {"must_not": {
"term": {"_meta._archived": "true"}}}}}
else:
query = {
"query": {
"bool": {
"should": [
{
"match": {
"_id": {
"query": api_name
}
}
},
{
"term": {
"_meta.slug": api_name
}
}
],
"must_not": {"term": {"_meta._archived": "true"}}
}
}
}
if fields and fields not in ["all", ["all"]]:
query["_source"] = fields
if size and isinstance(size, int):
query['size'] = min(size, 100) # set max size to 100 for now.
if from_ and isinstance(from_, int) and from_ > 0:
query['from'] = from_
res = self._es.search(self._index, self._doc_type, query)
if return_raw == '2':
return res
res = [_get_hit_object(d) for d in res['hits']['hits']]
if not return_raw:
try:
res = [self._get_api_doc(x, with_meta=with_meta) for x in res]
except ValueError as e:
res = {'success': False, 'error': str(e)}
if len(res) == 1:
res = res[0]
return res
def _do_aggregations(self, _field, agg_name, size):
query = {
"query": {
"bool": {
"must_not": {"term": {"_meta._archived": True}}
}
},
"aggs": {
agg_name: {
"terms": {
"field": _field,
"size": size
}
}
}
}
res = self._es.search(self._index, self._doc_type, query, size=0)
res = res["aggregations"]
return res
def get_api_id_from_slug(self, slug_name):
query = {
"query": {
"bool": {
"should": [
{"term": {"_meta.slug": slug_name}},
{"ids": {"values": [slug_name]}}
]
}
}
}
try:
res = self._es.search(
index=self._index, doc_type=self._doc_type, body=query, size=1, _source=False)
except:
return
if res.get('hits', {}).get('hits', []):
return res['hits']['hits'][0]['_id']
# used in ValueSuggestionHandler [GET]
def value_suggestion(self, field, size=100, use_raw=True):
"""return a list of existing values for the given field."""
_field = field + ".raw" if use_raw else field
agg_name = 'field_values'
res = self._do_aggregations(_field, agg_name, size)
return res
def delete_api(self, id):
"""delete a saved API metadata, be careful with the deletion."""
if ask("Are you sure to delete this API metadata?") == 'Y':
print(self._es.delete(index=self._index,
doc_type=self._doc_type, id=id))
# used in APIMetaDataHandler [DELETE]
def archive_api(self, id, user):
""" function to set an _archive flag for an API, making it
unsearchable from the front end, takes an id identifying the API,
and a user that must match the APIs creator. """
# does the api exist?
try:
_doc = self._es.get(index=self._index,
doc_type=self._doc_type, id=id)
except:
_doc = None
if not _doc:
return (404, {"success": False, "error": "Could not retrieve API '{}' to delete".format(id)})
# is the api unarchived?
if _doc.get('_source', {}).get('_meta', {}).get('_archived', False):
return (405, {"success": False, "error": "API '{}' already deleted".format(id)})
# is this user the owner of this api?
_user = user.get('login', None)
if _doc.get('_source', {}).get('_meta', {}).get('github_username', '') != _user:
return (405, {"success": False, "error": "User '{user}' is not the owner of API '{id}'".format(user=_user, id=id)})
# do the archive, deregister the slug name
_doc['_source']['_meta']['_archived'] = 'true'
_doc['_source']['_meta'].pop('slug', None)
self._es.index(index=self._index, doc_type=self._doc_type,
id=id, body=_doc['_source'], refresh=True)
return (200, {"success": True, "message": "API '{}' successfully deleted".format(id)})
# used in GitWebhookHandler [POST] and self.backup_all()
def fetch_all(self, as_list=False, id_list=[], query={}, ignore_archives=False):
"""return a generator of all docs from the ES index.
return a list instead if as_list is True.
if query is passed, it returns docs that match the query.
else if id_list is passed, it returns only docs from the given ids.
"""
if query:
_query = query
elif id_list:
_query = {"query": {"ids": {"type": ES_DOC_TYPE, "values": id_list}}}
elif ignore_archives:
_query = {"query": {"bool": {"must_not": {"term": {"_meta._archived": "true"}}}}}
else:
_query = {"query": {"match_all": {}}}
scan_res = helpers.scan(client=self._es, query=_query,
index=self._index, doc_type=self._doc_type)
def _fn(x):
x['_source'].setdefault('_id', x['_id'])
return x['_source']
doc_iter = (_fn(x) for x in scan_res) # return docs only
if as_list:
return list(doc_iter)
else:
return doc_iter
def backup_all(self, outfile=None, ignore_archives=False, aws_s3_bucket=None):
"""back up all docs into a output file."""
# get the real index name in case self._index is an alias
logging.info("Backup started.")
alias_d = self._es.indices.get_alias(self._index)
assert len(alias_d) == 1
index_name = list(alias_d.keys())[0]
default_name = "{}_backup_{}.json".format(index_name, get_datestamp())
outfile = outfile or default_name
doc_li = self.fetch_all(as_list=True, ignore_archives=ignore_archives)
if aws_s3_bucket:
location_prompt = 'on S3'
s3 = boto3.resource('s3')
s3.Bucket(aws_s3_bucket).put_object(
Key='db_backup/{}'.format(outfile), Body=json.dumps(doc_li, indent=2))
else:
out_f = open(outfile, 'w')
location_prompt = 'locally'
out_f = open(outfile, 'w')
json.dump(doc_li, out_f, indent=2)
out_f.close()
logging.info("Backed up %s docs in \"%s\" %s.", len(doc_li), outfile, location_prompt)
def restore_all(self, backupfile, index_name, overwrite=False):
"""restore all docs from the backup file to a new index."""
def legacy_backupfile_support_path_str(_doc):
_paths = []
if 'paths' in _doc:
for path in _doc['paths']:
_paths.append({
"path": path,
"pathitem": _doc['paths'][path]
})
if _paths:
_doc['paths'] = _paths
return _doc
def legacy_backupfile_support_rm_flds(_doc):
_d = {"_meta": _doc['_meta']}
for key in SWAGGER2_INDEXED_ITEMS:
if key in _doc:
_d[key] = _doc[key]
_d['~raw'] = _doc['~raw']
return _d
if self._es.indices.exists(index_name):
if overwrite and ask("Warning: index \"{}\" exists. Do you want to overwrite it?".format(index_name)) == 'Y':
self._es.indices.delete(index=index_name)
else:
print(
"Error: index \"{}\" exists. Try a different index_name.".format(index_name))
return
print("Loading docs from \"{}\"...".format(backupfile), end=" ")
in_f = open(backupfile)
doc_li = json.load(in_f)
print("Done. [{} Documents]".format(len(doc_li)))
print("Creating index...", end=" ")
create_index(index_name, es=self._es)
print("Done.")
print("Indexing...", end=" ")
swagger_v2_count = 0
openapi_v3_count = 0
for _doc in doc_li:
_id = _doc.pop('_id')
if "swagger" in _doc:
swagger_v2_count += 1
_doc = legacy_backupfile_support_rm_flds(_doc)
_doc = legacy_backupfile_support_path_str(_doc)
elif "openapi" in _doc:
openapi_v3_count += 1
else:
print('\n\tWARNING: ', _id, 'No Version.')
self._es.index(index=index_name,
doc_type=self._doc_type, body=_doc, id=_id)
print(swagger_v2_count, ' Swagger Objects and ',
openapi_v3_count, ' Openapi Objects. ')
print("Done.")
def _validate_slug_name(self, slug_name):
''' Function that determines whether slug_name is a valid slug name '''
_valid_chars = string.ascii_letters + string.digits + "-_~"
_slug = slug_name.lower()
# reserved for dev node, normal web functioning
if _slug in ['www', 'dev', 'smart-api']:
return (False, {"success": False, "error": "Slug name '{}' is reserved, please choose another".format(_slug)})
# length requirements
if len(_slug) < 4 or len(_slug) > 50:
return (False, {"success": False, "error": "Slug name must be between 4 and 50 chars"})
# character requirements
if not all([x in _valid_chars for x in _slug]):
return (False, {"success": False, "error": "Slug name contains invalid characters. Valid characters: '{}'".format(_valid_chars)})
# does it exist already?
_query = {
"query": {
"bool": {
"should": [
{"term": {"_meta.slug.raw": _slug}},
{"ids": {"values": [_slug]}}
]
}
}
}
if len(
self._es.search(
index=self._index, doc_type=self._doc_type, body=_query, _source=False).get(
'hits', {}).get('hits', [])) > 0:
return (False, {"success": False, "error": "Slug name '{}' already exists, please choose another".format(_slug)})
# good name
return (True, {})
# used in APIMetaDataHandler [PUT]
def set_slug_name(self, _id, user, slug_name):
''' set the slug name of API _id to slug_name. '''
if not self.exists(_id):
return (404, {"success": False, "error": "Could not retrieve API '{}' to set slug name".format(_id)})
_user = self._es.get(
index=self._index, doc_type=self._doc_type, id=_id, _source=["_meta"]).get(
'_source', {}).get(
'_meta', {}).get(
'github_username', '')
# Make sure this is the correct user
if user.get('login', None) != _user:
return (405, {"success": False, "error": "User '{}' is not the owner of API '{}'".format(user.get('login', None), _id)})
# validate the slug name
_valid, _resp = self._validate_slug_name(slug_name=slug_name)
if not _valid:
return (405, _resp)
# update the slug name
self._es.update(index=self._index, doc_type=self._doc_type, id=_id, body={
"doc": {"_meta": {"slug": slug_name.lower()}}}, refresh=True)
return (200, {"success": True, "{}._meta.slug".format(_id): slug_name.lower()})
# used in APIMetaDataHandler [DELETE]
def delete_slug(self, _id, user, slug_name):
''' delete the slug of API _id. '''
if not self.exists(_id):
return (404, {"success": False, "error": "Could not retrieve API '{}' to delete slug name".format(_id)})
doc = self._es.get(index=self._index,
doc_type=self._doc_type, id=_id).get('_source', {})
# Make sure this is the correct user
if user.get('login', None) != doc.get('_meta', {}).get('github_username', ''):
return (405, {"success": False, "error": "User '{}' is not the owner of API '{}'".format(user.get('login', None), _id)})
# Make sure this is the correct slug name
if doc.get('_meta', {}).get('slug', '') != slug_name:
return (405, {"success": False, "error": "API '{}' slug name is not '{}'".format(_id, slug_name)})
# do the delete
doc['_meta'].pop('slug')
self._es.index(index=self._index, doc_type=self._doc_type,
body=doc, id=_id, refresh=True)
return (200, {"success": True, "{}".format(_id): "slug '{}' deleted".format(slug_name)})
# used in APIMetaDataHandler [PUT]
def refresh_one_api(self, _id, user, dryrun=True):
''' authenticate the API document of specified _id correspond to the specified user,
and refresh the API document based on its saved metadata url '''
# _id validation
try:
api_doc = self._es.get(
index=self._index, doc_type=self._doc_type, id=_id)
except:
return (404, {"success": False, "error": "Could not retrieve API '{}' to refresh".format(_id)})
api_doc['_source'].update({'_id': api_doc['_id']})
# ownership validation
_user = user.get('login', None)
if api_doc.get('_source', {}).get('_meta', {}).get('github_username', '') != _user:
return (405, {"success": False, "error": "User '{user}' is not the owner of API '{id}'".format(user=_user, id=_id)})
status = self._refresh_one(
api_doc=api_doc['_source'], user=_user, dryrun=dryrun)
if not dryrun:
self._es.indices.refresh(index=self._index)
if status.get('success', False):
return (200, status)
else:
return (405, status)
def _refresh_one(self, api_doc, user=None, override_owner=False, dryrun=True,
error_on_identical=False, save_v2=False):
''' refresh the given API document object based on its saved metadata url '''
_id = api_doc['_id']
_meta = api_doc['_meta']
res = get_api_metadata_by_url(_meta['url'])
if res and isinstance(res, dict):
if res.get('success', None) is False:
res['error'] = '[Request] '+res.get('error', '')
status = res
else:
_meta['timestamp'] = datetime.now().isoformat()
res['_meta'] = _meta
status = self.save_api(
res, user_name=user, override_owner=override_owner, overwrite=True,
dryrun=dryrun, warn_on_identical=error_on_identical, save_v2=True)
else:
status = {'success': False, 'error': 'Invalid input data.'}
return status
def refresh_all(
self, id_list=[],
dryrun=True, return_status=False, use_etag=True, ignore_archives=True):
'''refresh saved API documents based on their metadata urls.
:param id_list: the list of API documents to perform the refresh operation
:param ignore_archives:
:param dryrun:
:param use_etag: by default, HTTP ETag is used to speed up version detection
'''
updates = 0
status_li = []
logging.info("Refreshing API metadata:")
for api_doc in self.fetch_all(id_list=id_list, ignore_archives=ignore_archives):
_id, status = api_doc['_id'], ''
if use_etag:
_res = polite_requests(api_doc.get('_meta', {}).get('url', ''), head=True)
if _res.get('success'):
res = _res.get('response')
etag_local = api_doc.get('_meta', {}).get('ETag', '')
etag_server = res.headers.get('ETag', 'N').strip('W/"')
if etag_local == etag_server:
status = "OK (Via Etag)"
if not status:
res = self._refresh_one(
api_doc, dryrun=dryrun, override_owner=True, error_on_identical=True,
save_v2=True)
if res.get('success'):
if res.get('warning'):
status = 'OK'
else:
status = "OK Updated"
updates += 1
else:
status = "ERR " + res.get('error')[:60]
status_li.append((_id, status))
logging.info("%s: %s", _id, status)
logging.info("%s: %s APIs refreshed. %s Updates.", get_datestamp(), len(status_li), updates)
if dryrun:
logging.warning("This is a dryrun! No actual changes have been made.")
logging.warning("When ready, run it again with \"dryrun=False\" to apply changes.")
return status_li
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,054
|
polyg314/smartAPI
|
refs/heads/master
|
/src/web/api/handlers.py
|
import datetime
import hashlib
import hmac
import json
import re
from collections import OrderedDict
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import yaml
from biothings.web.api.es.handlers import \
QueryHandler as BioThingsESQueryHandler
from biothings.web.api.es.handlers.base_handler import BaseESRequestHandler
from .es import ESQuery
from .transform import APIMetadata, get_api_metadata_by_url
from utils.slack_notification import send_slack_msg
class BaseHandler(BaseESRequestHandler):
def get_current_user(self):
user_json = self.get_secure_cookie("user")
if not user_json:
return None
return json.loads(user_json.decode('utf-8'))
class ValidateHandler(BaseHandler):
def _validate(self, data):
if data and isinstance(data, dict):
metadata = APIMetadata(data)
valid = metadata.validate()
return self.return_json(valid)
else:
return self.return_json({"valid": False, "error": "The input url does not contain valid API metadata."})
def get(self):
url = self.get_argument('url', None)
if url:
data = get_api_metadata_by_url(url)
if data.get('success', None) is False:
self.return_json(data)
else:
self._validate(data)
else:
self.return_json(
{"valid": False, "error": "Need to provide an input url first."})
def post(self):
if self.request.body:
try:
data = tornado.escape.json_decode(self.request.body)
except ValueError:
try:
data = yaml.load(self.request.body, Loader=yaml.SafeLoader)
except (yaml.scanner.ScannerError,
yaml.parser.ParserError):
return self.return_json({"valid": False, "error": "The input request body does not contain valid API metadata."})
self._validate(data)
else:
self.return_json(
{"valid": False, "error": "Need to provide data in the request body first."})
class APIHandler(BaseHandler):
def post(self):
# check if a logged in user
user = self.get_current_user()
if not user:
res = {'success': False,
'error': 'Authenticate first with your github account.'}
self.set_status(401)
self.return_json(res)
else:
# save an API metadata
overwrite = self.get_argument('overwrite', '').lower()
overwrite = overwrite in ['1', 'true']
dryrun = self.get_argument('dryrun', '').lower()
dryrun = dryrun in ['on', '1', 'true']
save_v2 = self.get_argument('save_v2', '').lower()
save_v2 = save_v2 in ['1', 'true']
url = self.get_argument('url', None)
if url:
data = get_api_metadata_by_url(url)
# try:
# data = tornado.escape.json_decode(data)
# except ValueError:
# data = None
if data and isinstance(data, dict):
if data.get('success', None) is False:
self.return_json(data)
else:
_meta = {
"github_username": user['login'],
'url': url,
'timestamp': datetime.datetime.now().isoformat()
}
data['_meta'] = _meta
esq = ESQuery()
res = esq.save_api(
data, overwrite=overwrite, dryrun=dryrun, user_name=user['login'], save_v2=save_v2)
self.return_json(res)
## send notification to slack
if(res["success"] == True):
send_slack_msg(data, res, user['login'])
else:
self.return_json(
{'success': False, 'error': 'Invalid input data.'})
else:
self.return_json(
{'success': False, 'error': 'missing required parameter.'})
class APIMetaDataHandler(BaseHandler):
esq = ESQuery()
def get(self, api_name):
'''return API metadata for a matched api_name,
if api_name is "all", return a list of all APIs
'''
fields = self.get_argument('fields', None)
out_format = self.get_argument('format', 'json').lower()
return_raw = self.get_argument('raw', False)
with_meta = self.get_argument('meta', False)
size = self.get_argument('size', None)
from_ = self.get_argument('from', 0)
try:
# size capped to 100 for now by get_api method below.
size = int(size)
except (TypeError, ValueError):
size = None
try:
from_ = int(from_)
except (TypeError, ValueError):
from_ = 0
if fields:
fields = fields.split(',')
res = self.esq.get_api(api_name, fields=fields, with_meta=with_meta,
return_raw=return_raw, size=size, from_=from_)
if out_format == 'yaml':
self.return_yaml(res)
else:
self.return_json(res)
def put(self, api_name):
''' refresh API metadata for a matched api_name,
checks to see if current user matches the creating user.'''
slug_name = self.get_argument('slug', None)
dryrun = self.get_argument('dryrun', '').lower()
dryrun = dryrun in ['on', '1', 'true']
# must be logged in first
user = self.get_current_user()
if not user:
res = {'success': False,
'error': 'Authenticate first with your github account.'}
self.set_status(401)
else:
if slug_name:
(status, res) = self.esq.set_slug_name(
_id=api_name, user=user, slug_name=slug_name)
else:
(status, res) = self.esq.refresh_one_api(
_id=api_name, user=user, dryrun=dryrun)
self.set_status(status)
self.return_json(res)
def delete(self, api_name):
'''delete API metadata for a matched api_name,
checks to see if current user matches the creating user.'''
# must be logged in first
user = self.get_current_user()
slug_name = self.get_argument('slug', '').lower()
if not user:
res = {'success': False,
'error': 'Authenticate first with your github account.'}
self.set_status(401)
elif slug_name:
(status, res) = self.esq.delete_slug(
_id=api_name, user=user, slug_name=slug_name)
self.set_status(status)
else:
(status, res) = self.esq.archive_api(api_name, user)
self.set_status(status)
self.return_json(res)
class ValueSuggestionHandler(BaseHandler):
esq = ESQuery()
def get(self):
field = self.get_argument('field', None)
try:
size = int(self.get_argument('size', 100))
except:
size = 100
if field:
res = self.esq.value_suggestion(field, size=size)
else:
res = {'error': 'missing required "field" parameter'}
self.return_json(res)
class GitWebhookHandler(BaseHandler):
esq = ESQuery()
def post(self):
# do message authentication
digest_obj = hmac.new(key=self.web_settings.API_KEY.encode(
), msg=self.request.body, digestmod=hashlib.sha1)
if not hmac.compare_digest('sha1=' + digest_obj.hexdigest(), self.request.headers.get('X-Hub-Signature', '')):
self.set_status(405)
self.return_json(
{'success': False, 'error': 'Invalid authentication'})
return
data = tornado.escape.json_decode(self.request.body)
# get repository owner name
repo_owner = data.get('repository', {}).get(
'owner', {}).get('name', None)
if not repo_owner:
self.set_status(405)
self.return_json(
{'success': False, 'error': 'Cannot get repository owner'})
return
# get repo name
repo_name = data.get('repository', {}).get('name', None)
if not repo_name:
self.set_status(405)
self.return_json(
{'success': False, 'error': 'Cannot get repository name'})
return
# find all modified files in all commits
modified_files = set()
for commit_obj in data.get('commits', []):
for fi in commit_obj.get('added', []):
modified_files.add(fi)
for fi in commit_obj.get('modified', []):
modified_files.add(fi)
# build query
_query = {"query": {"bool": {"should": [
{"regexp": {"_meta.url.raw": {"value": '.*{owner}/{repo}/.*/{fi}'.format(owner=re.escape(repo_owner), repo=re.escape(repo_name), fi=re.escape(fi)),
"max_determinized_states": 200000}}} for fi in modified_files]}}}
# get list of ids that need to be refreshed
ids_refresh = [x['_id'] for x in self.esq.fetch_all(query=_query)]
# if there are any ids to refresh, do it
if ids_refresh:
self.esq.refresh_all(id_list=ids_refresh, dryrun=False)
APP_LIST = [
(r'/?', APIHandler),
(r'/query/?', BioThingsESQueryHandler),
(r'/validate/?', ValidateHandler),
(r'/metadata/(.+)/?', APIMetaDataHandler),
(r'/suggestion/?', ValueSuggestionHandler),
(r'/webhook_payload/?', GitWebhookHandler),
]
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,055
|
polyg314/smartAPI
|
refs/heads/master
|
/src/tests/remote.py
|
'''
SmartAPI Read-Only Test
'''
import os
from nose.core import runmodule
from nose.tools import eq_
from biothings.tests import BiothingsTestCase
class SmartAPIRemoteTest(BiothingsTestCase):
''' Test against server specified in environment variable SMARTAPI_HOST
or SmartAPI production server if SMARTAPI_HOST is not specified '''
__test__ = True # explicitly set this to be a test class
host = os.getenv("SMARTAPI_HOST", "https://smart-api.info")
api = '/api'
# Query Functionalities
def test_101_regular(self):
''' Query regular string '''
self.query(q='translator')
def test_102_named_field(self):
''' Query named field '''
self.query(q='tags.name:translator')
def test_103_match_all(self):
''' Query all documents '''
self.query(q='__all__')
def test_104_random_score(self):
''' Query random documents '''
res = self.query(q='__any__')
query_1_id = res['hits'][0]['_id']
res = self.query(q='__any__')
query_2_id = res['hits'][0]['_id']
assert query_1_id != query_2_id
def test_105_filters(self):
''' Query with multiple filters '''
flt = '{"tags.name.raw":["annotation","variant"],"info.contact.name.raw":["Chunlei Wu"]}'
res = self.query(q='__all__', filters=flt)
eq_(len(res['hits']), 3)
# Error Handling
def test_201_special_char(self):
''' Handle special characters '''
self.query(q='translat\xef\xbf\xbd\xef\xbf\xbd', expect_hits=False)
self.request("query?q=http://example.com/", expect_status=400)
def test_202_missing_term(self):
''' Handle empty request '''
self.request("query", expect_status=400)
def test_203_bad_size(self):
''' Handle type error '''
self.request("query?q=__all__&size=my", expect_status=400)
def test_204_bad_index(self):
''' Handle index out of bound '''
res_0 = self.request('query?q=__all__&fields=_id&size=5').json()
ids_0 = {hit['_id'] for hit in res_0['hits']}
res_1 = self.request('query?q=__all__&fields=_id&size=5&from=5').json()
ids_1 = [hit['_id'] for hit in res_1['hits']]
for _id in ids_1:
if _id in ids_0:
assert False
# Result Formatting
def test_301_sources(self):
''' Return specified fields '''
res = self.query(q='__all__', fields='_id,info')
for hit in res['hits']:
assert '_id' in hit and 'info' in hit
assert '_meta' not in hit
def test_302_size(self):
''' Return specified size '''
res = self.query(q='__all__', size=6)
eq_(len(res['hits']), 6)
def test_303_raw(self):
''' Return raw ES result '''
res = self.query(q='__all__', raw=1)
assert '_shards' in res
def test_304_query(self):
''' Return query sent to ES '''
res = self.request('query?q=__all__&rawquery=1').json()
assert "query" in res
assert "bool" in res["query"]
if __name__ == '__main__':
print()
print('SmartAPI Remote Test:', SmartAPIRemoteTest.host)
print('-'*70 + '\n')
runmodule(argv=['', '--logging-level=INFO', '-v'])
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,056
|
polyg314/smartAPI
|
refs/heads/master
|
/src/web/api/query_builder.py
|
from biothings.web.api.es.query_builder import ESQueryBuilder as BiothingsESQueryBuilder
import json
class SmartAPIQueryBuilder(BiothingsESQueryBuilder):
def get_query_filters(self):
_filter = None
if self.options.filters:
try:
terms_filter = json.loads(self.options.filters)
if terms_filter:
if len(terms_filter) == 1:
_filter = {"terms": terms_filter}
else:
_filter = [{"terms": {f[0]: f[1]}}
for f in terms_filter.items()]
except:
pass
return _filter
def get_missing_filters(self):
no_archived = {
"term": {
"_meta._archived": "true"
}
}
return no_archived
def _extra_query_types(self, q):
dis_max_query = {
"query": {
"dis_max": {
"queries": [
{
"term": {
"info.title": {
"value": q,
"boost": 2.0
}
}
},
{
"term": {
"server.url": {
"value": q,
"boost": 1.1
}
}
},
{
"term": {
"_id": q,
}
},
{
"query_string": {
"query": q
}
},
{
"query_string": {
"query": q + "*",
"boost": 0.8
}
},
]
}
}
}
return dis_max_query
def _query_GET_query(self, q):
# override as an alternative solution
# see change below
if self._is_user_query():
_query = self._user_query(q)
elif self._is_match_all(q):
_query = self._match_all(q)
elif self._is_random_query(q) and self.allow_random_query:
_query = self._random_query(q)
else:
_query = self._extra_query_types(q)
if not _query:
_query = self._default_query(q)
# previously assigned to _query directly
_query['query'] = self.add_query_filters(_query)
_query = self.queries.raw_query(_query)
_ret = self._return_query_kwargs({'body': _query})
if self.options.fetch_all:
_ret['body'].pop('sort', None)
_ret['body'].pop('size', None)
_ret.update(self.scroll_options)
return _ret
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,057
|
polyg314/smartAPI
|
refs/heads/master
|
/src/web/api/transform.py
|
'''
Validate and transform SmartAPI/OpenAPI v3 metadata for indexing
'''
import base64
import copy
import gzip
import json
import sys
from collections import OrderedDict
import jsonschema
import requests
import yaml
if sys.version_info.major >= 3 and sys.version_info.minor >= 6:
from hashlib import blake2b
else:
from pyblake2 import blake2b # pylint: disable=import-error
# Official oas3 json schema for validation is still in-development.
# For now we us this updated oas3-schema from swagger-editor
OAS3_SCHEMA_URL = 'https://raw.githubusercontent.com/swagger-api/swagger-editor/v3.7.1/src/plugins/json-schema-validator/oas3-schema.yaml'
SWAGGER2_SCHEMA_URL = 'https://raw.githubusercontent.com/swagger-api/swagger-editor/v3.6.1/src/plugins/validate-json-schema/structural-validation/swagger2-schema.js'
# List of root keys that should be indexed in version 2 schema
SWAGGER2_INDEXED_ITEMS = ['info', 'tags', 'swagger', 'host', 'basePath']
# list of major versions of schema that we support
SUPPORTED_SCHEMA_VERSIONS = ['SWAGGER2', 'OAS3']
# This is a separate schema for SmartAPI extensions only
SMARTAPI_SCHEMA_URL = 'https://raw.githubusercontent.com/SmartAPI/smartAPI-Specification/OpenAPI.next/schemas/smartapi_schema.json'
METADATA_KEY_ORDER = ['openapi', 'info', 'servers',
'externalDocs', 'tags', 'security', 'paths', 'components']
def encode_raw(metadata):
'''return encoded and compressed metadata'''
_raw = json.dumps(metadata).encode('utf-8')
_raw = base64.urlsafe_b64encode(gzip.compress(_raw)).decode('utf-8')
return _raw
def decode_raw(raw, sorted=True, as_string=False):
'''if sorted is True, the keys in the decoded dictionary will follow
a defined order.
'''
_raw = gzip.decompress(base64.urlsafe_b64decode(raw)).decode('utf-8')
if as_string:
return _raw
d = json.loads(_raw)
if sorted:
d2 = OrderedDict()
for key in METADATA_KEY_ORDER:
if key in d:
d2[key] = d[key]
for key in d:
if key not in d2:
d2[key] = d[key]
return d2
else:
return d
def polite_requests(url, head=False):
try:
if head:
res = requests.head(url, timeout=5)
else:
res = requests.get(url, timeout=5)
except requests.exceptions.Timeout:
return {"success": False, "error": "URL request is timeout."}
except requests.exceptions.ConnectionError:
return {"success": False, "error": "URL request had a connection error."}
except requests.exceptions.RequestException:
return {"success": False, "error": "Failed to make the request to this URL."}
if res.status_code != 200:
return {"success": False, "error": "URL request returned {}.".format(res.status_code)}
return {"success": True, "response": res}
def get_api_metadata_by_url(url, as_string=False):
_res = polite_requests(url)
if _res.get('success'):
res = _res.get('response')
if as_string:
return res.text
else:
try:
metadata = res.json()
# except json.JSONDecodeError: # for py>=3.5
except ValueError: # for py<3.5
try:
metadata = yaml.load(res.text, Loader=yaml.SafeLoader)
except (yaml.scanner.ScannerError,
yaml.parser.ParserError):
return {"success": False,
"error": "Not a valid JSON or YAML format."}
return metadata
else:
return _res
class APIMetadata:
def __init__(self, metadata):
# get the major version of the schema type
if metadata.get('openapi', False):
self.schema_version = 'OAS' + metadata['openapi'].split('.')[0]
elif metadata.get('swagger', False):
self.schema_version = 'SWAGGER' + metadata['swagger'].split('.')[0]
else:
self.schema_version = None
# set the correct schema validation url
if self.schema_version == 'SWAGGER2':
self.schema_url = SWAGGER2_SCHEMA_URL
else:
self.schema_url = OAS3_SCHEMA_URL
self.get_schema()
self.metadata = metadata
self._meta = self.metadata.pop('_meta', {})
try:
self._meta['ETag'] = requests.get(
self._meta['url']).headers.get(
'ETag', 'I').strip('W/"')
except BaseException:
pass
if self.schema_version == 'SWAGGER2':
self._meta['swagger_v2'] = True
def get_schema(self):
schema = requests.get(self.schema_url).text
if schema.startswith("export default "):
schema = schema[len("export default "):]
try:
self.oas_schema = json.loads(schema)
except:
self.oas_schema = yaml.load(schema, Loader=yaml.SafeLoader)
self.smartapi_schema = requests.get(SMARTAPI_SCHEMA_URL).json()
def encode_api_id(self):
x = self._meta.get('url', None)
if not x:
raise ValueError("Missing required _meta.url field.")
return blake2b(x.encode('utf8'), digest_size=16).hexdigest()
def validate(self, raise_error_on_v2=True):
'''Validate API metadata against JSON Schema.'''
if not self.schema_version or self.schema_version not in SUPPORTED_SCHEMA_VERSIONS:
return {"valid": False, "error": "Unsupported schema version '{}'. Supported versions are: '{}'.".format(
self.schema_version, SUPPORTED_SCHEMA_VERSIONS)}
if raise_error_on_v2 and self.schema_version == 'SWAGGER2':
return {"valid": False, "error": "Found a v2 swagger schema, please convert to v3 for fullest functionality or click the checkbox to proceed with v2 anyway.", "swagger_v2": True}
try:
jsonschema.validate(self.metadata, self.oas_schema)
except jsonschema.ValidationError as e:
err_msg = "'{}': {}".format('.'.join([str(x) for x in e.path]), e.message)
return {"valid": False, "error": "[{}] ".format(self.schema_version) + err_msg}
except Exception as e:
return {"valid": False, "error": "Unexpected Validation Error: {} - {}".format(type(e).__name__, e)}
if self.schema_version == 'OAS3':
try:
jsonschema.validate(self.metadata, self.smartapi_schema)
except jsonschema.ValidationError as e:
err_msg = "'{}': {}".format('.'.join([str(x) for x in e.path]), e.message)
return {"valid": False, "error": "[SmartAPI] " + err_msg}
_warning = ""
_ret = {"valid": True}
else:
_warning = "No SmartAPI extensions supported on Swagger/OpenAPI version 2"
_ret = {"valid": True, "_warning": _warning, "swagger_v2": True}
return _ret
def _encode_raw(self):
'''return encoded and compressed metadata'''
_raw = json.dumps(self.metadata).encode('utf-8')
_raw = base64.urlsafe_b64encode(gzip.compress(_raw)).decode('utf-8')
return _raw
def convert_es(self):
'''convert API metadata for ES indexing.'''
if self.schema_version == 'OAS3':
_d = copy.copy(self.metadata)
_d['_meta'] = self._meta
# convert paths to a list of each path item
_paths = []
for path in _d.get('paths', []):
_paths.append({
"path": path,
"pathitem": _d['paths'][path]
})
if _paths:
_d['paths'] = _paths
else:
# swagger 2 or other, only index limited fields
_d = {"_meta": self._meta}
for key in SWAGGER2_INDEXED_ITEMS:
if key in self.metadata:
_d[key] = self.metadata[key]
# include compressed binary raw metadata as "~raw"
_d["~raw"] = encode_raw(self.metadata)
return _d
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,058
|
polyg314/smartAPI
|
refs/heads/master
|
/src/utils/slack_notification.py
|
import json
import requests
import re
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
try:
from config import SLACK_WEBHOOKS
except ImportError:
SLACK_WEBHOOKS = []
def get_tags(data):
"""Generate array of all the tags listed in the newly registered API"""
tags = []
if('tags' in data):
for item in data['tags']:
tags.append(item['name'])
return tags
def change_link_markdown(description):
"""Change markdown styling of links to match fit Slack Markdown styling
Description text links formatted as [link name](URL), we want <URL|link name>
"""
return re.sub('\[(?P<label>[^\[\]]+)\]\((?P<url>[^()]+)\)', '<\g<url>|\g<label>>', description)
def generate_slack_params(data, res, github_user, webhook_dict):
"""Generate parameters that will be used in slack post request.
In this case, markdown is used to generate formatting that
will show in Slack message
"""
api_title = data["info"]["title"]
# limit API description to 120 characters
api_description = ((data["info"]["description"][:120] + '...')
if len(data["info"]["description"]) > 120
else data["info"]["description"])
api_description = change_link_markdown(api_description)
api_id = res["_id"]
registry_url = f"http://smart-api.info/registry?q={api_id}"
docs_url = f"http://smart-api.info/ui/{api_id}"
api_data = {
"api_title": api_title,
"api_description": api_description,
"registry_url": registry_url,
"docs_url": docs_url,
"github_user": github_user
}
# default markdown
default_block_markdown_template = ("A new API has been registered on SmartAPI.info:\n\n"
"*Title:* {api_title}\n"
"*Description:* {api_description}\n"
"*Registered By:* <https://github.com/{github_user}|{github_user}>\n\n"
"<{registry_url}|View on SmartAPI Registry> - <{docs_url}|View API Documentation>")
# get template - use default if one not provided
block_markdown_tpl = webhook_dict.get("template", default_block_markdown_template)
# fill template with variable values
block_markdown = block_markdown_tpl.format(**api_data)
params = {
"attachments": [{
"color": "#b0e3f9",
"blocks": [{
"type": "section",
"text": {
"type": "mrkdwn",
"text": block_markdown
}
}]
}]
}
return params
def send_slack_msg(data, res, github_user):
"""Make requests to slack to post information about newly registered API.
Notifications will be sent to every
channel/webhook that is not tag specific, or will be sent to
slack if the registered API contains a tag that is also specific
a channel/webhook.
"""
headers = {'content-type': 'application/json'}
data_tags = get_tags(data)
http_client = AsyncHTTPClient()
for x in SLACK_WEBHOOKS:
send_request = False
if('tags' in x):
if(isinstance(x['tags'], str)):
if(x['tags'] in data_tags):
send_request = True
elif(isinstance(x['tags'], list)):
if(bool(set(x['tags']) & set(data_tags))):
send_request = True
else:
send_request = True
if(send_request):
params = generate_slack_params(data, res, github_user, x)
req = HTTPRequest(url=x['webhook'], method='POST', body=json.dumps(params), headers=headers)
http_client = AsyncHTTPClient()
http_client.fetch(req)
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,059
|
polyg314/smartAPI
|
refs/heads/master
|
/src/index.py
|
"""
SmartAPI Web Server Entry Point
> python index.py
"""
import datetime
import logging
import os.path
from tornado.ioloop import IOLoop
from utils.api_monitor import update_uptime_status
from utils.versioning import backup_and_refresh
import config
from biothings.web.index_base import main
from biothings.web.settings import BiothingESWebSettings
WEB_SETTINGS = BiothingESWebSettings(config=config)
def schedule_daily_job():
tomorrow = datetime.datetime.today() + datetime.timedelta(days=1)
midnight = datetime.datetime.combine(tomorrow, datetime.time.min)
IOLoop.current().add_timeout(midnight.timestamp(), daily_job)
def daily_job():
def sync_job():
backup_and_refresh()
update_uptime_status()
IOLoop.current().run_in_executor(None, sync_job)
schedule_daily_job()
if __name__ == '__main__':
(SRC_PATH, _) = os.path.split(os.path.abspath(__file__))
STATIC_PATH = os.path.join(SRC_PATH, 'static')
# IOLoop.current().add_callback(daily_job) # run upon start
schedule_daily_job()
main(WEB_SETTINGS.generate_app_list(),
app_settings={"cookie_secret": config.COOKIE_SECRET},
debug_settings={"static_path": STATIC_PATH},
use_curl=True)
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,060
|
polyg314/smartAPI
|
refs/heads/master
|
/src/tests/local.py
|
'''
SmartAPI Read-Only Test
'''
from nose.core import run
from biothings.tests import TornadoTestServerMixin
from remote import SmartAPIRemoteTest
class SmartAPILocalTest(TornadoTestServerMixin, SmartAPIRemoteTest):
'''
Self contained test class
Starts a Tornado server and perform tests against this server.
'''
__test__ = True # explicitly set this to be a test class
if __name__ == '__main__':
print()
print('SmartAPI Local Test')
print('-'*70 + '\n')
run(argv=['', '--logging-level=INFO', '-v'], defaultTest='local.SmartAPILocalTest')
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,061
|
polyg314/smartAPI
|
refs/heads/master
|
/src/config.py
|
''' SmartAPI Configuration '''
# pylint: disable=wildcard-import, unused-wildcard-import, unused-import
from biothings.web.settings.default import *
from config_key import *
from web.api.handlers import APP_LIST as api_app_list
from web.api.query_builder import SmartAPIQueryBuilder
from web.handlers import APP_LIST as web_app_list
# *****************************************************************************
# Credentials
# *****************************************************************************
# Define in config_key.py:
# COOKIE_SECRET = '<Any Random String>'
# GITHUB_CLIENT_ID = '<your Github application Client ID>'
# GITHUB_CLIENT_SECRET = '<your Github application Client Secret>'
# *****************************************************************************
# Elasticsearch
# *****************************************************************************
ES_INDEX = 'smartapi_oas3'
ES_DOC_TYPE = 'api'
# *****************************************************************************
# Tornado URL Patterns
# *****************************************************************************
def add_apps(prefix='', app_list=None):
'''
Add prefix to each url handler specified in app_list.
add_apps('test', [('/', testhandler,
('/test2', test2handler)])
will return:
[('/test/', testhandler,
('/test/test2', test2handler)])
'''
if not app_list:
app_list = []
if prefix:
return [('/'+prefix+url, handler) for url, handler in app_list]
else:
return app_list
APP_LIST = []
APP_LIST += add_apps('', web_app_list)
APP_LIST += add_apps('api', api_app_list)
# *****************************************************************************
# Biothings Query Settings
# *****************************************************************************
# Subclass of biothings.web.api.es.query_builder.ESQueryBuilder
ES_QUERY_BUILDER = SmartAPIQueryBuilder
# Keyword Argument Control
QUERY_GET_ESQB_KWARGS.update({'filters': {'default': None, 'type': str}})
# Header Strings
ACCESS_CONTROL_ALLOW_METHODS = 'GET,POST,PUT,DELETE,OPTIONS'
# Only affect API endpoints
DISABLE_CACHING = True
# Heavy operation. Enable on small db only.
ALLOW_RANDOM_QUERY = True
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,062
|
polyg314/smartAPI
|
refs/heads/master
|
/src/utils/versioning.py
|
'''
Backup es index to S3 and refresh
'''
import logging
from tornado.ioloop import IOLoop
from web.api.es import ESQuery
def backup_and_refresh():
'''
Run periodically in the main event loop
'''
esq = ESQuery()
try:
esq.backup_all(aws_s3_bucket='smartapi')
except:
logging.exception("Backup failed.")
try:
esq.refresh_all(dryrun=False)
except:
logging.exception("Refresh failed.")
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,063
|
polyg314/smartAPI
|
refs/heads/master
|
/src/web/handlers.py
|
import json
import logging
import os
import sys
import tornado.gen
import tornado.httpclient
import tornado.httpserver
import tornado.ioloop
import tornado.web
import torngithub
from jinja2 import Environment, FileSystemLoader
from tornado.httputil import url_concat
from torngithub import json_decode, json_encode
from web.api.es import ESQuery
from biothings.web.api.helper import BaseHandler as BioThingsBaseHandler
log = logging.getLogger("smartapi")
src_path = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]
if src_path not in sys.path:
sys.path.append(src_path)
TEMPLATE_PATH = os.path.join(src_path, 'templates/')
AVAILABLE_TAGS = ['translator', 'nihdatacommons']
# your Github application Callback
GITHUB_CALLBACK_PATH = "/oauth"
GITHUB_SCOPE = ""
# Docs: http://docs.python-guide.org/en/latest/scenarios/web/
# Load template file templates/site.html
templateLoader = FileSystemLoader(searchpath=TEMPLATE_PATH)
templateEnv = Environment(loader=templateLoader, cache_size=0)
class BaseHandler(BioThingsBaseHandler):
def get_current_user(self):
user_json = self.get_secure_cookie("user")
if not user_json:
return None
return json_decode(user_json)
class MainHandler(BaseHandler):
def get(self):
slug = self.request.host.split(".")[0]
# print("Host: {} - Slug: {}".format(self.request.host, slug))
if slug.lower() not in ['www', 'dev', 'smart-api']:
# try to get a registered subdomain/tag
esq = ESQuery()
api_id = esq.get_api_id_from_slug(slug)
if api_id:
swaggerUI_file = "smartapi-ui.html"
swagger_template = templateEnv.get_template(swaggerUI_file)
swagger_output = swagger_template.render(apiID=api_id)
self.write(swagger_output)
return
index_file = "index.html"
index_template = templateEnv.get_template(index_file)
index_output = index_template.render()
self.write(index_output)
class UserInfoHandler(BaseHandler):
def get(self):
current_user = self.get_current_user() or {}
for key in ['access_token', 'id']:
if key in current_user:
del current_user[key]
self.return_json(current_user)
class LoginHandler(BaseHandler):
def get(self):
xsrf = self.xsrf_token
login_file = "login.html"
login_template = templateEnv.get_template(login_file)
path = GITHUB_CALLBACK_PATH
_next = self.get_argument("next", "/")
if _next != "/":
path += "?next={}".format(_next)
login_output = login_template.render(path=path, xsrf=xsrf)
self.write(login_output)
class AddAPIHandler(BaseHandler, torngithub.GithubMixin):
# def get(self):
# self.write("Hello, world")
# self.write(html_output)
# template.render(list=movie_list,
# title="Here is my favorite movie list")
def get(self):
if self.current_user:
# self.write('Login User: ' + self.current_user["name"]
# + '<br> Email: ' + self.current_user["email"]
# + ' <a href="/logout">Logout</a>')
template_file = "reg_form.html"
reg_template = templateEnv.get_template(template_file)
reg_output = reg_template.render()
self.write(reg_output)
else:
path = '/login'
_next = self.get_argument("next", self.request.path)
if _next != "/":
path += "?next={}".format(_next)
self.redirect(path)
class LogoutHandler(BaseHandler):
def get(self):
self.clear_cookie("user")
self.redirect(self.get_argument("next", "/"))
class GithubLoginHandler(BaseHandler, torngithub.GithubMixin):
@tornado.gen.coroutine
def get(self):
# we can append next to the redirect uri, so the user gets the
# correct URL on login
redirect_uri = url_concat(self.request.protocol +
"://" + self.request.host +
GITHUB_CALLBACK_PATH,
{"next": self.get_argument('next', '/')})
# if we have a code, we have been authorized so we can log in
if self.get_argument("code", False):
user = yield self.get_authenticated_user(
redirect_uri=redirect_uri,
client_id=self.web_settings.GITHUB_CLIENT_ID,
client_secret=self.web_settings.GITHUB_CLIENT_SECRET,
code=self.get_argument("code")
)
if user:
log.info('logged in user from github: ' + str(user))
self.set_secure_cookie("user", json_encode(user))
else:
self.clear_cookie("user")
self.redirect(self.get_argument("next", "/"))
return
# otherwise we need to request an authorization code
yield self.authorize_redirect(
redirect_uri=redirect_uri,
client_id=self.web_settings.GITHUB_CLIENT_ID,
extra_params={"scope": GITHUB_SCOPE, "foo": 1}
)
class RegistryHandler(BaseHandler):
def get(self, tag=None):
template_file = "smart-registry.html"
# template_file = "/smartapi/dist/index.html"
reg_template = templateEnv.get_template(template_file)
# author filter parsing
if self.get_argument('owners', False):
owners = [x.strip().lower()
for x in self.get_argument('owners').split(',')]
else:
owners = []
# special url tag
if tag:
if tag.lower() in AVAILABLE_TAGS:
# print("tags: {}".format([tag.lower()]))
reg_output = reg_template.render(Context=json.dumps(
{"Tags": [tag.lower()],
"Special": True,
"Owners": owners}))
else:
raise tornado.web.HTTPError(404)
# typical query filter tags
elif self.get_argument('tags', False) or \
self.get_argument('owners', False):
tags = [x.strip().lower()
for x in self.get_argument('tags', "").split(',')]
# print("tags: {}".format(tags))
reg_output = reg_template.render(
Context=json.dumps(
{"Tags": tags,
"Special": False,
"Owners": owners}))
else:
reg_output = reg_template.render(Context=json.dumps({}))
self.write(reg_output)
class DocumentationHandler(BaseHandler):
def get(self):
doc_file = "documentation.html"
documentation_template = templateEnv.get_template(doc_file)
documentation_output = documentation_template.render()
self.write(documentation_output)
class DashboardHandler(BaseHandler):
def get(self):
doc_file = "dashboard.html"
dashboard_template = templateEnv.get_template(doc_file)
dashboard_output = dashboard_template.render()
self.write(dashboard_output)
class SwaggerUIHandler(BaseHandler):
def get(self, yourApiID=None):
if not yourApiID:
if self.get_argument('url', False):
api_id = self.get_argument('url').split('/')[-1]
self.redirect('/ui/{}'.format(api_id), permanent=True)
else:
raise tornado.web.HTTPError(404)
return
swaggerUI_file = "smartapi-ui.html"
swagger_template = templateEnv.get_template(swaggerUI_file)
swagger_output = swagger_template.render(apiID=yourApiID)
self.write(swagger_output)
class BrandingHandler(BaseHandler):
def get(self):
doc_file = "brand.html"
branding_template = templateEnv.get_template(doc_file)
branding_output = branding_template.render()
self.write(branding_output)
class GuideHandler(BaseHandler):
def get(self):
doc_file = "guide.html"
guide_template = templateEnv.get_template(doc_file)
guide_output = guide_template.render()
self.write(guide_output)
class APIEditorHandler(BaseHandler):
def get(self, yourApiID=None):
if not yourApiID:
if self.get_argument('url', False):
api_id = self.get_argument('url').split('/')[-1]
self.redirect('/editor/{}'.format(api_id), permanent=True)
else:
# raise tornado.web.HTTPError(404)
swaggerEditor_file = "editor.html"
swagger_template = templateEnv.get_template(swaggerEditor_file)
swagger_output = swagger_template.render(
Context=json.dumps({"Id": '', "Data": False}))
self.write(swagger_output)
return
swaggerEditor_file = "editor.html"
swagger_template = templateEnv.get_template(swaggerEditor_file)
swagger_output = swagger_template.render(
Context=json.dumps({"Id": yourApiID, "Data": True}))
self.write(swagger_output)
class AboutHandler(BaseHandler):
def get(self):
doc_file = "about.html"
about_template = templateEnv.get_template(doc_file)
about_output = about_template.render()
self.write(about_output)
class PrivacyHandler(BaseHandler):
def get(self):
doc_file = "privacy.html"
privacy_template = templateEnv.get_template(doc_file)
privacy_output = privacy_template.render()
self.write(privacy_output)
class FAQHandler(BaseHandler):
def get(self):
doc_file = "faq.html"
faq_template = templateEnv.get_template(doc_file)
faq_output = faq_template.render()
self.write(faq_output)
class TemplateHandler(BaseHandler):
def initialize(self, filename, status_code=200, env=None):
self.filename = filename
self.status = status_code
def get(self, **kwargs):
template = self.env.get_template(self.filename)
output = template.render(Context=json.dumps(kwargs))
self.set_status(self.status)
self.write(output)
class PortalHandler(BaseHandler):
def get(self, portal=None):
portals = ['translator']
template_file = "portal.html"
reg_template = templateEnv.get_template(template_file)
if portal in portals:
reg_output = reg_template.render(Context=json.dumps(
{"portal": portal}))
else:
raise tornado.web.HTTPError(404)
self.write(reg_output)
class MetaKGHandler(BaseHandler):
def get(self):
print('META KG')
doc_file = "metakg.html"
template = templateEnv.get_template(doc_file)
output = template.render(Context=json.dumps(
{"portal": 'translator'}))
self.write(output)
APP_LIST = [
(r"/", MainHandler),
(r"/user/?", UserInfoHandler),
(r"/add_api/?", AddAPIHandler),
(r"/login/?", LoginHandler),
(GITHUB_CALLBACK_PATH, GithubLoginHandler),
(r"/logout/?", LogoutHandler),
(r"/registry/(.+)/?", RegistryHandler),
(r"/registry/?", RegistryHandler),
(r"/documentation/?", DocumentationHandler),
(r"/dashboard/?", DashboardHandler),
(r"/ui/(.+)/?", SwaggerUIHandler),
(r"/ui/?", SwaggerUIHandler),
(r"/branding/?", BrandingHandler),
(r"/guide/?", GuideHandler),
(r"/editor/(.+)/?", APIEditorHandler),
(r"/editor/?", APIEditorHandler),
(r"/about/?", AboutHandler),
(r"/faq/?", FAQHandler),
(r"/privacy/?", PrivacyHandler),
# (r"/portal/?", TemplateHandler, {"filename": "registry.html"}),
(r"/portal/translator/metakg/?", MetaKGHandler),
(r"/portal/([^/]+)/?", PortalHandler),
]
|
{"/src/web/api/es.py": ["/src/web/api/transform.py"], "/src/web/api/handlers.py": ["/src/web/api/es.py", "/src/web/api/transform.py"]}
|
19,072
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/example11.py
|
from RobotArm import RobotArm
robotArm = RobotArm('exercise 11')
# Jouw python instructies zet je vanaf hier:
kleur = "white"
# Na jouw code wachten tot het sluiten van de window:
for blok in range(1):
for blok in range(9):
robotArm.moveRight();
for blok in range(15):
robotArm.grab()
kleur = robotArm.scan() # de command robotArm.scan controleert of he blokje de gewenste kleur is
print(kleur)
if kleur == "white":
robotArm.moveRight();
robotArm.drop()
robotArm.moveLeft();
else:
robotArm.drop()
robotArm.moveLeft();
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,073
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/example10.py
|
from RobotArm import RobotArm
robotArm = RobotArm('exercise 10')
# Jouw python instructies zet je vanaf hier:
afstand = 10
# Na jouw code wachten tot het sluiten van de window:
for blok in range(5):
afstand = afstand - 1
for blok in range(afstand):
robotArm.grab()
robotArm.moveRight();
robotArm.drop()
for blok in range(afstand):
robotArm.moveLeft();
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,074
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/example.py
|
from RobotArm import RobotArm
robotArm = RobotArm('exercise 1')
# Jouw python instructies zet je vanaf hier:
# Na jouw code wachten tot het sluiten van de window:
robotArm.wait()
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,075
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/example13.py
|
from RobotArm import RobotArm
# Let op: hier start het anders voor een random level:
robotArm = RobotArm()
robotArm.randomLevel(1,7)
# Jouw python instructies zet je vanaf hier:
# Na jouw code wachten tot het sluiten van de window:
for blok in range(0, 9):
robotArm.grab()
kleur = robotArm.scan()
print(kleur)
if kleur != "":
for blokje in range(0, blok + 1):
robotArm.moveRight();
robotArm.drop()
for blokje in range(0, blok + 1):
robotArm.moveLeft();
print("")
elif kleur == "":
break
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,076
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/tempCodeRunnerFile.py
|
robotArm.moveRight();
robotArm.drop()
robotArm.moveLeft();
else:
robotArm.drop()
robotArm.moveLeft();
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,077
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/example8.py
|
from RobotArm import RobotArm
robotArm = RobotArm('exercise 8')
# Jouw python instructies zet je vanaf hier:
blok = 1
# Na jouw code wachten tot het sluiten van de window:
for blok in range (7):
for blok in range (9):
robotArm.moveRight();
robotArm.grab()
robotArm.drop()
for blok in range (8):
robotArm.moveLeft();
robotArm.grab()
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,078
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/example7.py
|
from RobotArm import RobotArm
robotArm = RobotArm('exercise 7')
robotArm.speed = 2
# Jouw python instructies zet je vanaf hier
blokje=1
# Na jouw code wachten tot het sluiten van de window:
for blokje in range(5):
for blokje in range(6):
robotArm.moveRight();
robotArm.grab()
robotArm.moveLeft();
robotArm.drop()
for blokje in range(2):
robotArm.moveRight();
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,079
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/RobotArm.py
|
import pygame # install in terminal with: pip install pygame
import sys
import random
# RobotArm class ################################################
#
# An object of this class...
#
# lets you load and display a yard with stacks of colored boxes
# you can load a predefined level at the creation
# lets you program the movement of boxes and scan their colors
# lets you inspect the yard for debugging purposes
#
# supported colors are: white, green, red, blue and yellow
#
# ######## methods for public use:
# moveRight()
# moves the robotarm one stack position to the right
# returns True if succeeded, returns False if not possible
#
# moveLeft()
# moves the robotarm one stack position to the left
# returns True if succeeded, returns False if not possible
#
# grab()
# lets the robotarm grab a box from the stack if there is one
# returns True if succeeded, returns False if not possible
#
# drop()
# lets the robotarm drop its box to the stack if not full
# returns True if succeeded, returns False if not possible
#
# scan()
# returns the color of the box at the robotarm
#
# wait(operator)
# waits for the the program window to be closed
# operator is an optional function with a parameter: events {list of events}
# the operator must/can handle each event in events
#
# operate()
# make the robotarm operate on keyboard-keys: LEFT, RIGHT and DOWN
#
# ######## creating and loading levels ########
#
# loadLevel(levelName)
# loads a predefined level for levelName {string}
# returns True if succeeded, returns False if failed
#
# loadMyLevel(yard, levelName)
# loads a self made yard with a self made levelName {string}
# where yard is a list of stacks each stack is a list of colors
# box colors example of a yard: [['red','green'],['red','blue'],[],['green']]
# returns True if succeeded, returns False if errors found, but sanitized
#
# randomLevel(stacks, layers)
# loads a simple random level with stacks and layers
#
# loadRandomLevel(requirements )
# loads a random level with optional requirements
# requirements dictionary can contain key-values:
# maxStacks {int}: number of random stacks to provide
# minBoxes {int}: minmum number of boxes provided per stack
# maxBoxes {int}: maximum number of boxes provided per stack
# maxColors {int}: maximum number of colors provided in the yard
# requiredColors {list of string}: list of required colors
# levelName {string}: name of the level
#
# inspectYard()
# prints the yard data, for inspection during debugging
#
# ###########################################################
class RobotArm:
_colors = [
{"name": 'white', 'code': (255,255,255)},
{"name": 'red', 'code': (255,0,0)},
{"name": 'green', 'code': (0,150,0)},
{"name": 'blue', 'code': (0,0,255)},
{"name": 'yellow', 'code': (255,255,0)}
]
_defaultlevels = [
{'name': 'exercise 1', 'yard' : [[],["red"]]},
{'name': 'exercise 2', 'yard' : [["blue"],[],[],[],["blue"],[],[],["blue"]]},
{'name': 'exercise 3', 'yard' : [["white","white","white","white"]]},
{'name': 'exercise 4', 'yard' : [["blue","white", "green"]]},
{'name': 'exercise 5', 'yard' : [[],["red","red","red","red","red","red","red"]]},
{'name': 'exercise 6', 'yard' : [["red"],["blue"],["white"],["green"],["green"],["blue"],["red"],["white"]]},
{'name': 'exercise 7', 'yard' : [[],["blue","blue","blue","blue","blue","blue"], [],["blue","blue","blue","blue","blue","blue"], [],["blue","blue","blue","blue","blue","blue"], [],["blue","blue","blue","blue","blue","blue"],[],["blue","blue","blue","blue","blue","blue"]]},
{'name': 'exercise 8', 'yard' : [[],["red","red","red","red","red","red","red"]]},
{'name': 'exercise 9', 'yard' : [["blue"],["green", "green"],["white","white","white"],["red","red","red","red"]]},
{'name': 'exercise 10', 'yard' : [["green"],["blue"],["white"],["red"],["blue"]]},
{'name': 'exercise 11', 'yard' : {'maxStacks': 9, 'minBoxes': 1, 'maxBoxes': 1, 'requiredColors': ['white'], 'maxColors': 4}},
{'name': 'exercise 12', 'yard' : {'maxStacks': 9, 'minBoxes': 1, 'maxBoxes': 1, 'requiredColors': ['red'], 'maxColors': 4}},
{'name': 'exercise 13', 'yard' : [["green"],["green"],["green"],["blue"],["white"],["green"],["red"],["red"],["blue"],["green"]]},
{'name': 'exercise 14', 'yard' : [[],["green"],["white"],["green","white"],["red","white"],["white","white"],["blue"],["blue","blue","blue"],["blue", "green", "green"],["red"]]},
{'name': 'exercise 15', 'yard' : [[],["blue"],[],["blue"],["white"],[],["red"],["green"],["red"],["green"]]}
]
_speeds = [{'fps': 100,'step': 1},{'fps': 150,'step': 2},{'fps': 250,'step': 4},{'fps': 400,'step': 5},{'fps': 500,'step': 10},{'fps': 500,'step': 20}]
EMPTY = ''
_backgroundColor = (200,200,200)
_penColor = (0,0,0)
_maxStacks = 10
_maxLayers = 7
_boxHeight = 29
_boxWidth = 29
_penWidth = 1
_boxMargin = 2
_armTopHeight = 15
_bottomMargin = 2
_idleAnimationTime = 300
_screenMargin = 3
_eventSleepTime = 300
_eventActiveCycles = 100
_iconImage = 'robotarm.ico'
def __init__(self, levelName = ''):
self._color = self.EMPTY
self._stack = 0
self._yardBottom = self._armTopHeight + (self._maxLayers + 1) * self._boxSpaceHeight() + self._penWidth
self._armHeight = self._armTopHeight
self._armX = 0
self.speed = 1
self._yard = []
pygame.init()
self._clock = pygame.time.Clock()
self._screenWidth = self._stackX(self._maxStacks) + self._screenMargin
self._screenHeight = self._layerY(-1) + self._bottomMargin + 2 * self._screenMargin
self._screen = pygame.display.set_mode((self._screenWidth, self._screenHeight))
try:
programIcon = pygame.image.load(self._iconImage)
pygame.display.set_icon(programIcon)
except:
print(self._iconImage + ' not found')
# Load level at creation
if levelName != '':
self.loadLevel(levelName)
########### ANIMATION METHODS ###########
def _getColorCode(self, name):
for c in self._colors:
if c['name'] == name:
return c['code']
return False
def _checkSpeed(self):
speedInvalid = False
if type(self.speed) is not int:
speedInvalid = True
if not (self.speed in range(len(self._speeds))):
speedInvalid = True
if speedInvalid:
self.speed = 0 # reset speed to zero
print('speed must be an integer between 0 and ' + str(len(self._speeds)-1))
def _drawBoxAtPosition(self, x, y, color):
pygame.draw.rect(self._screen, color, (x, y, self._boxWidth, self._boxHeight))
pygame.draw.rect(self._screen, self._penColor, (x, y, self._boxWidth, self._boxHeight), self._penWidth)
def _boxSpaceWidth(self):
return (self._boxWidth + 2 * self._boxMargin) + self._penWidth
def _stackX(self, stack):
return self._screenMargin + self._boxMargin + stack * self._boxSpaceWidth() + self._penWidth
def _boxSpaceHeight(self):
return (self._boxHeight - self._penWidth)
def _layerY(self,layer):
return self._yardBottom - (layer + 1) * self._boxSpaceHeight() - self._screenMargin
def _drawBox(self, stack, layer):
x = self._stackX(stack)
y = self._layerY(layer)
color = self._getColorCode(self._yard[stack][layer])
self._drawBoxAtPosition(x,y,color)
def _drawStack(self, stack):
for l in range(len(self._yard[stack])):
self._drawBox(stack,l)
x = self._stackX(stack) - self._boxMargin - self._penWidth
y = self._layerY(-1) + self._bottomMargin
pygame.draw.lines(self._screen, self._penColor, False, [(x, y - 5), (x, y), (x + self._boxSpaceWidth(), y), (x + self._boxSpaceWidth(), y - 5)])
def _drawArm(self):
xm = self._armX + int(self._boxSpaceWidth()/2) - self._boxMargin
pygame.draw.line(self._screen, self._penColor, (xm, 2), (xm, self._armHeight - 2))
pygame.draw.lines(self._screen, self._penColor, False, [
(self._armX - self._boxMargin, self._armHeight + 2),
(self._armX - self._boxMargin, self._armHeight - 2),
(self._armX + self._boxWidth + self._penWidth, self._armHeight - 2),
(self._armX + self._boxWidth + self._penWidth , self._armHeight + 2)])
if self._color > '':
self._drawBoxAtPosition(self._armX,self._armHeight,self._getColorCode(self._color))
def _drawState(self):
pygame.display.set_caption('Robotarm: ' + self._levelName)
self._screen.fill(self._backgroundColor)
for c in range(len(self._yard)):
self._drawStack(c)
self._drawArm()
def _animate(self, *args):
self._checkSpeed()
self._armX = self._stackX(self._stack)
if (args[0] == 'down'):
self._armHeight = self._armTopHeight
targetLayer = len(self._yard[self._stack])
if self._color == '':
targetLayer -= 1
targetHeight = self._layerY(targetLayer)
elif (args[0] == 'left'):
targetX = self._stackX(self._stack - 1)
elif (args[0] == 'right'):
targetX = self._stackX(self._stack + 1)
ready = False
while not ready:
if (args[0] == 'idle'):
ready = True
elif (args[0] == 'down'):
ready = self._armHeight == targetHeight
elif (args[0] == 'up'):
ready = self._armHeight == self._armTopHeight
elif (args[0] == 'left') or (args[0] == 'right'):
ready = self._armX == targetX
for event in pygame.event.get():
self.checkCloseEvent(event)
self._drawState()
pygame.display.update()
self._clock.tick(self._speeds[self.speed]['fps'])
if (args[0] == 'down'):
self._armHeight += self._speeds[self.speed]['step']
if self._armHeight > targetHeight:
self._armHeight = targetHeight
elif (args[0] == 'up'):
self._armHeight -= self._speeds[self.speed]['step']
if self._armHeight < self._armTopHeight:
self._armHeight = self._armTopHeight
elif (args[0] == 'left'):
self._armX -= self._speeds[self.speed]['step']
if self._armX < targetX:
self._armX = targetX
elif (args[0] == 'right'):
self._armX += self._speeds[self.speed]['step']
if self._armX > targetX:
self._armX = targetX
elif (args[0] == 'idle'):
pygame.time.delay(self._idleAnimationTime)
########### ROBOTARM MANIPULATION ###########
def moveRight(self):
success = False
if self._stack < self._maxStacks - 1:
self._animate('right')
self._stack += 1
success = True
return success
def moveLeft(self):
success = False
if self._stack > 0:
self._animate('left')
self._stack -= 1
success = True
return success
def grab(self):
success = False
if self._color == self.EMPTY:
self._animate('down')
if len(self._yard[self._stack]) > 0:
self._color = self._yard[self._stack][-1]
self._yard[self._stack].pop(-1)
success = True
self._animate('up')
return success
def drop(self):
success = False
if self._color != self.EMPTY:
if len(self._yard[self._stack]) < self._maxLayers:
self._animate('down')
self._yard[self._stack].append(self._color)
self._color = self.EMPTY
self._animate('up')
success = True
return success
def scan(self):
return self._color
########### LEVEL & YARD lOADING & CREATION ###########
def _checkYard(self,yard):
success = True
if type(yard) is not list:
yard = []
success = False
for s in range(len(yard)):
if type(yard[s]) is not list:
yard[s] = []
success = False
for c in range(len(yard[s])):
if self._getColorCode(yard[s][c]) == False:
yard[s][c] = 'white'
success = False
return {'yard' : yard, 'success' : success}
def loadMyLevel(self, yard, levelName = 'unknown level'):
result = self._checkYard(yard)
self._yard = result['yard'] # sanitized yard
success = result['success'] # where there errors?
while len(self._yard) < self._maxStacks:
self._yard.append([])
self._levelName = levelName
self._animate('idle')
return success
def loadLevel(self, levelName):
success = False
for level in self._defaultlevels:
if levelName == level['name']:
if type(level['yard']) is dict:
level['yard']['levelName'] = levelName
self.loadRandomLevel(level['yard'])
else:
self.loadMyLevel(level['yard'], levelName)
success = True
if not success:
self.loadMyLevel([])
return success
def _requiredColorsFound(self, yard, requiredColors):
colors = []
for stack in yard:
for color in stack:
colors.append(color)
for color in requiredColors:
if colors.count(color) == 0:
return False
return True
def _createRandomYard(self, maxStacks, minBoxes, maxBoxes, colors, maxColors, requiredColors):
yard = []
while len(yard) == 0 or not self._requiredColorsFound(yard, requiredColors):
yard = []
for l in range(maxStacks):
random.seed()
stack = []
height = random.randint(minBoxes, maxBoxes)
for b in range(height):
color = colors[random.randint(0,len(colors)-1)]
stack.append(color)
yard.append(stack)
return yard
def _randomColors(self, requiredColors, maxColors):
colors = []
for color in requiredColors:
if not color in colors:
colors.append(color)
while len(colors) < maxColors:
color = self._colors[random.randint(0,len(self._colors)-1)]['name']
if not color in colors:
colors.append(color)
return colors
def loadRandomLevel(self, requirements = {}):
maxStacks = requirements['maxStacks'] if 'maxStacks' in requirements else 6
maxStacks = self._maxStacks if maxStacks > self._maxStacks else maxStacks
minBoxes = requirements['minBoxes'] if 'minBoxes' in requirements else 1
maxBoxes = requirements['maxBoxes'] if 'maxBoxes' in requirements else 3
maxBoxes = self._maxLayers if maxBoxes > self._maxLayers else maxBoxes
requiredColors = requirements['requiredColors'] if 'requiredColors' in requirements else []
levelName = requirements['levelName'] if 'levelName' in requirements else 'random level'
maxColors = requirements['maxColors'] if 'maxColors' in requirements else 4
colors = self._randomColors(requiredColors, maxColors)
myYard = self._createRandomYard(maxStacks, minBoxes, maxBoxes, colors, maxColors, requiredColors)
self.loadMyLevel(myYard, levelName)
def randomLevel(self, stacks, layers):
self.loadRandomLevel({'maxStacks': stacks, 'maxBoxes': layers})
def inspectYard(self):
print(self._yard)
########### EVENT HANDLING ###########
def checkCloseEvent(self,event):
if event.type == pygame.QUIT:
sys.exit()
def _defaultHandler(self, events):
for event in events:
self.checkCloseEvent(event)
def wait(self, handler = False):
cycle = 0
while True:
events = pygame.event.get() # get latest events
if callable(handler):
handler(events)
self._defaultHandler(events)
if len(events) > 0: # events happened?
cycle = 0 # stay awake and alert
cycle += 1 # prepare for sleep
if cycle > self._eventActiveCycles: # after 30 cycles
pygame.time.delay(self._eventSleepTime) # go asleep for 300 milliseconds, give the processor some rest
cycle = 0 # wake up for events during sleep
def _operator(self, instructions):
for instruction in instructions:
if instruction.type == pygame.KEYDOWN:
if instruction.key == pygame.K_LEFT:
self.moveLeft()
if instruction.key == pygame.K_RIGHT:
self.moveRight()
if instruction.key == pygame.K_DOWN:
if self.scan() == '':
self.grab()
else:
self.drop()
def operate(self):
self.wait(self._operator)
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,080
|
AkashRamlal1/robotarm
|
refs/heads/main
|
/example12.py
|
from RobotArm import RobotArm
robotArm = RobotArm('exercise 12')
# Jouw python instructies zet je vanaf hier:
kleur = "red"
# Na jouw code wachten tot het sluiten van de window:
for blok in range(9):
robotArm.moveRight();
for blok in range(9): # hoeveel blokken zijn er? geen 27!
robotArm.grab()
kleur = robotArm.scan()
print(kleur)
if kleur == "red":
for i in range(blok + 2): # gebruik hier niet de var blok
robotArm.moveRight();
robotArm.drop()
for i in range(blok + 3):
robotArm.moveLeft()
else:
robotArm.drop()
robotArm.moveLeft();
|
{"/example11.py": ["/RobotArm.py"], "/example10.py": ["/RobotArm.py"], "/example.py": ["/RobotArm.py"], "/example13.py": ["/RobotArm.py"], "/example8.py": ["/RobotArm.py"], "/example7.py": ["/RobotArm.py"], "/example12.py": ["/RobotArm.py"]}
|
19,095
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/wrapper.py
|
# For profiling with Scalene:
# scalene wrapper.py process_revo
from runpy import run_module
run_module("eo_dicts.cli", run_name="__main__")
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,096
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/search.py
|
import sqlite3
import os
import humanize
from .utils import output_dir
def search_multiple(*words: str) -> None:
for word in words:
search(word)
def search(word: str) -> None:
db_filename = os.path.join(output_dir(), "vortaro.db")
conn = sqlite3.connect(db_filename)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
for row in cursor.execute(
"""
SELECT *
FROM words w
LEFT JOIN definitions d ON (w.definition_id = d.id)
WHERE word = ?
""",
(word,),
):
for field, value in dict(row).items():
print("%s: %s" % (field, repr(value)))
print("")
finally:
cursor.close()
conn.close()
def stats() -> None:
db_filename = os.path.join(output_dir(), "vortaro.db")
conn = sqlite3.connect(db_filename)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM version")
print("Version:", cursor.fetchone()[0])
file_size = os.path.getsize(db_filename)
print("Size:", humanize.naturalsize(file_size), "-", file_size)
cursor.execute("SELECT COUNT(*) FROM words")
print("Words:", cursor.fetchone()[0])
cursor.execute("SELECT COUNT(*) FROM definitions")
print("Definitions:", cursor.fetchone()[0])
cursor.execute("SELECT COUNT(*) FROM languages")
print("Languages:", cursor.fetchone()[0])
cursor.execute("SELECT COUNT(*) FROM translations_es")
translations_es = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM translations_en")
translations_en = cursor.fetchone()[0]
print("Translations:")
print("\tEnglish:", translations_en)
print("\tSpanish:", translations_es)
finally:
cursor.close()
conn.close()
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,097
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/utils.py
|
import xml.etree.ElementTree as ET
import os
from typing import Optional, Iterator, TypeVar, Iterable
T = TypeVar("T")
MAPPING = {
"C": "Ĉ",
"G": "Ĝ",
"H": "Ĥ",
"J": "Ĵ",
"S": "Ŝ",
"U": "Ŭ",
"c": "ĉ",
"g": "ĝ",
"h": "ĥ",
"j": "ĵ",
"s": "ŝ",
"u": "ŭ",
}
def add_hats(word: str) -> str:
if not word or len(word) == 1:
return word
res = ""
pos = 0
while pos < len(word) - 1:
char = word[pos]
if char in MAPPING.keys() and word[pos + 1] in ("x", "X"):
res += MAPPING[char]
pos += 2
else:
res += char
pos += 1
if pos == len(word) - 1:
res += word[-1]
return res
def get_languages() -> list[dict[str, Optional[str]]]:
base_dir = os.path.dirname(__file__)
xml_path = os.path.join(base_dir, "..", "revo", "cfg", "lingvoj.xml")
tree = ET.parse(xml_path)
langs = tree.findall("lingvo")
alphabet = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz/-"
# normal sort puts ĉ, ĝ,... at the end
langs = sorted(langs, key=lambda x: [alphabet.index(c) for c in (x.text or "")])
return [{"code": lang.get("kodo"), "name": lang.text} for lang in langs]
def get_disciplines() -> dict[str, Optional[str]]:
base_dir = os.path.dirname(__file__)
xml_path = os.path.join(base_dir, "..", "revo", "cfg", "fakoj.xml")
tree = ET.parse(xml_path)
return {node.get("kodo") or "": node.text for node in tree.findall("fako")}
def list_languages() -> None:
langs = get_languages()
for n, lang in enumerate(langs, 1):
print(n, lang["code"], lang["name"])
def letter_enumerate(iterable: Iterable[T]) -> Iterator[tuple[str, T]]:
for n, elem in enumerate(iterable):
yield (chr(ord("a") + n), elem)
def output_dir() -> str:
return os.path.join(os.path.dirname(__file__), "..", "output")
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,098
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/cli.py
|
import fire
from . import process_revo
from .utils import list_languages
from .search import search_multiple, stats
from typing import Optional
class Vortaro(object):
def show_languages(self):
list_languages()
def search(self, *words: str):
search_multiple(*words)
def stats(self):
stats()
def process_revo(
self,
word: Optional[str] = None,
xml_file: Optional[str] = None,
output_db: str = "vortaro.db",
limit: Optional[int] = None,
verbose: bool = False,
dry_run: bool = False,
min_entries_to_include_lang: int = 100,
):
process_revo.main(
word,
xml_file,
output_db,
limit,
verbose,
dry_run,
min_entries_to_include_lang,
)
def main():
fire.Fire(Vortaro)
if __name__ == "__main__":
main()
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,099
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/tests/test_parser.py
|
from ..parser.revo import Art, Snc, Dif, Drv, Subart, Refgrp
from lxml import etree
import pytest
@pytest.fixture
def parser():
return lambda xml: etree.fromstring(xml)
def test_set_parent(parser):
xml = """<art>
<kap>-<rad>aĉ</rad>/</kap>
<subart>
<drv><kap>-<tld/></kap></drv>
</subart>
</art>"""
art = Art(parser(xml))
for tag in art.children:
assert tag.parent == art
def test_article_kap(parser):
xml = """<art>
<kap>
<ofc>1</ofc>
-<rad>aĉ</rad>/ <fnt><bib>PV</bib></fnt>
</kap>
</art>"""
assert Art(parser(xml)).kap == ("aĉ", "/")
def test_article_no_drv(parser):
xml = """<art>
<kap><rad>al</rad></kap>
<subart>
<dif>Prefikso kun la senco <tld/><sncref ref="al.0.prep_proksimigxo"/></dif>:
<snc ref="al.0.prep_proksimigxo">
<ekz><ind><tld/>veni</ind>, <tld/>kuri <tld/>porti, <tld/>esti.</ekz>
</snc>
</subart>
</art>"""
derivs = list(Art(parser(xml)).derivations())
assert len(derivs) == 1
assert derivs[0].__class__ is Subart
parsed = derivs[0].to_text()
assert (
parsed.string == "Prefikso kun la senco al: \nalveni, alkuri alporti, alesti."
)
assert parsed.format == {
"ekz": [(27, 58)],
"tld": [(27, 29), (35, 37), (42, 44), (51, 53)],
}
def test_drv_multiple_kap(parser):
xml = """<drv mrk="ajn.sen0a"><kap>sen <tld/>a, <var><kap>sen ia <tld/></kap></var></kap></drv>"""
assert Drv(parser(xml), {"radix": "ajn"}).kap == "sen ajna, sen ia ajn"
def test_drv_kap(parser):
xml = '<drv mrk="a1.0.volvita"><kap><tld/> volvita</kap></drv>'
assert Drv(parser(xml), {"radix": "a"}).kap == "a volvita"
def test_drv_main_word_multiple(parser):
xml = '<drv mrk="abort.0ajxo"><kap><tld/>aĵo, <var><kap><tld/>ulo</kap></var></kap></drv>'
assert Drv(parser(xml), {"radix": "abort"}).main_word() == "abortaĵo, abortulo"
def test_drv_whitespace_after_gra_and_ref(parser):
xml = """<drv mrk="abol.0i">
<kap><tld/>i</kap>
<gra><vspec>tr</vspec></gra>
<snc mrk="abol.0i.JUR">
<uzo tip="fak">JUR</uzo>
<ref tip="dif" cel="abolic.0i">abolicii</ref>
<ekz>
sklaveco estis <tld/>ita en Brazilo en 1888.
</ekz>
</snc>
</drv>"""
assert (
Drv(parser(xml), {"radix": "abol"}).to_text().string
== "(tr) JUR = abolicii \nsklaveco estis abolita en Brazilo en 1888. "
)
def test_subdrv(parser):
xml = """<drv mrk="ad.0">
<kap><ofc>*</ofc>-<tld/></kap>
<dif>Sufikso esprimanta ĝenerale la agon kaj uzata por derivi:</dif>
<subdrv>
<dif>
substantivojn:
</dif>
</subdrv>
</drv>"""
assert (
Drv(parser(xml), {"radix": "ad"}).to_text().string
== "Sufikso esprimanta ĝenerale la agon kaj uzata por derivi:\n\nA. substantivojn: "
)
def test_subdrv_snc(parser):
xml = """<drv mrk="ir.0ado">
<kap><tld/>ado, <var><kap><tld/>o</kap></var></kap>
<subdrv>
<dif>
Ago <tld/>i:
</dif>
<snc mrk="ir.0ado.deAL"><ekz>Frazo</ekz></snc>
<snc mrk="ir.0ado.al"><ekz>Alia frazo</ekz></snc>
</subdrv>
<subdrv><dif>Maniero (...)</dif></subdrv>
</drv>
"""
assert (
Drv(parser(xml), {"radix": "ir"}).to_text().string
== "A. Ago iri: \n\n1. \nFrazo\n\n2. \nAlia frazo\n\nB. Maniero (...)"
)
def test_snc_single(parser):
xml = """<snc mrk="abak.0o.ARKI">
<uzo tip="fak">ARKI</uzo>
<dif>
Supera plata parto de kolona
<ref tip="vid" cel="kapite.0o">kapitelo</ref>.
</dif>
</snc>"""
assert (
Snc(parser(xml)).to_text().string
== "ARKI Supera plata parto de kolona kapitelo. "
)
def test_snc_no_tail_after_tld(parser):
assert (
Snc(parser('<snc mrk="abat.0o"><dif><tld/></dif></snc>'), {"radix": "abat"})
.to_text()
.string
== "abat"
)
def test_snc_ignore_fnt(parser):
xml = (
'<snc mrk="-"><dif>Difino <ekz>Frazo<fnt><aut>Iu</aut></fnt>.</ekz></dif></snc>'
)
assert Snc(parser(xml)).to_text().string == "Difino \nFrazo."
def test_snc_ignore_trd(parser):
xml = '<snc mrk="-"><dif>Difino <ekz><ind>Frazo</ind>.<trd lng="hu">Trd</trd></ekz></dif></snc>'
tag = Snc(parser(xml)).to_text()
assert tag.string == "Difino \nFrazo."
assert tag.format == {"ekz": [(8, 14)]}
def test_snc_replace_tld(parser):
xml = """<snc mrk="abat.0o">
<dif>Monaĥejestro de <tld/>ejo.</dif>
</snc>"""
assert (
Snc(parser(xml), {"radix": "abat"}).to_text().string
== "Monaĥejestro de abatejo."
)
def test_snc_replace_tld_lit(parser):
xml = """<snc mrk="abat.0o">
<dif>Monaĥejestro de <tld lit="A"/>ejo.</dif>
</snc>"""
assert (
Snc(parser(xml), {"radix": "abat"}).to_text().string
== "Monaĥejestro de Abatejo."
)
def test_snc_whitespace(parser):
xml = """<snc>
<dif>
Amata:
<ekz>
<tld/>a patrino;
</ekz>
<ekz>
nia <ind><tld/>memora</ind> majstro
</ekz>
</dif></snc>
"""
assert (
Snc(parser(xml), {"radix": "kar"}).to_text().string
== "Amata: \nkara patrino; \nnia karmemora majstro "
)
def test_snc_no_more_whitespace_after_ref(parser):
xml = """<snc>
<dif>
<ref tip="lst" cel="famili.0o.BIO"
lst="voko:zoologiaj_familioj">Familio</ref> el la ordo
<ref tip="malprt" cel="best.rabo0oj">rabobestoj</ref>
(<trd lng="la">Canidae</trd>).
</dif>
</snc>"""
assert (
Snc(parser(xml), {"radix": "hunded"}).to_text().string
== "Familio el la ordo rabobestoj (Canidae). "
)
def test_subsnc(parser):
xml = """<snc mrk="-">
<dif>Uzata kiel:</dif>
<subsnc><dif>A</dif></subsnc>
<subsnc><dif>B</dif></subsnc>
</snc>"""
assert Snc(parser(xml)).to_text().string == "Uzata kiel:\n\na) A\n\nb) B"
def test_multiple_snc(parser):
xml = """<art>
<kap><rad>zon</rad>/o</kap>
<drv mrk="zon.0o">
<kap><ofc>*</ofc><tld/>o</kap>
<snc mrk="zon.0o.TEKS"><dif>A</dif></snc>
<snc mrk="zon.0o.korpo"><dif>B</dif></snc>
</drv>
</art>
"""
drvs = [d.to_text().string for d in Art(parser(xml)).derivations()]
assert drvs == ["1. A\n\n2. B"]
def test_dif_space_between_elements(parser):
xml = """<dif>
<ref tip="dif" cel="fin.0ajxo.GRA">Finaĵo</ref>
(lingvoscience: sufikso)
</dif>"""
assert Dif(parser(xml)).to_text().string == "Finaĵo (lingvoscience: sufikso) "
def test_trd_inside_ekz(parser):
xml = """<art>
<kap><rad>abstin</rad>/i</kap>
<drv mrk="abstin.0i">
<kap><tld/>i</kap>
<gra><vspec>ntr</vspec></gra>
<snc>
<dif>Trinki ion pro medicina motivo:
<ekz>
<ind><tld/>ulo</ind>;
<trd lng="ca">abstinent<klr> (subst.)</klr></trd>
<trdgrp lng="hu">
<trd>absztinens</trd>,
<trd>önmegtartóztatás;</trd>
</trdgrp>
<trd lng="es">abstemio</trd>
</ekz>
</dif>
</snc>
<trd lng="en">abstain</trd>
</drv>
</art>"""
derivs = list(Art(parser(xml)).derivations())
assert len(derivs) == 1
trds = derivs[0].translations()
assert trds == {
"abstini": {"en": {None: ["abstain"]}},
# 'abstinulo': {
# 'ca': ['abstinent (subst.)'],
# 'hu': ['absztinens', 'önmegtartóztatás'],
# 'es': ['abstemio']},
}
def test_trd_preserves_whitespace(parser):
# pl words come from abdiki
xml = """<drv mrk="telefo.posx0o">
<kap>poŝ<tld/>o</kap>
<trdgrp lng="es">
<trd><klr tip="amb">teléfono</klr> <ind>móvil</ind></trd>,
<trd><klr tip="amb">teléfono</klr> <ind>celular</ind></trd>
</trdgrp>
<trdgrp lng="pl">
<trd><klr>dać </klr>dymisję</trd>
</trdgrp>
</drv>"""
drv = Drv(parser(xml), {"radix": "telefon"})
trds = drv.translations()
assert trds == {
"poŝtelefono": {
"es": {None: ["teléfono móvil", "teléfono celular"]},
"pl": {None: ["dać dymisję"]},
}
}
def test_trd_inside_snc(parser):
xml = """<drv mrk="brik.0o">
<kap><ofc>*</ofc><tld/>o</kap>
<snc mrk="brik.0o.bakita">
<trd lng="en">brick</trd>
</snc>
<snc mrk="brik.0o.FIG_elemento"></snc>
<snc mrk="brik.0o.formo">
<trd lng="en">block</trd>
</snc>
</drv>"""
drv = Drv(parser(xml), {"radix": "brik"})
trds = drv.translations()
assert trds == {"briko": {"en": {1: ["brick"], 3: ["block"]}}}
def test_trd_inside_only_snc(parser):
xml = """<drv mrk="cxili.CX0o">
<kap><tld/>o</kap>
<snc><trd lng="da">Chile</trd></snc>
</drv>"""
drv = Drv(parser(xml), {"radix": "cxili"})
assert drv.translations() == {"ĉilio": {"da": {None: ["Chile"]}}}
def test_trd_multiple_kap(parser):
xml = """<drv mrk="arab.SaudaA0ujo">
<kap>Sauda <tld lit="A"/>ujo,
<var><kap>Saud-<tld lit="A"/>ujo</kap></var>,
<var><kap>Saŭda <tld lit="A"/>ujo</kap></var>
</kap>
<trd lng="pl">Arabia Saudyjska</trd>
</drv>"""
drv = Drv(parser(xml), {"radix": "arab"})
assert drv.translations() == {
"Sauda Arabujo, Saud-Arabujo, Saŭda Arabujo": {
"pl": {None: ["Arabia Saudyjska"]}
}
}
def test_refgrp_arrow(parser):
xml = """<refgrp tip="sin">
<ref cel="plagx.0o">plaĝo</ref>
</refgrp>"""
assert Refgrp(parser(xml)).to_text().string == "→ plaĝo"
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,100
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/tests/test_string_with_format.py
|
from ..parser.string_with_format import StringWithFormat, Format, expand_tld
def test_init():
string = StringWithFormat()
assert string.string == ""
assert string.format == {}
def test_add():
string = StringWithFormat()
string.add("Saluton")
assert string.string == "Saluton"
string.add(" mondo!")
assert string.string == "Saluton mondo!"
def test_add_format():
string = StringWithFormat()
string.add_italic("Saluton")
assert string.string == "Saluton"
assert string.format == {"italic": [(0, 7)]}
string.add_italic(" mondo!")
assert string.string == "Saluton mondo!"
assert string.format == {"italic": [(0, 14)]}
def test_add_format_final():
string = StringWithFormat()
string.add("Saluton")
assert string.string == "Saluton"
string.add_italic(" mondo!")
assert string.string == "Saluton mondo!"
assert string.format == {"italic": [(7, 14)]}
def test_merge():
string1 = StringWithFormat()
string2 = StringWithFormat()
string1.add_italic("N")
string2.add_italic("u")
string1.add(string2)
assert string1.string == "Nu"
assert string1.format == {"italic": [(0, 2)]}
def test_prepend():
string = StringWithFormat()
string.add_italic("mondo!")
assert string.format == {"italic": [(0, 6)]}
string.prepend("Saluton ")
assert string.string == "Saluton mondo!"
assert string.format == {"italic": [(8, 14)]}
def test_strip_left():
string = StringWithFormat()
string.add_italic(" Bonan tagon")
string = string.strip()
assert string.string == "Bonan tagon"
assert string.format == {"italic": [(0, 11)]}
def test_strip_right():
string = StringWithFormat()
string.add_italic("Bonan tagon ")
string = string.strip()
assert string.string == "Bonan tagon"
assert string.format == {"italic": [(0, 11)]}
def test_join():
s1 = StringWithFormat().add_italic("a")
s2 = StringWithFormat("b")
s3 = StringWithFormat().add_italic("c")
string = StringWithFormat.join([s1, s2, s3], "-")
assert string.string == "a-b-c"
assert string.format == {"italic": [(0, 1), (4, 5)]}
def test_encode_format():
s = StringWithFormat().add_bold("Bonan").add_italic(" tagon").add_bold("!")
assert s.encode_format() == "bold:0,5;11,12\nitalic:5,11"
def test_expand_tld():
s = StringWithFormat()
s.add("amik", Format.TLD).add("eco, ge").add("patr", Format.TLD).add("oj")
s = expand_tld(s)
assert s.string == "amikeco, gepatroj"
assert s.format == {"tld": [(0, 7), (9, 17)]}
def test_expand_tld_start():
s = StringWithFormat()
s.add("a").add("b", Format.TLD)
s = expand_tld(s)
assert s.string == "ab"
assert s.format == {"tld": [(0, 2)]}
def test_expand_tld_start2():
s = StringWithFormat()
s.add(",a").add("b", Format.TLD)
s = expand_tld(s)
assert s.string == ",ab"
assert s.format == {"tld": [(1, 3)]}
def test_expand_tld_end():
s = StringWithFormat()
s.add("a", Format.TLD).add("b")
s = expand_tld(s)
assert s.string == "ab"
assert s.format == {"tld": [(0, 2)]}
def test_expand_tld_end2():
s = StringWithFormat()
s.add("a", Format.TLD).add("b,")
s = expand_tld(s)
assert s.string == "ab,"
assert s.format == {"tld": [(0, 2)]}
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,101
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/parser/revo.py
|
import os.path
import fire
import functools
import xml.etree.ElementTree as ET
from lxml import etree
from ..utils import add_hats, letter_enumerate
from .string_with_format import StringWithFormat, Format
from abc import abstractmethod
from typing import Union, Iterator, Optional, Type, TypeVar, cast
T = TypeVar("T", bound="Node")
def remove_extra_whitespace(string: str) -> str:
cleaned = " ".join(string.split())
# Preserve trailing whitespace
if string and string[-1] == " ":
cleaned += " "
if string and string[0] == " ":
cleaned = " " + cleaned
return cleaned
class Node:
def __init__(
self, node: ET.Element, extra_info: Optional[dict[str, "Node"]] = None
):
if extra_info is None:
extra_info = {}
self.parent: Optional["Node"] = extra_info.get("parent")
self.children: list[Union[str, "Node"]]
self.parse_children(node, extra_info)
def __repr__(self):
keys = " ".join(
"{}={}".format(k, repr(v))
for k, v in self.__dict__.items()
if k != "parent"
)
return "<%s %s>" % (self.__class__.__name__, keys)
def parse_children(self, node: ET.Element, extra_info: dict[str, "Node"]) -> None:
self.children = []
if node.text and node.text.strip():
self.children.append(remove_extra_whitespace(node.text))
for child in node:
if child.tag in ["adm", "bld", "fnt"]:
if child.tail and child.tail.strip():
self.children.append(remove_extra_whitespace(child.tail))
continue
tag_class = globals()[child.tag.title()]
extra_info["parent"] = self
self.children.append(tag_class(child, extra_info))
if child.tail and child.tail.strip():
self.children.append(remove_extra_whitespace(child.tail))
self.children = self.add_whitespace_nodes_to_children()
# print(node.tag, '- children:', self.children)
def add_whitespace_nodes_to_children(self) -> list[Union[str, "Node"]]:
children = []
for n, child in enumerate(self.children):
children.append(child)
if isinstance(child, Ref) and n < len(self.children) - 1:
next_node = self.children[n + 1]
# print("DETECTED ref, next:", next_node, next_node.__class__)
if isinstance(next_node, str) and next_node[0] not in ". ,;:":
children.append(" ")
elif not isinstance(next_node, str):
children.append(" ")
elif (
isinstance(child, Klr) and n < len(self.children) - 1 and child.children
):
if (
isinstance(child.children[-1], str)
and child.children[-1][-1] != " "
):
children.append(" ")
return children
def get(self, *args: Type[T]) -> Iterator[T]:
"Get nodes based on their class"
for tag in self.children:
if tag.__class__ in args:
tag = cast(T, tag)
yield tag
def get_except(self, *args: Type["Node"]) -> Iterator[Union[str, "Node"]]:
for tag in self.children:
if tag.__class__ not in args:
yield tag
def get_recursive(self, *args: Type[T]) -> Iterator[T]:
if not hasattr(self, "children"):
return
for tag in self.children:
if tag.__class__ in args:
tag = cast(T, tag)
yield tag
elif isinstance(tag, str):
continue
else:
for nested_tag in tag.get_recursive(*args):
yield nested_tag
def get_ancestor(self, *args: Type[T]) -> T:
if not self.parent:
raise
elif self.parent.__class__ in args:
parent = cast(T, self.parent)
return parent
return self.parent.get_ancestor(*args)
@abstractmethod
def to_text(self) -> StringWithFormat:
pass
def main_word(self) -> str:
kap = getattr(self, "kap", "")
if not kap:
kap = self.get_ancestor(Art).kap[0]
if kap is None:
return ""
return add_hats(kap.strip())
def translations(self) -> dict[str, dict[str, dict[Optional[int], list[str]]]]:
trds: dict[str, dict[str, dict[Optional[int], list[str]]]] = {}
for tag in self.get_recursive(Trd, Trdgrp):
if not isinstance(tag.parent, (Drv, Snc)):
continue
# N° of snc inside the Drv
snc_index = None
if isinstance(tag.parent, Snc):
if not isinstance(tag.parent.parent, Drv):
# TODO check if we are missing something
# example: -ad (ad.xml and subdrv)
continue
drv = tag.parent.parent
main_word = drv.main_word()
sncs = [t for t in drv.children if isinstance(t, Snc)]
# If there is only one Snc we don't need to specify a snc_index
if len(sncs) > 1:
snc_index = sncs.index(tag.parent) + 1
else:
main_word = tag.parent.main_word()
if main_word not in trds:
trds[main_word] = {}
if not isinstance(tag, (Trd, Trdgrp)):
raise
lng, texts = tag.parse_trd()
if isinstance(texts, str):
texts = [texts]
if lng not in trds[main_word]:
trds[main_word][lng] = {}
trds[main_word][lng][snc_index] = texts
return trds
class TextNode(Node):
# Format enum, can also be a list
base_format: Union[list[Format], Format, None] = None
def to_text(self) -> StringWithFormat:
parts: list[StringWithFormat] = []
for node in self.children:
if isinstance(node, str):
parts.append(StringWithFormat(node))
else:
parts.append(node.to_text())
try:
content = StringWithFormat()
for part in parts:
content += part
# print(self.children, "\n", parts, "\n")
return content.apply_format(self.base_format)
except Exception:
print(self.children)
print(parts)
raise
class Art(Node):
def __init__(self, node: ET.Element, extra_info=None):
if extra_info is None:
extra_info = {}
assert node.tag == "art"
rad = node.find("kap/rad")
if rad is None:
raise
tail = ""
if rad.tail:
tail = rad.tail.strip()
self.kap = (rad.text, tail)
extra_info["radix"] = self.kap[0]
super().__init__(node, extra_info)
def derivations(self) -> Iterator[Union["Subart", "Drv"]]:
for subart in self.get(Subart):
for drv in subart.derivations():
yield drv
for drv in self.get(Drv):
yield drv
assert not list(self.get(Snc))
def to_text(self):
raise Exception("Do not use Art.to_text() directly")
class Kap(TextNode):
pass
class Rad(TextNode):
pass
class Gra(TextNode):
pass
class Mlg(TextNode):
pass
class Vspec(TextNode):
def to_text(self) -> StringWithFormat:
return StringWithFormat("(").add(super().to_text()).add(")")
class Ofc(TextNode):
def to_text(self) -> StringWithFormat:
return StringWithFormat("")
class Var(TextNode):
pass
class Subart(TextNode):
def __init__(self, node: ET.Element, extra_info=None):
super().__init__(node, extra_info)
self.mrk = ""
self.kap = ""
def derivations(self) -> Iterator[Union["Subart", "Drv"]]:
# Note that this method sometimes will return the subart node
drvs = list(self.get(Drv))
if len(drvs) == 1:
self.kap = drvs[0].kap
self.mrk = drvs[0].mrk
yield self
else:
for drv in drvs:
if not self.kap:
self.kap = drv.kap
self.mrk = drv.mrk
yield drv
# al.xml, last <subart> has <snc> as a direct child
if not drvs and list(self.get(Snc)):
yield self
class Drv(Node):
def __init__(self, node: ET.Element, extra_info=None):
self.mrk = node.get("mrk") or ""
if not extra_info:
extra_info = {}
kap_node = node.find("kap")
assert kap_node is not None
kap = Kap(kap_node, extra_info)
self.kap = kap.to_text().string
super().__init__(node, extra_info)
self.parse_children(node, extra_info)
def read_snc(self) -> list[StringWithFormat]:
meanings = []
n_sncs = len(list(self.get(Snc)))
for n, snc in enumerate(self.get(Snc)):
if n_sncs > 1:
text = StringWithFormat("%s. " % (n + 1,))
text += snc.to_text()
else:
text = snc.to_text()
meanings.append(text)
return meanings
def to_text(self) -> StringWithFormat:
content = StringWithFormat()
# Kap and Fnt ignored
for node in self.get(Gra, Uzo, Dif, Ref):
if isinstance(node, Ref) and node.tip != "dif":
continue
content += node.to_text()
if isinstance(node, Gra):
content += " "
meanings = self.read_snc()
for nn, subdrv in letter_enumerate(self.get(Subdrv)):
text = subdrv.to_text()
text.prepend("%s. " % nn.upper())
if nn == "a" and (meanings or len(content)):
text.prepend("\n\n")
meanings.append(text)
content += StringWithFormat.join(meanings, "\n\n")
# Renaming node2 to node causes issues with mypy
for node2 in self.get_except(Subdrv, Snc, Gra, Uzo, Fnt, Kap, Dif, Mlg):
if isinstance(node2, Ref) and node2.tip == "dif":
continue
if isinstance(node2, str):
# Nodes added by hand in add_whitespace_nodes_to_children
content += node2
else:
content += node2.to_text()
return content
class Subdrv(Node):
def __init__(self, node: ET.Element, extra_info=None):
super().__init__(node, extra_info)
self.parse_children(node, extra_info)
def to_text(self) -> StringWithFormat:
content = StringWithFormat()
# Fnt omitted
for node in self.get(Dif, Gra, Uzo, Ref):
if isinstance(node, Ref) and node.tip != "dif":
continue
content += node.to_text()
for n, snc in enumerate(self.get(Snc), 1):
text = snc.to_text()
text.prepend("%s. " % n)
text.prepend("\n\n")
content += text
for text_node in self.get_except(Snc, Gra, Uzo, Fnt, Dif, Ref):
if isinstance(text_node, Ref) and text_node.tip == "dif":
continue
if isinstance(text_node, str):
raise
content += text_node.to_text()
return content
class Snc(Node):
def __init__(self, node, extra_info=None):
self.mrk = node.get("mrk")
if not extra_info:
extra_info = {}
# example: snc without mrk but drv has it (see zoni in zon.xml)
self.mrk = self.mrk or extra_info["radix"]
super().__init__(node, extra_info)
def to_text(self) -> StringWithFormat:
content = StringWithFormat()
# Fnt ignored
for node in self.get(Gra, Uzo, Dif, Ref):
if isinstance(node, Ref) and node.tip != "dif":
continue
content += node.to_text()
if isinstance(node, Gra):
content += " "
if list(self.get(Subsnc)):
content += "\n\n"
subs = []
for n, subsnc in letter_enumerate(self.get(Subsnc)):
text = subsnc.to_text()
text.prepend("%s) " % n)
subs.append(text)
content += StringWithFormat.join(subs, "\n\n")
# Renaming node2 to node causes issues with mypy
for node2 in self.get_except(Gra, Uzo, Fnt, Dif, Subsnc):
if isinstance(node2, Ref) and node2.tip == "dif":
continue
if isinstance(node2, str):
# Nodes added by hand in add_whitespace_nodes_to_children
content += node2
else:
content += node2.to_text()
return content
class Subsnc(TextNode):
def __init__(self, node: ET.Element, extra_info=None):
super().__init__(node, extra_info)
self.mrk = node.get("mrk")
class Uzo(TextNode):
def __init__(self, node: ET.Element, extra_info=None):
super().__init__(node, extra_info)
self.tip = node.get("tip")
if self.tip == "fak":
self.base_format = Format.UZO_FAKO
def to_text(self) -> StringWithFormat:
text = super().to_text()
if self.tip == "stl":
mapping = {
"FRAZ": "(frazaĵo)",
"FIG": "(figure)",
"VULG": "(vulgare)",
"RAR": "(malofte)",
"POE": "(poezie)",
"ARK": "(arkaismo)",
"EVI": "(evitinde)",
"KOMUNE": "(komune)",
"NEO": "(neologismo)",
}
text = StringWithFormat(mapping.get(text.string, text.string))
return text + " "
class Dif(TextNode):
pass
class Tezrad(Node):
def to_text(self) -> StringWithFormat:
return StringWithFormat("")
# TODO link to url
class Url(TextNode):
pass
# TODO link
class Lstref(TextNode):
pass
class Trd(TextNode):
def __init__(self, node: ET.Element, extra_info=None):
super().__init__(node, extra_info)
self.lng = node.get("lng") or ""
# abel.xml has a trd inside a dif
def to_text(self) -> StringWithFormat:
if isinstance(self.parent, Dif):
return super().to_text()
return StringWithFormat("")
def parse_trd(self) -> tuple[str, str]:
return (self.lng, super().to_text().string)
class Trdgrp(Node):
def __init__(self, node: ET.Element, extra_info=None):
self.lng = node.get("lng") or ""
super().__init__(node, extra_info)
def to_text(self) -> StringWithFormat:
return StringWithFormat("")
def parse_trd(self) -> tuple[str, list[str]]:
return (self.lng, [trd.parse_trd()[1] for trd in self.get(Trd)])
class Ref(TextNode):
@staticmethod
def add_arrow(tip: Optional[str], text: StringWithFormat) -> StringWithFormat:
if not tip:
return text
symbol = "→"
if tip == "dif":
symbol = "="
content = StringWithFormat(symbol + " ")
content += text
return content
def __init__(self, node: ET.Element, extra_info=None):
super().__init__(node, extra_info)
self.tip = node.get("tip")
def to_text(self) -> StringWithFormat:
if isinstance(self.parent, (Dif, Rim, Ekz, Klr)):
return super().to_text()
return Ref.add_arrow(self.tip, super().to_text())
# symbol = "→"
# if self.tip == 'malprt':
# symbol = "↗"
# elif self.tip == "prt":
# symbol = "↘"
# content = StringWithFormat(symbol+' ')
# content += super().to_text()
# return content
class Refgrp(TextNode):
def __init__(self, node: ET.Element, extra_info=None):
super().__init__(node, extra_info)
self.tip = node.get("tip")
def to_text(self) -> StringWithFormat:
if isinstance(self.parent, (Dif, Rim, Ekz, Klr)):
return super().to_text()
return Ref.add_arrow(self.tip, super().to_text())
class Sncref(TextNode):
pass
class Ekz(TextNode):
base_format = Format.EKZ
def to_text(self) -> StringWithFormat:
content = super().to_text()
content.prepend("\n")
return content
class Tld(Node):
def __init__(self, node: ET.Element, extra_info=None):
self.radix = ""
self.lit = node.get("lit") or ""
if extra_info:
self.radix = extra_info.get("radix") or ""
self.radix = self.radix.strip()
self.parent = extra_info.get("parent")
def to_text(self) -> StringWithFormat:
content = None
if self.lit and self.radix:
content = StringWithFormat(self.lit + self.radix[1:])
else:
content = StringWithFormat(self.radix or "-----")
if isinstance(self.parent, Ekz) or (
self.parent and isinstance(self.parent.parent, Ekz)
):
content = content.apply_format(Format.TLD)
return content
# found in amik.xml
class Klr(TextNode):
pass
class Rim(TextNode):
def __init__(self, node: ET.Element, extra_info=None):
super().__init__(node, extra_info)
self.num = node.get("num") or ""
def to_text(self) -> StringWithFormat:
string = super().to_text()
if self.num:
content = StringWithFormat().add_bold("\n\nRim. %s: " % self.num)
content += string
return content
return StringWithFormat().add_bold("\n\nRim. ").add(string)
class Aut(TextNode):
def to_text(self) -> StringWithFormat:
return StringWithFormat("[").add(super().to_text()).add("]")
class Fnt(Node):
def to_text(self) -> StringWithFormat:
return StringWithFormat("")
# found in zon.xml
class Frm(TextNode):
pass
# TODO sub format (seen en acetil.xml)
class Sub(TextNode):
pass
class Sup(TextNode):
pass
class K(TextNode):
pass
class G(TextNode):
pass
# TODO bold format (example: abstrakta)
class Em(TextNode):
pass
class Ctl(TextNode):
pass
class Ind(TextNode):
pass
class Mll(TextNode):
pass
class Nom(TextNode):
pass
class Esc(TextNode):
pass
class Nac(TextNode):
pass
class Baz(TextNode):
pass
# seen in dank.xml, danke al
class Mis(TextNode):
pass
# TODO strikethrough
class Ts(TextNode):
pass
# https://github.com/sstangl/tuja-vortaro/blob/master/revo/convert-to-js.py
@functools.cache
def entities_dict() -> dict[str, str]:
entities: dict[str, str] = {}
base_dir = os.path.join(os.path.dirname(__file__), "..", "..", "revo", "dtd")
with open(os.path.join(base_dir, "vokosgn.dtd"), "rb") as f:
dtd = etree.DTD(f)
for entity in dtd.iterentities():
entities[entity.name] = entity.content
with open(os.path.join(base_dir, "vokourl.dtd"), "rb") as f:
dtd = etree.DTD(f)
for entity in dtd.iterentities():
entities[entity.name] = entity.content
with open(os.path.join(base_dir, "vokomll.dtd"), "rb") as f:
dtd = etree.DTD(f)
for entity in dtd.iterentities():
entities[entity.name] = entity.content
return entities
def parse_article(filename: str) -> Art:
with open(filename) as f:
article = f.read()
xml_parser = ET.XMLParser()
for entity, value in entities_dict().items():
xml_parser.entity[entity] = value
tree = ET.fromstring(article, parser=xml_parser)
art = tree.find("art")
if not art:
raise Exception("XML file does not contain <art> tag!")
return Art(art)
def main(word: str):
art = parse_article("xml/%s.xml" % word)
print(art)
print()
print(art.to_text())
if __name__ == "__main__":
fire.Fire(main)
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,102
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/tests/test_utils.py
|
from ..utils import add_hats
def test_add_hats():
assert add_hats("") == ""
assert add_hats("saluton") == "saluton"
assert add_hats("sercxi") == "serĉi"
assert add_hats("CxSxGxJxHxUxcxsxgxjxhxux") == "ĈŜĜĴĤŬĉŝĝĵĥŭ"
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,103
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/process_revo.py
|
import os
import sqlite3
import glob
import itertools
import json
from typing import TypedDict, Optional
from .utils import get_languages, get_disciplines, output_dir
from .parser import revo
from .parser.string_with_format import expand_tld
class DefinitionDict(TypedDict):
article_id: int
word: str
mark: str
definition: str
format: str
trads: dict
position: int
definition_id: Optional[int]
class EntryDict(TypedDict):
article_id: int
word: str
definition: DefinitionDict
def insert_translations(trads: list[dict], cursor: sqlite3.Cursor) -> None:
# flatten
all_trans: list[dict] = []
for translation in trads:
for snc_index, words in translation["data"].items():
for word in words:
all_trans.append(
dict(translation=word, snc_index=snc_index, **translation)
)
all_trans.sort(
key=lambda x: (
x["lng"],
x["translation"],
x["snc_index"] is None,
x["snc_index"],
)
)
for translation in all_trans:
cursor.execute(
"""INSERT INTO translations_{code}
(definition_id, snc_index, word, translation)
VALUES (?,?,?,?)""".format(
code=translation["lng"]
),
(
translation["row_id"],
translation["snc_index"],
translation["word"],
translation["translation"],
),
)
def create_db(output_db: str) -> sqlite3.Connection:
base_dir = os.path.dirname(__file__)
db_filename = os.path.join(base_dir, output_db)
try:
os.remove(db_filename)
except Exception:
pass
conn = sqlite3.connect(db_filename)
c = conn.cursor()
c.execute(
"""
CREATE TABLE words (
id integer primary key,
word text,
definition_id integer
)
"""
)
# position: relative order inside the article
c.execute(
"""
CREATE TABLE definitions (
id integer primary key,
article_id integer,
words text,
mark text,
position integer,
definition text,
format text
)
"""
)
return conn
def create_langs_tables(cursor: sqlite3.Cursor, entries_per_lang: dict) -> None:
cursor.execute(
"""
CREATE TABLE languages (
id integer primary key,
code text,
name text,
num_entries integer
)
"""
)
lang_names = {
lang_def["code"]: (order, lang_def["name"])
for order, lang_def in enumerate(get_languages())
}
# Normal sort won't consider ĉ, ŝ, ...,
# get_languages() gives the correct order
langs = sorted(entries_per_lang.keys(), key=lambda x: lang_names[x][0])
for lang in langs:
cursor.execute(
"""
CREATE TABLE translations_{lang} (
id integer primary key,
definition_id integer,
snc_index integer,
word text,
translation text
)
""".format(
lang=lang
)
)
cursor.execute(
"""
INSERT INTO languages (code, name, num_entries)
VALUES (?, ?, ?)
""",
(lang, lang_names[lang][1], entries_per_lang[lang]),
)
def create_disciplines_tables(cursor: sqlite3.Cursor) -> None:
cursor.execute(
"""
CREATE TABLE disciplines (
id integer primary key,
code text,
name text
)
"""
)
for code, discipline in get_disciplines().items():
cursor.execute(
"INSERT INTO disciplines (code, name) VALUES (?, ?)", (code, discipline)
)
def create_version_table(cursor: sqlite3.Cursor) -> None:
base_dir = os.path.dirname(__file__)
version = ""
with open(os.path.join(base_dir, "..", "revo", "VERSION"), "r") as f:
version = f.read().strip()
cursor.execute("CREATE TABLE version (id text primary key)")
cursor.execute("INSERT INTO version (id) values (?)", (version,))
def parse_article(filename: str, num_article: int, verbose=False) -> list[EntryDict]:
art = None
try:
art = revo.parse_article(filename)
except Exception:
print("Error parsing %s" % filename)
raise
found_words = []
entries: list[EntryDict] = []
has_subart = False
drvs = list(art.derivations())
for pos, drv in enumerate(drvs, 1):
if isinstance(drv, revo.Subart):
has_subart = True
if pos == len(drvs) and has_subart and not drv.kap:
# first subart contains the whole article,
# so this snc will not be needed
continue
main_word_txt = drv.main_word()
found_words.append(main_word_txt)
row_id = None
content = drv.to_text()
content = expand_tld(content)
assert "StringWithFormat" not in content.string
# definition_id will be used to check whether the definition is already in the database
definition: DefinitionDict = dict(
article_id=num_article,
word=main_word_txt,
mark=drv.mrk,
definition=content.string,
format=content.encode_format(),
trads=drv.translations(),
position=pos,
definition_id=None,
)
# note that before inserting the entries will be sorted by 'word'
first_word = True
for word in main_word_txt.split(", "):
word = word.strip()
# "definition" dict is shared between entries in this loop
entries.append(
dict(article_id=num_article, word=word, definition=definition)
)
if first_word:
first_word = False
# Avoid duplication of translations
definition = definition.copy()
definition["trads"] = {}
if verbose:
print(filename, drv.mrk, row_id)
else:
print(filename, drv.mrk)
return entries
def create_index(cursor: sqlite3.Cursor) -> None:
cursor.execute("CREATE INDEX index_word_words ON words (word)")
cursor.execute("CREATE INDEX index_definition_id_words ON words (definition_id)")
def write_stats(entries_per_lang: dict) -> None:
base_dir = os.path.dirname(__file__)
with open(os.path.join(base_dir, "..", "stats.json"), "w") as f:
json.dump(entries_per_lang, f, ensure_ascii=False, indent=4)
def insert_entries(
entries: list[EntryDict], cursor: sqlite3.Cursor, min_entries_to_include_lang: int
) -> None:
entries = sorted(entries, key=lambda x: x["word"].lower())
translations = []
for entry in entries:
print(entry["word"])
if not entry["definition"]["definition_id"]:
definition = entry["definition"]
cursor.execute(
"""INSERT INTO definitions (
article_id, words, mark, position, definition, format)
values (?, ?, ?, ?, ?, ?)""",
(
definition["article_id"],
definition["word"],
definition["mark"],
definition["position"],
definition["definition"],
definition["format"],
),
)
entry["definition"]["definition_id"] = cursor.lastrowid
assert entry["definition"]["definition_id"] is not None
def_id: int = entry["definition"]["definition_id"]
cursor.execute(
"INSERT into words (word, definition_id) values (?, ?)",
[entry["word"], def_id],
)
trads = entry["definition"]["trads"]
if trads:
for word, more_trads in trads.items():
for lng, trans_data in more_trads.items():
translations.append(
dict(row_id=def_id, word=word, lng=lng, data=trans_data)
)
translations = sorted(translations, key=lambda x: x["lng"])
entries_per_lang = {}
for lng, g in itertools.groupby(translations, key=lambda x: x["lng"]):
count = len(list(g))
if count >= min_entries_to_include_lang:
print(lng, count)
entries_per_lang[lng] = count
write_stats(entries_per_lang)
create_langs_tables(cursor, entries_per_lang)
translations = [t for t in translations if t["lng"] in entries_per_lang]
insert_translations(translations, cursor)
def main(
word: Optional[str],
xml_file: Optional[str],
output_db: str,
limit: Optional[int],
verbose: bool,
dry_run: bool,
min_entries_to_include_lang: int,
) -> None:
conn = create_db(os.path.join(output_dir(), output_db))
cursor = conn.cursor()
if not dry_run:
create_disciplines_tables(cursor)
entries: list[EntryDict] = []
try:
files = []
if xml_file:
files = [xml_file]
else:
base_dir = os.path.dirname(__file__)
path = os.path.join(base_dir, "..", "revo", "xml", "*.xml")
files = glob.glob(path)
files.sort()
num_article = 1
for filename in files:
if word and word not in filename:
continue
parsed_entries = parse_article(filename, num_article, verbose)
entries += parsed_entries
num_article += 1
if limit and num_article >= limit:
break
if not dry_run:
insert_entries(entries, cursor, min_entries_to_include_lang)
create_index(cursor)
create_version_table(cursor)
finally:
if not dry_run:
conn.commit()
cursor.close()
conn.close()
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,104
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/tests/test_process.py
|
import os
import sqlite3
import pytest
from ..utils import output_dir
from ..cli import Vortaro
TEST_DB = "test.db"
XML_BASE_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "revo", "xml")
# source: https://github.com/pallets/click/issues/737#issuecomment-309231467
@pytest.fixture
def vortaro():
return Vortaro()
def db_file():
return os.path.join(output_dir(), TEST_DB)
def test_process_subart(vortaro):
vortaro.process_revo(
output_db=TEST_DB, xml_file=os.path.join(XML_BASE_DIR, "an.xml")
)
conn = sqlite3.connect(db_file())
cursor = conn.cursor()
res = cursor.execute("SELECT words, mark, position from definitions")
assert list(res) == [
("-an", "an.0", 1),
("anaro", "an.0aro", 3),
("aniĝi", "an.0igxi", 4),
("ano", "an.0o", 2),
]
def test_process_subart_2(vortaro):
vortaro.process_revo(
output_db=TEST_DB, xml_file=os.path.join(XML_BASE_DIR, "al.xml")
)
conn = sqlite3.connect(db_file())
cursor = conn.cursor()
res = cursor.execute("SELECT word, definition_id from words")
assert list(res) == [
("al", 1),
("aligi", 2),
("aliĝi", 3),
("aliĝilo", 4),
("malaliĝi", 5),
("realiĝi", 6),
]
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,105
|
djuretic/praktika-vortaro-dicts
|
refs/heads/master
|
/eo_dicts/parser/string_with_format.py
|
from enum import Enum
# not using tpying.Self because mypy doesn't support it yet
from typing import Optional, Union
class Format(Enum):
ITALIC = "italic"
BOLD = "bold"
# Example sentence
EKZ = "ekz"
# Headword
TLD = "tld"
# Example: GEOG POL
UZO_FAKO = "fako"
class StringWithFormat:
def __init__(self, string: Optional[str] = None):
self.string = string or ""
self.format: dict[str, list[tuple[int, int]]] = {}
@classmethod
def join(
cls, string_list: list["StringWithFormat"], separator: str
) -> "StringWithFormat":
if len(string_list) == 0:
return StringWithFormat()
base = string_list[0]
for n, string in enumerate(string_list[1:]):
if n < len(string_list) - 1:
base += separator
base += string
return base
def add(
self,
other: Union[str, "StringWithFormat"],
format_type: Optional[Format] = None,
keep_whitespace=False,
) -> "StringWithFormat":
# print('ADD', repr(self), repr(self.format), repr(other), format_type)
if format_type and format_type.value not in self.format:
self.format[format_type.value] = []
if isinstance(other, StringWithFormat):
assert format_type is None
# first string length
n = len(self.string)
self.add(other.string, keep_whitespace=keep_whitespace)
for fmt, fmt_list in other.format.items():
if fmt not in self.format:
self.format[fmt] = []
if (
self.format[fmt]
and self.format[fmt][-1][-1] == n
and fmt_list
and fmt_list[0][0] == 0
):
# merge two formats in one
self.format[fmt][-1] = (self.format[fmt][-1][0], n + fmt_list[0][1])
fmt_list = fmt_list[1:]
self.format[fmt] += [(start + n, end + n) for (start, end) in fmt_list]
else:
if format_type:
last_format = self.format[format_type.value]
if last_format and last_format[-1][-1] == len(self.string):
last_format[-1] = (
last_format[-1][0],
len(self.string) + len(other),
)
else:
self.format[format_type.value].append(
(len(self.string), len(self.string) + len(other))
)
self.string += other
return self
def add_italic(self, other: Union[str, "StringWithFormat"]) -> "StringWithFormat":
return self.add(other, Format.ITALIC)
def add_bold(self, other: Union[str, "StringWithFormat"]) -> "StringWithFormat":
return self.add(other, Format.BOLD)
def apply_format(
self, format_type: Union[list[Format], Format, None]
) -> "StringWithFormat":
if not format_type:
return self
if isinstance(format_type, (list, tuple)):
for format_t in format_type:
self.apply_format(format_t)
else:
if format_type and format_type.value not in self.format:
self.format[format_type.value] = []
self.format[format_type.value].append((0, len(self.string)))
return self
def __add__(self, other: Union[str, "StringWithFormat"]) -> "StringWithFormat":
return self.add(other)
def prepend(self, other: str) -> "StringWithFormat":
alt = StringWithFormat(other).add(self)
self.string = alt.string
self.format = alt.format
return self
def strip(self) -> "StringWithFormat":
original = self.string
base_len = len(original)
new_format = dict(self.format)
new_string = original.rstrip()
if len(new_string) != base_len:
for key in new_format:
new_format[key] = [
(a, min(len(new_string), b)) for (a, b) in new_format[key]
]
base_len = len(new_string)
new_string = new_string.lstrip()
if len(new_string) != base_len:
dif = base_len - len(new_string)
for key in new_format:
new_format[key] = [
(max(0, a - dif), max(0, b - dif)) for (a, b) in new_format[key]
]
new_string_format = StringWithFormat(new_string)
new_string_format.format = new_format
return new_string_format
def encode_format(self) -> str:
encoded = []
for fmt, values in self.format.items():
tmp_list = ["%s,%s" % item for item in values]
encoded.append("%s:%s" % (fmt, ";".join(tmp_list)))
return "\n".join(encoded)
def __eq__(self, other) -> bool:
if isinstance(other, StringWithFormat):
return self.string == other.string and self.format == other.format
return False
def __repr__(self) -> str:
return "<%s %s>" % (self.__class__.__name__, repr(self.string))
def __len__(self) -> int:
return len(self.string)
def expand_tld(string: StringWithFormat) -> StringWithFormat:
if not isinstance(string, StringWithFormat) or not string.format.get(
Format.TLD.value
):
return string
boundaries = " \n:;;.,•?!()[]{}'\"„“"
original_format = string.format[Format.TLD.value]
new_format = []
for start, end in original_format:
for i in range(start, -1, -1):
if string.string[i] in boundaries:
break
start = i
for i in range(end, len(string.string)):
end = i
if string.string[i] in boundaries:
break
else:
end = len(string.string)
new_format.append((start, end))
string.format[Format.TLD.value] = new_format
return string
|
{"/eo_dicts/search.py": ["/eo_dicts/utils.py"], "/eo_dicts/cli.py": ["/eo_dicts/utils.py", "/eo_dicts/search.py"], "/eo_dicts/tests/test_parser.py": ["/eo_dicts/parser/revo.py"], "/eo_dicts/tests/test_string_with_format.py": ["/eo_dicts/parser/string_with_format.py"], "/eo_dicts/parser/revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_utils.py": ["/eo_dicts/utils.py"], "/eo_dicts/process_revo.py": ["/eo_dicts/utils.py", "/eo_dicts/parser/string_with_format.py"], "/eo_dicts/tests/test_process.py": ["/eo_dicts/utils.py", "/eo_dicts/cli.py"]}
|
19,208
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/settings.py
|
from django.conf import settings
# Consumer backend
REQUESTS_CONSUMER_BACKEND = getattr(
settings, "DRF_BATCH_REQUESTS_CONSUMER_BACKEND", 'drf_batch_requests.backends.sync.SyncRequestsConsumeBackend'
)
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,209
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/backends/base.py
|
class RequestsConsumeBaseBackend(object):
def consume_request(self, request, start_callback=None, success_callback=None, fail_callback=None):
raise NotImplementedError
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,210
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/tests/test_view.py
|
import json
from django.core.files.uploadedfile import SimpleUploadedFile
from rest_framework import status
from tests.mixins import APITestCase
class BaseTestCase(APITestCase):
def test_json_batch(self):
batch = [
{
"method": "GET",
"relative_url": "/tests/test/",
"name": "request1"
},
{
"method": "GET",
"relative_url": "/tests/test/?ids={result=request1:$.data.*.id}"
}
]
responses = self.forced_auth_req('post', '/batch/', data={'batch': batch})
self.assertEqual(responses.status_code, status.HTTP_200_OK, msg=responses.data)
self.assertEqual("request1", responses.data[0]['name'])
self.assertEqual("OK", responses.data[0]['code_text'])
responses_data = [json.loads(r['body']) for r in responses.data]
self.assertIn('ids', responses_data[1]['get'])
self.assertEqual(
responses_data[1]['get']['ids'],
','.join([str(o['id']) for o in responses_data[0]['data']])
)
def test_multipart_simple_request(self):
batch = [
{
"method": "GET",
"relative_url": "/tests/test/"
}
]
responses = self.forced_auth_req(
'post', '/batch/',
data={'batch': json.dumps(batch)},
request_format='multipart',
)
self.assertEqual(responses.status_code, status.HTTP_200_OK, msg=responses.data)
responses_data = list(map(lambda r: json.loads(r['body']), responses.data))
self.assertIn('data', responses_data[0])
def test_multipart_files_upload(self):
batch = [
{
"method": "POST",
"relative_url": "/tests/test-files/",
"attached_files": {
"file": "file1",
"second_file": 'file2'
}
}
]
responses = self.forced_auth_req(
'post', '/batch/',
data={
'batch': json.dumps(batch),
'file1': SimpleUploadedFile('hello_world.txt', u'hello world!'.encode('utf-8')),
'file2': SimpleUploadedFile('second file.txt', u'test!'.encode('utf-8')),
},
request_format='multipart',
)
self.assertEqual(responses.status_code, status.HTTP_200_OK, msg=responses.data)
responses_data = list(map(lambda r: json.loads(r['body']), responses.data))
self.assertIn('files', responses_data[0])
self.assertListEqual(sorted(['file', 'second_file']), sorted(list(responses_data[0]['files'].keys())))
self.assertListEqual(
sorted(['hello_world.txt', 'second file.txt']),
sorted([a['name'] for a in responses_data[0]['files'].values()])
)
def test_non_json(self):
responses = self.forced_auth_req(
'post', '/batch/',
data={
'batch': [
{
'method': 'GET',
'relative_url': '/test-non-json/'
}
]
}
)
self.assertEqual(responses.status_code, status.HTTP_200_OK, msg=responses.data)
self.assertEqual(responses.data[0]['body'], 'test non-json output')
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,211
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_settings/urls.py
|
try:
from django.conf.urls import include, url
except ImportError:
# django 2.0
from django.urls import include
from django.urls import re_path as url
urlpatterns = [
url(r'^batch/', include('drf_batch_requests.urls', namespace='drf_batch')),
url(r'^example/', include('drf_batch_example.urls', namespace='drf_batch_example')),
]
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,212
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/response.py
|
import json
from json import JSONDecodeError
from typing import Iterable
from rest_framework.status import is_success
class ResponseHeader:
def __init__(self, name: str, value: str):
self.name = name
self.value = value
def to_dict(self):
return {
'key': self.name,
'value': self.value,
}
class BatchResponse:
name: str
code: int
code_text: str
headers: Iterable[ResponseHeader]
body: str
_data: dict
_return_body: bool = True
def __init__(self, name: str, status_code: int, body: str, headers: Iterable[ResponseHeader] = None,
omit_response_on_success: bool = False, status_text: str = None):
self.name = name
self.status_code = status_code
self.status_text = status_text
self.body = body
self.headers = headers or []
self.omit_response_on_success = omit_response_on_success
if is_success(self.status_code):
try:
self._data = json.loads(self.body)
except JSONDecodeError:
self._data = {}
if is_success(self.status_code) and self.omit_response_on_success:
self._return_body = False
def to_dict(self) -> dict:
return {
'name': self.name,
'code': self.status_code,
'code_text': self.status_text,
'headers': [h.to_dict() for h in self.headers],
'body': self.body,
}
@property
def data(self):
return self._data
class DummyBatchResponse(BatchResponse):
def __init__(self, name: str):
super().__init__(name, 418, '')
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,213
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/utils.py
|
import random
import string
def get_attribute(instance, attrs):
for attr in attrs:
if instance is None:
return None
if attr == '*':
# todo: maybe there should be some kind of filtering?
continue
if isinstance(instance, list):
instance = list(map(lambda i: i[attr], instance))
else:
instance = instance[attr]
return instance
def generate_random_id(size=10, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def generate_node_callback(node, status):
def callback():
if status == 'start':
node.start()
elif status == 'success':
node.complete()
elif status == 'fail':
node.fail()
else:
raise NotImplementedError
return callback
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,214
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_example/views.py
|
from django.http import JsonResponse
from rest_framework.views import APIView
class TestView(APIView):
def get(self, request, *args, **kwargs):
return self.finalize_response(request, JsonResponse({
'id': 1,
'data': [
{'id': '1'},
{'id': '2'},
{'id': '3'},
{'id': '4'},
],
'empty_argument': None
}))
def post(self, request, *args, **kwargs):
return self.finalize_response(request, JsonResponse({'data': request.data.get('data')}))
# todo: add CBV and FBV
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,215
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/request.py
|
import json
import re
from io import BytesIO
from urllib.parse import urlsplit
from django.http import HttpRequest
from django.http.request import QueryDict
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_str as force_text
from rest_framework.exceptions import ValidationError
from drf_batch_requests.exceptions import RequestAttributeError
from drf_batch_requests.serializers import BatchRequestSerializer
from drf_batch_requests.utils import get_attribute
class BatchRequest(HttpRequest):
def __init__(self, request, request_data):
super(BatchRequest, self).__init__()
self.name = request_data.get('name')
self.omit_response_on_success = request_data.get('omit_response_on_success', False)
self._stream = BytesIO(request_data['_body'].encode('utf-8'))
self._read_started = False
self.method = request_data['method']
split_url = urlsplit(request_data['relative_url'])
self.path_info = self.path = split_url.path
self.GET = QueryDict(split_url.query)
self._set_headers(request, request_data.get('headers', {}))
self.COOKIES = request.COOKIES
# Standard WSGI supported headers
# (are not prefixed with HTTP_)
_wsgi_headers = ["content_length", "content_type", "query_string",
"remote_addr", "remote_host", "remote_user",
"request_method", "server_name", "server_port"]
def _set_headers(self, request, headers):
"""
Inherit headers from batch request by default.
Override with values given in subrequest.
"""
self.META = request.META if request is not None else {}
if headers is not None:
self.META.update(self._transform_headers(headers))
def _transform_headers(self, headers):
"""
For every header:
- replace - to _
- prepend http_ if necessary
- convert to uppercase
"""
result = {}
for header, value in headers.items():
header = header.replace("-", "_")
header = "http_{header}".format(header=header) \
if header.lower() not in self._wsgi_headers \
else header
result.update({header.upper(): value})
return result
class BatchRequestsFactory(object):
response_variable_regex = re.compile(r'({result=(?P<name>[\w\d_]+):\$\.(?P<value>[\w\d_.*]+)})')
def __init__(self, request):
self.request = request
self.request_serializer = BatchRequestSerializer(data=request.data)
self.request_serializer.is_valid(raise_exception=True)
self.update_soft_dependencies()
self.named_responses = {}
def update_soft_dependencies(self):
for request_data in self.request_serializer.validated_data['batch']:
parents = request_data.get('depends_on', [])
for part in request_data.values():
params = re.findall(
self.response_variable_regex, force_text(part)
)
parents.extend(map(lambda param: param[1], params or []))
request_data['depends_on'] = set(parents)
def _prepare_formdata_body(self, data, files=None):
if not data and not files:
return ''
match = re.search(r'boundary=(?P<boundary>.+)', self.request.content_type)
assert match
boundary = match.groupdict()['boundary']
body = ''
for key, value in data.items():
value = value if isinstance(value, str) else json.dumps(value)
body += '--{}\r\nContent-Disposition: form-data; name="{}"\r\n\r\n{}\r\n'.format(boundary, key, value)
if files:
for key, attachment in files.items():
attachment.seek(0)
attachment_body_part = '--{0}\r\nContent-Disposition: form-data; name="{1}"; filename="{2}"\r\n' \
'Content-Type: {3}\r\n' \
'Content-Transfer-Encoding: binary\r\n\r\n{4}\r\n'
body += attachment_body_part.format(
boundary, key, attachment.name, attachment.content_type, attachment.read()
)
body += '--{}--\r\n'.format(boundary)
return body
def _prepare_urlencoded_body(self, data):
raise NotImplementedError
def _prepare_json_body(self, data):
return json.dumps(data)
def _process_attr(self, attr):
params = re.findall(
self.response_variable_regex, attr
)
if not params:
return attr
for url_param in params:
if url_param[1] not in self.named_responses:
raise ValidationError('Named request {} is missing'.format(url_param[1]))
result = get_attribute(
self.named_responses[url_param[1]].data,
url_param[2].split('.')
)
if result is None:
raise RequestAttributeError('Empty result for {}'.format(url_param[2]))
if isinstance(result, list):
result = ','.join(map(str, result))
if attr == url_param[0]:
attr = result
else:
attr = attr.replace(url_param[0], str(result))
return attr
def updated_obj(self, obj):
"""
For now, i'll update only dict values. Later it can be used for keys/single values/etc
:param obj: dict
:return: dict
"""
if isinstance(obj, dict):
for key, value in obj.items():
obj[key] = self.updated_obj(value)
elif isinstance(obj, str):
return self._process_attr(obj)
return obj
def get_requests_data(self):
return self.request_serializer.validated_data['batch']
def generate_request(self, request_data):
request_data['data'] = self.updated_obj(request_data['data'])
request_data['relative_url'] = self._process_attr(request_data['relative_url'])
if self.request.content_type.startswith('multipart/form-data'):
request_data['_body'] = self._prepare_formdata_body(request_data['data'],
files=request_data.get('files', {}))
elif self.request.content_type.startswith('application/x-www-form-urlencoded'):
request_data['_body'] = self._prepare_urlencoded_body(request_data['data'])
elif self.request.content_type.startswith('application/json'):
request_data['_body'] = self._prepare_json_body(request_data['data'])
else:
raise ValidationError('Unsupported content type')
return BatchRequest(self.request, request_data)
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,216
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/urls.py
|
try:
from django.conf.urls import url
except ImportError:
# django 2.0
from django.urls import re_path as url
from drf_batch_requests import views
app_name = 'drt_batch_requests'
urlpatterns = [
url('^', views.BatchView.as_view())
]
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,217
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/exceptions.py
|
class BatchRequestException(Exception):
pass
class RequestAttributeError(BatchRequestException):
""" Empty request attribute. Unable to perform request. """
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,218
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/tests/urls.py
|
try:
from django.conf.urls import include, url
except ImportError:
# django 2.0
from django.urls import re_path as url, include
from tests import views
urlpatterns = [
url('batch/', include('drf_batch_requests.urls', namespace='drf_batch')),
url('test/', views.TestAPIView.as_view()),
url('test_fbv/', views.test_fbv),
url('test-files/', views.TestFilesAPIView.as_view()),
url('test-non-json/', views.SimpleView.as_view()),
]
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,219
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/views.py
|
from importlib import import_module
from django.db import transaction
from rest_framework.response import Response
from rest_framework.views import APIView
from drf_batch_requests import settings as app_settings
from drf_batch_requests.exceptions import RequestAttributeError
from drf_batch_requests.graph import RequestGraph
from drf_batch_requests.request import BatchRequestsFactory
from drf_batch_requests.response import BatchResponse, DummyBatchResponse, ResponseHeader
from drf_batch_requests.utils import generate_node_callback
try:
from json import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
class BatchView(APIView):
permission_classes = []
def get_requests_consumer_class(self):
mod, inst = app_settings.REQUESTS_CONSUMER_BACKEND.rsplit('.', 1)
mod = import_module(mod)
return getattr(mod, inst)
def get_requests_consumer(self):
return self.get_requests_consumer_class()()
@transaction.atomic
def post(self, request, *args, **kwargs):
requests = {}
responses = {}
requests_factory = BatchRequestsFactory(request)
requests_data = requests_factory.get_requests_data()
ordered_names = list(map(lambda r: r['name'], requests_data))
requests_graph = RequestGraph(requests_data)
backend = self.get_requests_consumer()
while True:
available_nodes = list(requests_graph.get_current_available_nodes())
for node in available_nodes:
try:
current_request = requests_factory.generate_request(node.request)
except RequestAttributeError:
# todo: set fail reason
node.fail()
start_callback = generate_node_callback(node, 'start')
success_callback = generate_node_callback(node, 'success')
fail_callback = generate_node_callback(node, 'fail')
if backend.consume_request(current_request, start_callback=start_callback,
success_callback=success_callback, fail_callback=fail_callback):
requests[node.name] = current_request
is_completed = requests_graph.is_completed()
for current_request, response in backend.responses.items():
if current_request.name in responses:
continue
header_items = response.items()
result = BatchResponse(
current_request.name,
response.status_code,
response.content.decode('utf-8'),
headers=[
ResponseHeader(key, value)
for key, value in header_items
],
omit_response_on_success=current_request.omit_response_on_success,
status_text=response.reason_phrase
)
if current_request.name:
requests_factory.named_responses[current_request.name] = result
responses[current_request.name] = result.to_dict()
if is_completed:
break
ordered_responses = [responses.get(name, DummyBatchResponse(name).to_dict()) for name in ordered_names]
return self.finalize_response(request, Response(ordered_responses))
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,220
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_requests/serializers.py
|
import json
from django.core.files import File
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from drf_batch_requests.utils import generate_random_id
class SingleRequestSerializer(serializers.Serializer):
method = serializers.CharField()
relative_url = serializers.CharField()
headers = serializers.JSONField(required=False)
name = serializers.CharField(required=False)
depends_on = serializers.JSONField(required=False)
body = serializers.JSONField(required=False, default={})
# attached files formats: ["a.jpg", "b.png"] - will be attached as it is, {"file": "a.jpg"} - attach as specific key
attached_files = serializers.JSONField(required=False)
data = serializers.SerializerMethodField()
files = serializers.SerializerMethodField()
def validate_headers(self, value):
if isinstance(value, dict):
return value
def validate_relative_url(self, value):
if not value.startswith('/'):
raise self.fail('Url should start with /')
return value
def validate_body(self, value):
if isinstance(value, dict):
return value
try:
json.loads(value)
except (TypeError, ValueError):
self.fail('invalid')
return value
def validate(self, attrs):
if 'name' not in attrs:
attrs['name'] = generate_random_id()
if 'depends_on' in attrs:
value = attrs['depends_on']
if not isinstance(value, (str, list)):
raise ValidationError({'depends_on': 'Incorrect value provided'})
if isinstance(value, str):
attrs['depends_on'] = [value]
return attrs
def get_data(self, data):
body = data['body']
if isinstance(body, dict):
return body
return json.loads(body)
def get_files(self, attrs):
if 'attached_files' not in attrs:
return []
attached_files = attrs['attached_files']
if isinstance(attached_files, dict):
return {
key: self.context['parent'].get_files()[attrs['attached_files'][key]] for key in attrs['attached_files']
}
elif isinstance(attached_files, list):
return {
key: self.context['parent'].get_files()[key] for key in attrs['attached_files']
}
else:
raise ValidationError('Incorrect format.')
class BatchRequestSerializer(serializers.Serializer):
batch = serializers.JSONField()
files = serializers.SerializerMethodField()
def get_files(self, attrs=None):
return {fn: f for fn, f in self.initial_data.items() if isinstance(f, File)}
def validate_batch(self, value):
if not isinstance(value, list):
raise ValidationError('List of requests should be provided to do batch')
r_serializers = list(map(lambda d: SingleRequestSerializer(data=d, context={'parent': self}), value))
errors = []
for serializer in r_serializers:
serializer.is_valid()
errors.append(serializer.errors)
if any(errors):
raise ValidationError(errors)
return [s.data for s in r_serializers]
def validate(self, attrs):
attrs = super(BatchRequestSerializer, self).validate(attrs)
files_in_use = []
for batch in attrs['batch']:
if 'attached_files' not in batch:
continue
attached_files = batch['attached_files']
if isinstance(attached_files, dict):
files_in_use.extend(attached_files.values())
elif isinstance(attached_files, list):
files_in_use.extend(attached_files)
else:
raise ValidationError({'attached_files': 'Invalid format.'})
missing_files = set(files_in_use) - set(self.get_files().keys())
if missing_files:
raise ValidationError('Some of files are not provided: {}'.format(', '.join(missing_files)))
return attrs
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,221
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/tests/mixins.py
|
try:
from django.urls import resolve
except ImportError:
from django.core.urlresolvers import resolve
from rest_framework.test import APIRequestFactory
from rest_framework.test import APITestCase as OriginalAPITestCase
from rest_framework.test import force_authenticate
class APITestCase(OriginalAPITestCase):
"""
Base test case for testing APIs
"""
maxDiff = None
def __init__(self, *args, **kwargs):
super(APITestCase, self).__init__(*args, **kwargs)
self.user = None
def forced_auth_req(self, method, url, user=None, data=None, request_format='json', **kwargs):
"""
Function that allows api methods to be called with forced authentication
:param method: the HTTP method 'get'/'post'
:type method: str
:param url: the relative url to the base domain
:type url: st
:param user: optional user if not authenticated as the current user
:type user: django.contrib.auth.models.User
:param data: any data that should be passed to the API view
:type data: dict
"""
factory = APIRequestFactory()
view_info = resolve(url)
data = data or {}
view = view_info.func
req_to_call = getattr(factory, method)
request = req_to_call(url, data, format=request_format, **kwargs)
user = user or self.user
force_authenticate(request, user=user)
response = view(request, *view_info.args, **view_info.kwargs)
if hasattr(response, 'render'):
response.render()
return response
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,222
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/drf_batch_example/urls.py
|
try:
from django.conf.urls import url
except ImportError:
# django 2.0
from django.urls import re_path as url
from drf_batch_example import views
app_name = 'drf_batch_requests_tests'
urlpatterns = [
url('test', views.TestView.as_view()),
]
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
19,223
|
roman-karpovich/drf-batch-requests
|
refs/heads/master
|
/tests/test_request.py
|
from django.test import SimpleTestCase
from rest_framework.test import APIRequestFactory
from drf_batch_requests.request import BatchRequest
class RequestTest(SimpleTestCase):
def test_subrequest_headers(self):
# Arrange
data = {
'method': 'get',
'relative_url': '/test/',
'headers': {
'header-1': 'whatever',
'Content-Length': 56,
},
'_body': ''
}
request = APIRequestFactory().post('/test')
# Act
result = BatchRequest(request, data)
# Assert
self.assertIn('HTTP_HEADER_1', result.META)
self.assertIn('CONTENT_LENGTH', result.META)
|
{"/tests/test_view.py": ["/tests/mixins.py"], "/drf_batch_requests/request.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/serializers.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/views.py": ["/drf_batch_requests/exceptions.py", "/drf_batch_requests/graph.py", "/drf_batch_requests/request.py", "/drf_batch_requests/response.py", "/drf_batch_requests/utils.py"], "/drf_batch_requests/serializers.py": ["/drf_batch_requests/utils.py"], "/tests/test_request.py": ["/drf_batch_requests/request.py"], "/drf_batch_requests/backends/sync.py": ["/drf_batch_requests/backends/base.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.