Skip to content

Commit e85b4d8

Browse files
committed
Import cpp library in algorithms.py instead of __init__.py
Also some whitespace cleanup / unification and mode sanitation.
1 parent 0f2f899 commit e85b4d8

File tree

10 files changed

+69
-61
lines changed

10 files changed

+69
-61
lines changed
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-
from libcuckoo_time_translator_python import *
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from .libcuckoo_time_translator_python import *

cuckoo_time_translator_python/python/cuckoo_time_translator/batch_algo.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,26 @@
33
import numpy as np
44
import sys
55

6+
67
def chunks(l, n):
78
"""Yield successive n-sized chunks from l."""
89
for i in range(0, len(l), n):
910
yield l[i:i + n]
1011

11-
def printDelayStat(delays, name, outlierLimit = None, file = None, chunkSizes = ()):
12+
13+
def printDelayStat(delays, name, outlierLimit=None, file=None, chunkSizes=()):
1214
if delays is not None and len(delays):
1315
if outlierLimit:
1416
delays = delays[delays < outlierLimit]
15-
16-
delays = np.array(delays) * 1e3 # convert to ms
17-
17+
18+
delays = np.array(delays) * 1e3 # convert to ms
19+
1820
files = [sys.stdout]
1921
if file: files.append(file)
2022
for f in files:
21-
print("%s: mean=%f ms, std=%f ms" % (name, np.mean(delays), np.std(delays)), file = f)
23+
print("%s: mean=%f ms, std=%f ms" % (name, np.mean(delays), np.std(delays)), file=f)
2224
for n in chunkSizes:
23-
print("std(%s over %d chunks) = %g ms" %(name, n, np.std([ np.mean(c) for c in chunks(delays, n)])), file = f)
25+
print("std(%s over %d chunks) = %g ms" % (name, n, np.std([ np.mean(c) for c in chunks(delays, n)])), file=f)
2426

2527
else :
2628
print("No %s data!" % name)

cuckoo_time_translator_python/python/cuckoo_time_translator/device_time_bags.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
from __future__ import print_function
2-
31
import os
4-
import sys
52

63
import pickle
74
import rosbag
@@ -12,6 +9,7 @@
129

1310
DefaultTopic = '/device_time'
1411

12+
1513
def guessTopics(bagFile):
1614
with rosbag.Bag(bagFile) as bag:
1715
found = []
@@ -21,8 +19,10 @@ def guessTopics(bagFile):
2119

2220
return found
2321

22+
2423
class DeviceTimeStream():
25-
def __init__(self, bagFile, topic, invalidate = False):
24+
25+
def __init__(self, bagFile, topic, invalidate=False):
2626
eventsFile = os.path.realpath(bagFile) + topic.replace("/", "_") + ".p"
2727
if os.path.exists(eventsFile):
2828
if invalidate:
@@ -31,7 +31,7 @@ def __init__(self, bagFile, topic, invalidate = False):
3131
verbose("Loading from " + eventsFile)
3232
self.__dict__ = pickle.load(open(eventsFile, "rb"))
3333
return
34-
34+
3535
bag = rosbag.Bag(bagFile)
3636

3737
self.filtered_hw_times = TimestampSeries()

cuckoo_time_translator_python/python/cuckoo_time_translator/plotting.py

100755100644
Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
from __future__ import print_function
44

5-
import sys
65
import os
76
import numpy as np
87
import matplotlib
@@ -11,10 +10,12 @@
1110

1211
from tools import *
1312

14-
def show(block = True):
13+
14+
def show(block=True):
1515
plt.show(block)
1616

17-
def save(fig, legend, fileName, fileFormat = 'pdf', overwrite = False):
17+
18+
def save(fig, legend, fileName, fileFormat='pdf', overwrite=False):
1819
fullFileName = fileName + '.' + fileFormat if not fileName.endswith(fileFormat) else fileName
1920
if not overwrite and os.path.exists(fullFileName):
2021
warn("Output file %s exists already! Not overwriting!" % fullFileName)
@@ -24,19 +25,19 @@ def save(fig, legend, fileName, fileFormat = 'pdf', overwrite = False):
2425
extra = ()
2526
if legend:
2627
extra = (legend,)
27-
28+
2829
fig.savefig(fullFileName, bbox_inches='tight', format=fileFormat)
2930

3031

