-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
executable file
·1692 lines (1269 loc) · 52.9 KB
/
Copy pathdata.py
File metadata and controls
executable file
·1692 lines (1269 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env/python
#
# - - - - I A R - - - -
#
# s1311631 Angus Pearson
# s1346981 Jevgenij Zubovskij
#
from __future__ import print_function
import redis
import whiptail
from state import *
import sys
import getopt
import matplotlib.pyplot as plt
import math
import time
import yaml
import json
import pprint
import re
import constants
import utils
# Check for ROS (http://ros.org/) support
try:
import rospy
ros = True
from std_msgs.msg import String
from geometry_msgs.msg import PoseWithCovariance, PoseStamped, Pose, Point32, PoseArray
from nav_msgs.msg import Odometry, Path, OccupancyGrid
from sensor_msgs.msg import PointCloud, ChannelFloat32
import tf
except ImportError as e:
print(e)
print("[NOTICE] Continuing without ROS integration")
ros = False
del e
# ROS Import check wrapper
def requireros(func):
def check_and_call(*args, **kwargs):
if not ros:
raise ImportError("[FATAL] ROS (rospy) Not supported/found")
else:
return func(*args, **kwargs)
return check_and_call
# Check for Pillow (Python Imaging Oibrary)
try:
import PIL
import numpy as np
pil = True
except ImportError as e:
print(e)
print("[NOTICE] Continuing withut PIL support")
pil = False
del e
# PIL Import check wrapper
def requireimage(func):
def check_and_call(*args, **kwargs):
if not pil:
raise ImportError("[FATAL] PIL (Image Lib) Not supported/found")
else:
return func(*args, **kwargs)
return check_and_call
# ^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
class DSException(Exception):
pass
# ^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
class DataStore(object):
'''
Primary Data Munging class, handles chatter with Redis and ROS.
`data.py` can be used interactively.
_._
_.-``__ ''-._
_.-`` `. `_. ''-._
.-`` .-```. ```\/ _.,_ ''-._
( ' , .-` | `, )
|`-._`-...-` __...-.``-._|'` _.-'|
| `-._ `._ / _.-' |
`-._ `-._ `-./ _.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' |
`-._ `-._`-.__.-'_.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' |
`-._ `-._`-.__.-'_.-' _.-'
`-._ `-.__.-' _.-'
`-._ _.-'
`-.__.-'
'''
def __init__(self, host='localhost', db=0, port=6379):
'''
Instantiate a DataStore class
Arguments:
host -- Redis server to use, defaults to 'localhost'
db -- Redis database to use, default 0
port -- Port the Redis server is listening on
Instantiates it's own StrictRedis, PrettyPrint and Whiptail classes
'''
if host.endswith(".sock"):
print("Using UNIX Socket for Redis")
self.r = redis.StrictRedis(unix_socket_path=host)
else:
self.r = redis.StrictRedis(host=host, port=port, db=db)
self.wt = whiptail.Whiptail()
self.pp = pprint.PrettyPrinter(indent=1)
self.og = GridManager(self.r)
# Redis List and Channel name
self.listname = "statestream"
self.goallist = "goalstream"
self.mapchan = self.og.channel
self.partchan = "particlestream"
# ROS Topics
self.posetopic = self.listname + "pose"
self.odomtopic = self.listname + "odom"
self.disttopic = self.listname + "dist"
self.goaltopic = self.listname + "goal"
self.maptopic = self.listname + "map"
self.parttopic = self.listname + "particles"
# Test Redis connection
if not self.r.ping():
raise redis.ConnectionError("No PONG from PING!")
def __str__(self):
'''
return a string representation of self
'''
return self.pp.pformat(self.__dict__)
__repr__ = __str__
def __del__(self):
self.save()
def keys(self):
'''
Returns a list of all keys in the Redis datastore
'''
return self.r.keys()
def push(self, pose, ranges=None):
'''
Push a new 'Pose' onto Redis, and optionally distance data.
Arguments:
pose -- Either GenericState instance or a dict, must have
x, y, t and theta members/keys
ranges -- List of raw sensor readings (float), length 8
Pushed are added to the history list and also published to the
predefined Redis channels
'''
# Type duck between GenericState and a dict
if isinstance(pose, GenericState):
hmap = {
't' : pose.time,
'x' : pose.x,
'y' : pose.y,
'theta': pose.theta
}
else:
hmap = {
't' : pose['t'],
'x' : pose['x'],
'y' : pose['y'],
'theta': pose['theta']
}
# Name we'll give this pose in Redis
mapname = "pose-" + str(hmap['t'])
# Build hashmap from given state class
if ranges is not None and len(ranges) == 8:
hmap.update({
'r0' : float(ranges[0]),
'r1' : float(ranges[1]),
'r2' : float(ranges[2]),
'r3' : float(ranges[3]),
'r4' : float(ranges[4]),
'r5' : float(ranges[5]),
'r6' : float(ranges[6]),
'r7' : float(ranges[7])
})
# For each part of the _python_ dict we
# create a Redis hashmap using the time as index
self.r.hmset(mapname, hmap)
# We push a reference to this new hashmap onto
# the statestream list
self.r.rpush(self.listname, mapname)
# Also publish onto a channel
self.r.publish(self.listname, mapname)
return hmap
def push_goal(self, path):
'''
Similar to push(), pushes a new goal path to Redis.
Arguments:
path -- A list of dicts e.g. [{'x': 0.0, 'y':100.0},{'x': 1502.5, 'y': 1337.0}]
'''
# Clear out old points
for key in self.r.lrange(self.goallist, 0, -1):
self.r.delete(key)
# Delete old list
self.r.delete(self.goallist)
pointnum = 0
for point in path:
pointname = "goal" + str(pointnum)
pointnum += 1
self.r.hmset(pointname, point)
self.r.rpush(self.goallist, pointname)
self.r.publish(self.goallist, self.goallist)
def push_particles(self):
raise NotImplementedError()
def sub(self):
'''
Mostly a test method, subscribe to Redis channels and print
any messages that come over it.
'''
sub = self.r.pubsub()
sub.subscribe([self.listname, self.goallist])
# Loop until stopped plotting the path
try:
for item in sub.listen():
if self.r.exists(item['data']):
data = self.r.hgetall(item['data'])
item['data'] = data
self.pp.pprint(item)
except KeyboardInterrupt as e:
print("Stopping...")
pass
def get(self, start=0, stop=-1):
'''
Returns a list in-order over the range given in args. Default is
to return the entire list.
Arguments:
start -- First list index
stop -- Last list index, -1 means all
'''
keys = self.r.lrange(self.listname, int(start), int(stop))
ret = list()
# Pull all the hashmaps out of the store
for key in keys:
ret.append(self.r.hgetall(key))
return ret
def get_dict(self, start=0, stop=-1):
'''
Extends the behaviour of get(), provides a time-keyed
dictionary of data as opposed to a list
Arguments:
start -- First list index
stop -- Last list index, -1 means all
'''
# Return a dictionary instead of a list
lst = self.get(start, stop)
ret = dict()
for item in lst:
# time as key, dict as value
ret[int(item['t'])] = item
return ret
def delete_before(self, time):
'''
Remove data with a key from earlier than specified from Redis
Arguments:
time -- cutoff time, any value less than this will be killed
'''
if time < 0:
raise ValueError("Time must be positive you crazy person!")
keys = self.r.lrange(self.listname, 0, -1) # All keys in our stream
for key in keys:
if int(key) <= int(time):
# Remove from list
self.r.lrem(self.listname, count=0, value=key)
# delete the key (hashmap)
self.r.delete(key)
def plot(self, start=0, stop=-1):
self.static_plot(start, stop)
def live_plot(self):
print("Deprecated, rospipe + rviz will work better")
try:
pubsub = self.r.pubsub()
pubsub.subscribe([self.listname])
plt.axis([-500, 500, -500, 500])
plt.ion()
while True:
# Loop until stopped plotting the path
for item in pubsub.listen():
#print(item)
if self.r.hexists(item['data'], 'x'):
data = self.r.hgetall(item['data'])
plt.scatter(float(data['x']), float(data['y']))
#print(str(data['x']) + " " + str(data['y']))
plt.show()
plt.pause(0.0001)
except KeyboardInterrupt as e:
print(e)
def static_plot(self, start=0, stop=-1):
'''
Produces a matplotlib plot of all odometry data in redis.
Arguments:
start -- First list index
stop -- Last list index, -1 means all
'''
data = self.get(start, stop)
xs = []
ys = []
for point in data:
xs.append(point['x'])
ys.append(point['y'])
plt.axis([-600, 600, -600, 600])
plt.ion()
plt.plot(xs, ys)
plt.show()
@requireros
def rospipe(self):
'''
Pipes messages published on Redis channels to ROS Topics,
transforming parts of the data allowing other stuff that
speaks ROS to interact with the data.
'''
print('''
__ __ __ _______ _____ _____
/ \ / \ / \ | ____ \ / ___ \ / ____|
\__/ \__/ \__/ | | \ | | / \ | | |
__ __ __ | | | | | | | | | \____
/ \ / \ / \ | \___/ / | | | | \_____ \
\__/ \__/ \__/ | __ \ | | | | \ |
__ __ __ | | \ | | | | | | |
/ \ / \ / \ | | | | | \___/ | ____/ |
\__/ \__/ \__/ |_| |_| \_____/ |______/
''')
print("Piping Redis ---> ROS")
# Pipe data out of Redis into ROS
rg = ROSGenerator()
pose_pub = rospy.Publisher(self.posetopic, PoseStamped, queue_size=100)
odom_pub = rospy.Publisher(self.odomtopic, Odometry, queue_size=100)
dist_pub = rospy.Publisher(self.disttopic, PointCloud, queue_size=100)
part_pub = rospy.Publisher(self.parttopic, PoseArray, queue_size=100)
goal_pub = rospy.Publisher(self.goaltopic, Path, queue_size=10)
map_pub = rospy.Publisher(self.maptopic, OccupancyGrid, queue_size=100)
tbr = tf.TransformBroadcaster()
# Pre-subscription, we should load the OccupancyGrid Map.
# This'll be the only one of our ROS classes that persists
print("generating map...")
og_map = rg.gen_map(self.og)
width, height = self.og._get_map_dimensions()
print("done.")
sub = self.r.pubsub()
sub.subscribe([self.listname, self.goallist, self.mapchan, self.partchan])
map_pub.publish(og_map)
# Loop until stopped plotting the path
for item in sub.listen():
if rospy.is_shutdown():
print("\nStopping rospipe...")
break
if item['type'] == "subscribe":
rospy.loginfo("Subscribed successfully to " + item['channel'])
continue
try:
if item['channel'] == self.listname:
# Stream of poses and distance data
# Pull from redis:
data = self.r.hgetall(item['data'])
required_keys = ['x','y','theta','t']
for key in required_keys:
if key not in data.keys():
raise DSException("Missing key {} from hashmap {}:{} on channel {}"
"".format(key, item['data'], data, item['channel']))
# Generate a new Quaternion based on the robot's pose
quat = tf.transformations.quaternion_from_euler(0.0, 0.0,
float(data['theta']))
# Generate new pose
pose = rg.gen_pose(data, quat)
pose_pub.publish(pose)
# Publish Khepera transform
tbr.sendTransform((pose.pose.position.x, pose.pose.position.y, 0),
quat, rospy.Time.now(), "khepera", "map")
# Generate odometry data
odom = rg.gen_odom(data, quat)
odom_pub.publish(odom)
# Generate pointcloud of distances
dist = rg.gen_dist(data)
dist_pub.publish(dist)
#rospy.loginfo(" Redis " + str(item['channel']) + " --> ROS")
elif item['channel'] == self.goallist:
# Less frequent planning channel
# Pull co-ords from Redis
data = self.r.lrange(self.goallist, 0, -1)
path = rg.gen_path()
quat = tf.transformations.quaternion_from_euler(0.0, 0.0, 0.0)
for datapoint in data:
raw_pose = self.r.hgetall(datapoint)
required_keys = ['x','y']
for key in required_keys:
if key not in raw_pose.keys():
raise DSException("Missing key " + str(key) + " from point " +
str(raw_pose) + " on channel " +
str(item['channel']))
this_pose = rg.gen_pose(raw_pose, quat)
path.poses.append(this_pose)
goal_pub.publish(path)
#rospy.loginfo(" Redis " + str(item['channel']) + " --> ROS")
elif item['channel'] == self.mapchan:
# Handle a map diff (update)
# TODO: Handle dimension changes in a less slow way
# TODO: Handle granularity changes
# A sharp represents a meta message
if not item['data'].startswith("#"):
toks = item['data'].split(' ')
if len(toks) % 2 != 0:
raise DSException("odd number of tokens, eww {}:{} {}"
"".format(len(toks), len(toks)%2, toks))
toks = zip(toks[::2], toks[1::2])
for key, occ in toks:
x, y = self.og._dekey(key)
occ = max(-1, min(100, int(float(occ))))
# in-place update this grid in og_map (the ROS OccupancyGrid instance)
# the map takes absolute coordinates to array index
x, y = self.og._genindex(x, y)
y *= width # row major, so scale y onto a flat array
og_map.data[int(x+y)] = occ # Toootaly worked first time
#rospy.loginfo("Map update {} --> {}".format(item['data'], occ))
else:
if item['data'].startswith("#bounds"):
new_bounds = yaml.load(item['data'].strip("#bounds"))
if type(new_bounds) is not dict:
raise DSException("Couldn't deserialise {} message '{}' into dict - got {}"
"".format(item['channel'], item['data'], type(new_bounds)))
# TODO: In-place update, waaaay faster
# 'bounds check' with True, which will resize the bounds
self.og._bounds_check(new_bounds['minx'], new_bounds['miny'], True)
self.og._bounds_check(new_bounds['maxx'], new_bounds['maxy'], True)
# SLOOOOOOOOW, maybe blocking subscribers
rospy.logerr("MAP RELOADING")
rospy.logwarn("Update occurred outwith bounding box, reloading map")
rospy.logwarn("This will take a while...")
try:
og_map = rg.gen_map(self.og)
except Exception as e:
rospy.logerr("Exception encountered when reloading: {}".format(e))
width, height = self.og._get_map_dimensions()
rospy.logwarn("DONE WITH RELOAD")
# ALways refresh
map_pub.publish(og_map)
elif item['channel'] == self.partchan:
# Pull from list of the same name
particles = self.r.lrange(self.partchan, 0, -1)
particles = map(json.loads, particles)
poses = rg.gen_particles(particles)
part_pub.publish(poses)
else:
# If we get an unexpected channel, complain loudly.... Thish should never happen
complaint = "Encountered unhandleable channel '" + str(item['channel']) + "'"
raise DSException(complaint)
except DSException as e:
rospy.logwarn(str(e))
#raise e
def replay(self, speed=1.0, limit=-1):
'''
Replay data already stored, by re-publishing to the Redis channel
Arguments:
speed -- Multiplier for replay speed, 1.0 is real time, > 1 is faster. Default 1.0
limit -- How far back to look (number of epochs) default -1 (all)
'''
print('''
____________________________
/|............................|
| |: KHEPERA REWIND :|
| |: "Redis & Co." :|
| |: ,-. _____ ,-. :|
| |: ( `)) [_____] ( `)) :|
|v|: `-` ' ' ' `-` :|
|||: ,______________. :|
|||...../::::o::::::o::::\.....|
|^|..../:::O::::::::::O:::\....|
|/`---/--------------------`---|
`.___/ /====/ /=//=/ /====/____/
`--------------------'
/// /#//#/
///-------------------------/#/-/#/
\\\\\-------------------------\\#\\-\\#\\
\\\\\ \\#\\\\#\\
''')
data = self.r.lrange(self.listname, 0, limit)
try:
for epoch in data:
print("epoch " + str(epoch))
self.r.publish(self.listname, epoch)
time.sleep(constants.MEASUREMENT_PERIOD_S * speed)
except KeyboardInterrupt as e:
print(e)
print("Replay done.")
def _destroy(self):
'''
Clear out all (literally all) data held in Redis
by flushing all keys from the DB. Interactive (uses whiptail prompt)
'''
if self.wt.confirm("Really destroy all data in Redis store?\n\nThis is not undoable!\n(run FLUSHDB)",
default='no'):
self.r.flushdb()
print("!!! Flushed Redis Data Store !!!")
else:
print("Did not flush Redis Store")
def save(self):
'''
Copy DB to disk
'''
return self.r.save()
# ^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
class GridManager(object):
'''
Handles the Occupancy Grid's mechanics, as it's a more complex datastructure.
Gets passed a reference to (presumably) a `DataStore`'s Redis instance.
Origin is centered in the map.
The Map is _sparse_, in that it is hypothetically infinitely large.
'''
def __init__(self, redis, granularity=10.0, debug=False):
'''
Arguments:
granularity -- Minimum distance representable in the map, as a decimal multiple of
whatever units the distances are given in.
Note: Very small granularities and very large granularities that may have '10e-12'
representations by default will break as they cannot be correctly keyed and de-keyed.
Standards & Conventions:
map:x:y = {
'occ' : -1 or [0..100]
}
Axes:
(forward)
X
^
|
|
|
Y <------- Z
(left) (up)
Tests:
------
Easiest to require 10.0 granularity for all tests
>>> ds.og.granularity
10.0
'''
self.DEBUG = debug
# Origin is bottom left corner, x left, y up
self._testworld = """\
????????????????????????????????
?XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX?
?X XX XX X?
?X X XX X?
?X XXXXXXX XX X?
?X XXXXXXX X XXXX?
?X XX X X?
?X XX X?
?X X?
?X XX X?
?X XXXX X?
?X XX X?
?X XX X?
?X XXXX XXXXXXX?
?X XX XX X X?
?X XX X X?
?X XX X X?
?X XX X?
?X XXXX XX X?
???? XXXX XXXX ??
???? ? X??X ??
?????? ???? XXXX ???
????? ???? ???
?????? ??? ????? ????
??????? ?????? ?????
???????? ??????????????
??????? ?? ???????????????
???????????? ???????????????
???????????????? ??????????
????????????????? ???????????
????????????????????????????????
????????????????????????????????
????????????????????????????????
????????????????????????????????
"""
self.granularity = granularity
self.wt = whiptail.Whiptail()
self.pp = pprint.PrettyPrinter(indent=1)
self.r = redis
# Redis list and channel names
self.mapname = "map"
self.mapmeta = self.mapname + "-meta"
self.channel = self.mapname + "-update"
# Default origin (location of the map)
# wit respect to the fixed reference frame
self.origin = {
'x' : 0.0,
'y' : 0.0,
'z' : 0.0,
'quat_x' : 0.0,
'quat_y' : 0.0,
'quat_z' : 0.0,
'quat_w' : 0.0
}
# Default size
self.bounds = {
'maxx' : 1500.0,
'maxy' : 1500.0,
'minx' : -1500.0,
'miny' : -1500.0
}
# If prior config exists, pull it in
for k, v in self.origin.iteritems():
if self.r.hexists(self.mapmeta, k):
self.origin[k] = float(self.r.hget(self.mapmeta, k))
if self.DEBUG:
print("{} got {} = {} from Redis".format(self.__class__.__name__, k, self.origin[k]))
for k, v in self.bounds.iteritems():
if self.r.hexists(self.mapmeta, k):
self.bounds[k] = float(self.r.hget(self.mapmeta, k))
if self.DEBUG:
print("{} got {} = {} from Redis".format(self.__class__.__name__, k, self.bounds[k]))
if self.r.hexists(self.mapmeta, "granularity"):
self.granularity = float(self.r.hget(self.mapmeta, "granularity"))
print("{} got granularity = {} from Redis".format(self.__class__.__name__, self.granularity))
if self.granularity == 0:
raise ValueError("Granularity CANNOT be zero, you crazy person!")
# Push origin and boundaries back to redis
self.r.hmset(self.mapmeta, self.origin)
self.r.hmset(self.mapmeta, self.bounds)
self.r.hmset(self.mapmeta, {
"granularity" : self.granularity
})
if self.DEBUG:
self.pp.pprint(self.bounds)
print("Using redis key '{}' for map, channel '{}' for updates"
"".format(self.mapname, self.channel))
# Regex to turn a serialised key into coords
# This re finds a combination of two floats or two ints
# IMPORTANT: Must remain consistent with _genkey()
self._dekey_re = re.compile("([+-]?\d+\.\d*|[+-]?\d+):([+-]?\d+\.\d*|[+-]?\d+)$")
def __str__(self):
'''
return a string representation of self
'''
return self.pp.pformat(self.__dict__)
__repr__ = __str__
def get(self, x, y):
'''
Returns the int held at the given grid coord's occupancy value
Handles type expetions, snaps to grid
BE AWARE coords will silently be snapped to the grid, allowing
querying at higher resolution than is represented in the map.
'''
return self._get_keyed([self._genkey(x, y)])[0]
def mget(self, pts):
'''
Returns a list of ints representing the occupancies of the points in the argument
Makes use of Redis pipelining, so haz all the speeds
BE AWARE coords will silently be snapped to the grid, allowing
querying at higher resolution than is represented in the map.
Arguments:
pts -- List of (x,y) tuples
'''
return self._get_keyed(map(lambda p: self._genkey(p[0],p[1]), pts))
def _get_keyed(self, ks):
'''
Similar to get(), though takes a list of strings. Suggested you don't use
this much as it is breakier. Almost always generate ks with
GridManager._genkey(str)
Arguments:
ks -- list(str), names of redis keys of grid
'''
pipe = self.r.pipeline()
for k in ks:
pipe.hget(k, 'occ')
occs = pipe.execute()
def safe_int_cast(val):
try:
return int(val)
except (ValueError, TypeError, AttributeError):
return None
return map(safe_int_cast, occs)
def get_map(self, rtype='L', default=-1):
'''
Return an array representing the whole map. Occupancies are ints,
default is unknown (-1). Range should be [-1..100].
Arguments:
rtype -- Type to return, default 'L'
- 'L' is a 2D python row-major list (biggest me use)
- 'N' is a 2D row-major NumPy ndarray
- 'C' is a flattened row-major NumPy ndarray (C style)
- 'F' is a flattened row-major NumPy ndarray (C style)
default -- Default value to populate the map with
NOTE: This method returns a fully populated map wthin the bounding
box, it is *not* going to be as fast.
For speed use methods such as get() and Redis subscribers to
in-place update a cached map.
'''
xwidth, yheight = self._get_map_dimensions()
data = np.ndarray((yheight, xwidth), dtype=int)
data.fill(int(default))
ks = self._get_map_keys()
os = self._get_keyed(ks)
assert len(os) == len(ks), "Length of key and value lists does not match!"
for index, k in enumerate(ks):
x, y = self._dekey(k)
xi, yi = self._genindex(x, y)
data[yi][xi] = os[index]
if rtype == 'N':
return data
elif rtype == 'C':
return data.flatten('C') # C/C++ Style, row major
elif rtype == 'F':
return data.flatten('F') # FORTRAN Style, col major
# Default ('L') give a 2D list
return data.tolist()
def _get_map_keys(self):
'''
Super simple, dump raw 100% organic map Redis data at your face
'''
return self.r.smembers(self.mapname)
def _get_map_dimensions(self):
'''
Returns array size needed to fit map given bounds and granularity.
'''
xwidth = 1 + int(math.ceil((-self.bounds['minx'] + self.bounds['maxx']) / self.granularity))
yheight = 1 + int(math.ceil((-self.bounds['miny'] + self.bounds['maxy']) / self.granularity))
return xwidth, yheight
def _genindex(self, x, y):
'''
Given a coordinate on grid return the corresponding index into a 2D
array for that point, row major:
[[ (0,0) , (1,0) , ... , (len(x),0) ],
...
[ (0,len(y)), (1,len(y)), ... , (len(x),len(y))]]
This method is very similar to GridManager._get_map_dimensions(), which could
be used to initialise an array thn indexed with this method.
Arguments:
x -- x (forward) axis coord
y -- y (left) axis coord
'''
xoffset = math.floor(-self.bounds['minx'] / self.granularity)
yoffset = math.floor(-self.bounds['miny'] / self.granularity)
xi = int((self._snap(x) / self.granularity) + xoffset)
yi = int((self._snap(y) / self.granularity) + yoffset)
if xi < 0 or yi < 0:
raise IndexError("Co-ordinates ({},{}) yielding index [{},{}] out of bounds; "
"Bounds are {}".format(x, y, xi, yi, self.bounds))
return xi, yi
def _snap(self, coord):
'''
Snap a given coordinate to the grid
Snapping treats the occupancy grid squares as being centred on the pysical (e.g.)
pose co-ordinate space: (Shown bracketed '(0,0)', OG shown braced '[0,0]')
Y
^
|
________|________
| | |
| | |
| | |
| |(0,0) |
| \-----------> X
| |
| |
| [0,0] |
\_________________/
Arguments:
coord -- Arbuitary coordinate (float, int)
Returns:
coord -- Snapped to grid. int or float, depending on whether the granularity is an
integer or float.