-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactive.py
75 lines (64 loc) · 2.66 KB
/
interactive.py
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
'''
Interactive display of (time, odometer, fuel, cost), e.g.:
$ python interactive.py data/bb_c-max_day_1_part_1.csv
t=0.0 odo=0.0 fuel=0.0 cost=0.0
t=5.00454115868 odo=0.0254855315666 fuel=0.0 cost=0.100107167993
t=10.0005161762 odo=0.0254855315666 fuel=0.0 cost=0.100107167993
t=14.9398450851 odo=0.0254855315666 fuel=0.0 cost=0.100107167993
t=20.0050661564 odo=0.0254855315666 fuel=0.0 cost=0.100107167993
t=24.996628046 odo=0.0254855315666 fuel=0.0 cost=0.100107167993
t=29.995401144 odo=0.0254855315666 fuel=0.0 cost=0.100107167993
t=35.0053191185 odo=0.0266996905002 fuel=0.0 cost=0.104876384285
t=40.0049920082 odo=0.0388356875 fuel=0.001783161 cost=0.159550836908
...
'''
import itertools
from rate import LITERS_TO_GALLONS, KM_TO_MILES, MAINT_COST_PER_MILE, CURRENT_FUEL_COST
TS, FIELD, VAL = range(3)
def generate_odo_fuel_pairs(stream, resolution=5):
start = int(float(stream[0][0]))
bucket = start - (start % resolution)
current_odo = -1
current_fuel = -1
last_fuel = -1
for row in stream:
ts = float(row[TS])
if row[FIELD] not in ["odometer", "fuel_consumed_since_restart"]:
continue
if current_odo == -1 and row[FIELD] == "odometer":
current_odo = row[VAL]
if current_fuel == -1 and row[FIELD] == "fuel_consumed_since_restart":
current_fuel = row[VAL]
if (ts - (ts % resolution)) > bucket:
if current_odo > 0:
#workaround for when fuel does not start at 0 on some runs
current_fuel = max(current_fuel, last_fuel)
yield (ts, (float(current_odo), float(current_fuel)))
bucket = (ts - (ts % resolution))
current_odo = -1
last_fuel = current_fuel
current_fuel = -1
def generate_taxi_stream(filename):
'''
Generate stream of (time, odo, fuel, cost) from the given CSV file.
'''
xs = [x.strip().replace(" ", "").split(',') for x in open(filename).readlines()]
pairs = generate_odo_fuel_pairs(xs)
(t0, (odo0, fuel0)) = init = next(pairs)
for (t, (odo, fuel)) in itertools.chain([init], pairs):
t_now = (t - t0)
odo_now = (odo - odo0) * KM_TO_MILES
fuel_now = (fuel - fuel0) * LITERS_TO_GALLONS
yield dict(
t=t_now,
odo=odo_now,
fuel=fuel_now,
cost=(odo_now * CURRENT_FUEL_COST) + (fuel_now * CURRENT_FUEL_COST),
)
if __name__ == "__main__":
import sys, time
sys.argv.pop(0)
f = sys.argv.pop(0)
for row in generate_taxi_stream(f):
print "t=%(t).2f\todo=%(odo).2f\tfuel=%(fuel).2f\tcost=%(cost).2f" % row
time.sleep(0.2)