31-
def plotMultiDelays(x, delays, xLabel, labels = None, title = None, markersize = 1.5, fileName = None, overwrite = None, colors = None, block = False, show = False):
32+
def plotMultiDelays(x, delays, xLabel, labels=None, title=None, markersize=1.5, fileName=None, overwrite=None, colors=None, block=False, show=False):
3233
if not colors:
3334
defaultColors = ['r', 'g', 'b']
3435
colors = list(reversed(defaultColors[:len(delays)]))
35-
36+
3637
yLabel = "offset [msec]"
37-
38+
3839
import matplotlib.gridspec as gridspec
39-
40+
4041
figsize = (5, 2.5)
4142

4243
breakX = False
@@ -47,28 +48,27 @@ def plotMyDelays(ax):
4748
if labels:
4849
for i, (d, l) in enumerate(zip(delays, labels)):
4950
assert(len(xA) == len(d))
50-
ax.plot(xA, np.asarray(d) * 1000, linestyle='-', marker='.', markersize= markersize, label = l, color = colors[i])
51+
ax.plot(xA, np.asarray(d) * 1000, linestyle='-', marker='.', markersize=markersize, label=l, color=colors[i])
5152
else:
5253
for i, d in enumerate(delays):
5354
assert(len(xA) == len(d))
54-
ax.plot(xA, np.asarray(d) * 1000, linestyle='-', marker='.', markersize= markersize, color = colors[i])
55+
ax.plot(xA, np.asarray(d) * 1000, linestyle='-', marker='.', markersize=markersize, color=colors[i])
5556

56-
fig, ax = plt.subplots(1, 1, figsize= figsize)
57+
fig, ax = plt.subplots(1, 1, figsize=figsize)
5758
plotMyDelays(ax)
5859
ax.set_xlabel(xLabel)
5960
ax.set_ylabel(yLabel)
6061

6162
if title:
6263
ax.set_title(title)
63-
64+
6465
legend = None
6566
if labels:
6667
legend = ax.legend(loc='upper right', shadow=False)
6768

68-
6969
if fileName:
70-
save(fig, legend, fileName, overwrite = overwrite)
71-
70+
save(fig, legend, fileName, overwrite=overwrite)
71+
7272
if show:
7373
show(block)
7474
return fig

cuckoo_time_translator_python/python/cuckoo_time_translator/timestamp_filters.py

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,28 @@
1-
from __future__ import print_function
2-
31
import numpy as np
4-
import math
5-
import sys
2+
import cuckoo_time_translator.algorithms as algorithms
3+
4+
from cuckoo_time_translator.algorithms import LocalTime, RemoteTime
65

7-
import cuckoo_time_translator as ctt
8-
from cuckoo_time_translator import LocalTime, RemoteTime
96

107
class TimestampFilter:
11-
def __init__(self, owt, batch = False, switchTime = None):
8+
9+
def __init__(self, owt, batch=False, switchTime=None):
1210
if switchTime:
13-
self.owt = ctt.SwitchingOwt(switchTime, owt)
11+
self.owt = algorithms.SwitchingOwt(switchTime, owt)
1412
else:
1513
self.owt = owt
1614
self.batch = batch
1715
self.switchTime = switchTime
18-
16+
1917
self._paramNames = { "batch" : False, "switchTime" : None }
20-
18+
2119
self.name = self.__class__.__name__
2220

2321
def _addParamNames(self, extra_names):
2422
return self._paramNames.update(extra_names)
2523

26-
def getConfigString(self, showDefaults = False):
27-
return "%s(%s)" % (self.name, ", ".join([ "%s=%s"% (name, getattr(self, name)) for name, default in self._paramNames.items() if showDefaults or default != getattr(self, name)]))
24+
def getConfigString(self, showDefaults=False):
25+
return "%s(%s)" % (self.name, ", ".join([ "%s=%s" % (name, getattr(self, name)) for name, default in self._paramNames.items() if showDefaults or default != getattr(self, name)]))
2826

2927
def __str__(self):
3028
return self.getConfigString(False)
@@ -48,17 +46,21 @@ def apply(self, hwTimes, receiveTimes):
4846
return correctedhwTimes
4947

5048
def getConfigAndStateString(self):
51-
return self.owt.getNameAndConfigString() + ": "+ self.owt.getStateString()
49+
return self.owt.getNameAndConfigString() + ": " + self.owt.getStateString()
50+
5251

5352
class ConvexHullFilter (TimestampFilter):
53+
5454
def __init__(self, *args, **kwargs):
55-
TimestampFilter.__init__(self, ctt.ConvexHullOwt(), *args, **kwargs)
55+
TimestampFilter.__init__(self, algorithms.ConvexHullOwt(), *args, **kwargs)
56+
5657

5758
class KalmanFilter(TimestampFilter):
58-
def __init__(self, outlierThreshold = None, sigmaSkew = None, *args, **kwargs):
59-
k = ctt.KalmanOwt()
59+
60+
def __init__(self, outlierThreshold=None, sigmaSkew=None, *args, **kwargs):
61+
k = algorithms.KalmanOwt()
6062
c = k.getConfig()
61-
63+
6264
extra_params = { "outlierThreshold" : c.outlierThreshold, "sigmaSkew" : c.sigmaSkew }
6365

6466
if outlierThreshold:
@@ -71,10 +73,12 @@ def __init__(self, outlierThreshold = None, sigmaSkew = None, *args, **kwargs):
7173

7274
k.setConfig(c)
7375
TimestampFilter.__init__(self, k, *args, **kwargs)
74-
76+
7577
self._addParamNames(extra_params)
7678

79+
7780
class LeastSquaresFilter(TimestampFilter):
81+
7882
def __init__(self):
7983
TimestampFilter.__init__(self, None, batch=True)
8084

@@ -84,11 +88,11 @@ def apply(self, hwTimes, receiveTimes):
8488

8589
from scipy import stats
8690
self.skew, self.offset, r_value, p_value, std_err = stats.linregress(hwTimes, receiveTimes)
87-
91+
8892
correctedhwTimes = [ self.offset + ht * self.skew for ht in hwTimes ]
8993
return correctedhwTimes
9094

91-
def getConfigString(self, showDefaults = False):
95+
def getConfigString(self, showDefaults=False):
9296
return "LeastSquaresFilter()"
9397

9498
def getConfigAndStateString(self):

cuckoo_time_translator_python/python/cuckoo_time_translator/timestamp_series.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,8 @@
1-
from __future__ import print_function
2-
3-
import os
4-
import sys
5-
6-
import pickle
7-
import rosbag
8-
91
class TimestampSeries(list):
2+
103
def __init__(self):
114
pass
12-
5+
136
def append(self, t):
147
assert float == type(t), "type(t)=" + str(type(t))
158
list.append(self, t)
Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,35 @@
1+
from __future__ import print_function
2+
13
import exceptions
24
try:
35
from termcolor import colored
46
except exceptions.ImportError:
57
print("Unable to import termcolor.")
68
print("Try:")
79
print("sudo pip install termcolor")
8-
def colored(X,Y):
10+
11+
def colored(X, Y):
912
return X
1013

1114
verbosity = False
1215

16+
1317
def info(text):
1418
print(colored(text, 'yellow'))
1519

20+
1621
def verbose(text):
1722
if verbosity:
1823
print(colored(text, 'yellow'))
1924

25+
2026
def warn(text):
2127
print(colored(str(text), 'red'))
2228

2329

2430
def error(text):
2531
print(colored("Error :" + str(text), 'red'))
2632

33+
2734
def ok(text):
2835
print(colored(str(text), 'green'))
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
2+
# # ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
33

44
from distutils.core import setup
55
from catkin_pkg.python_setup import generate_distutils_setup
@@ -9,6 +9,6 @@
99
packages=['cuckoo_time_translator'],
1010
package_dir={'':'python'},
1111
scripts=['scripts/ctt_introspect.py']
12-
)
12+
)
1313

1414
setup(**setup_args)

cuckoo_time_translator_python/test/Test.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
#!/usr/bin/env python
22
import os
3-
from cuckoo_time_translator import *
3+
from cuckoo_time_translator.algorithms import *
44

55
import unittest
66

77
from nose import SkipTest
88

9+
910
class TestTimes(unittest.TestCase):
11+
1012
def testConversions(self):
1113
l = LocalTime(3)
1214
self.assertEqual(3, float(l))
1315

14-
1516
def _testFilter(self, c):
1617
self.assertFalse(c.isReady())
1718
l = c.updateAndTranslateToLocalTimestamp(RemoteTime(5), LocalTime(4))
@@ -29,5 +30,6 @@ def testConvexHull(self):
2930
def testKalman(self):
3031
self._testFilter(KalmanOwt())
3132

33+
3234
if __name__ == '__main__':
3335
unittest.main()

0 commit comments

Comments
 (0)