-
Notifications
You must be signed in to change notification settings - Fork 0
/
logmap2.py
177 lines (143 loc) · 6.03 KB
/
logmap2.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
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
import json
import csv
import numpy as np
import pickle
import sqlite3
import multiprocessing
from Queue import Empty
from functools import partial
r = 3440 # radius of Earth in nautical miles
nlon = 2**13
nlat = 2**12
predef_ids = [ 'NC18', 'Rat', 'APPLE', 'LAKIE', 'ERORE', 'KSCR' ]
predef_lats = [ 36.3894444, 36.3894444, 40.556136, 40.829133, 40.954819, 35.7042745 ]
predef_lons = [ -76.9113889, -76.9113889, -74.062253, -73.976792, -73.899233, -79.5042976 ]
verbose = False
def ll2xyz(lon, lat):
return np.array( [np.cos(lat*np.pi/180) * np.cos(lon*np.pi/180),
np.cos(lat*np.pi/180) * np.sin(lon*np.pi/180),
np.sin(lat*np.pi/180) ])
def dist(a,b):
return r * np.abs(np.arccos(np.inner(a,b)))
def linedist(a,b,c):
q = np.cross(a,b)
n = q/np.sqrt(q.dot(q))
return r * np.abs(np.arccos(np.inner(n,c))-np.pi/2)
def maps_legs_from_flights(process_num, log, airports, xyzs, bigmapq, alllegsq):
bigmap = np.zeros((nlat,nlon))
def llcoords(id):
try:
lat = airports[id]['lat']
lon = airports[id]['lon']
except KeyError:
print " * Can't find airport with ICAO ID '" + id + "'"
raise
return (0,0)
return (lat, lon)
def ucoords(id):
try:
lat = airports[id]['lat']
lon = airports[id]['lon']
except KeyError:
print " * Can't find airport with ICAO ID '" + id + "'"
raise
return (0,0,0)
return ll2xyz(lon, lat)
def linemask(a,b,r=10):
d = dist(a,b)
return ( ( (linedist(a,b,xyzs)<r) &
(dist(a,xyzs)<d) &
(dist(b,xyzs)<d) )
| (dist(a,xyzs)<r )
| (dist(b,xyzs)<r ) )
def pointmask(a,r=15):
return dist(a,xyzs)<r
counter = 0
for flight in log:
littlemap = np.full((nlat,nlon),False,dtype='bool')
for leg in flight['legs']:
try:
if leg[0] == leg[1]:
littlemap |= pointmask(ucoords(leg[0]))
alllegsq.put([llcoords(leg[0])])
alllegsq.cancel_join_thread()
else:
littlemap |= linemask(ucoords(leg[0]),ucoords(leg[1]))
alllegsq.put([llcoords(leg[0]), llcoords(leg[1])])
alllegsq.cancel_join_thread()
except KeyError:
print " - Problem with flight " + flight['route'] + "."
area = (littlemap * area_comp).sum()
if area > 0:
bigmap += flight['durat'] * littlemap / area
counter += 1
if counter % 5 == 0: print ' - Process ' + str(process_num) + ' finished ' + str(counter) + ' flights.'
bigmapq.put(bigmap)
print 'Process ' + str(process_num) + ' complete after ' + str(counter) + ' flights.'
if __name__ == '__main__':
airports = {}
for id, lat, lon in zip(predef_ids, predef_lats, predef_lons):
ap = { 'lat': lat, 'lon': lon }
airports[id] = ap
with open('airports.csv') as airportdb:
apreader = csv.reader(airportdb)
header = apreader.next()
idnt_i = header.index('ident')
iata_i = header.index('iata_code')
locl_i = header.index('local_code')
lat_i = header.index('latitude_deg')
lon_i = header.index('longitude_deg')
for row in apreader:
ap = { 'lat': float(row[lat_i]),
'lon': float(row[lon_i]) }
airports[row[idnt_i]] = ap
if row[iata_i] not in airports:
airports[row[iata_i]] = ap
if row[locl_i] not in airports:
airports[row[locl_i]] = ap
print "Done building airport db."
lons = np.linspace(-180,180,nlon)
lats = np.linspace(-90,90,nlat)
lonv, latv = np.meshgrid(lons, lats, indexing='xy')
xyzs = ll2xyz(lonv,latv).transpose(1,2,0)
area_comp = np.cos(latv*np.pi/180)
print "Done calculating map coordinates."
log = []
db = sqlite3.connect('/Users/mcmanigle/Dropbox/Apps/PilotPro/Logbook.pilotpro')
route_cfid = db.execute('SELECT customFieldId from customFields WHERE name="Route"').fetchone()[0]
flights = db.execute('SELECT l.departure, l.destination, c.value, l.duration ' +
'FROM logbookEntries AS l LEFT JOIN customValues AS c ' +
'ON l.logbookEntryId = c.logbookEntryId AND c.customFieldId = "' + route_cfid + '"')
for row in flights:
flight = { 'deprt': row[0],
'destn': row[1],
'route': row[2] if row[2] else row[0]+'-'+row[1],
'durat': float(row[3]) }
stops = flight['route'].split('-')
if( stops[0] != row[0] ): stops = [row[0]] + stops
if( stops[-1] != row[1] ): stops += [row[1]]
flight['legs'] = [[stops[n], stops[n+1]] for n in range(len(stops)-1)]
log.append(flight)
if verbose:
print flight['route']
print flight['legs']
db.close()
print "Done building list of flights. " + str(len(log)) + " total."
num_jobs = multiprocessing.cpu_count() - 3
bigmapq = multiprocessing.Queue()
alllegsq = multiprocessing.Queue()
print "Starting " + str(num_jobs) + " workers, for about " + str(len(log)/num_jobs) + " flights per worker..."
for i in range(num_jobs):
j = multiprocessing.Process( target=maps_legs_from_flights,
args=(i+1, log[i::num_jobs], airports, xyzs, bigmapq, alllegsq) )
j.start()
bigmap = np.zeros((nlat,nlon))
alllegs = []
for i in range(num_jobs):
bigmap += bigmapq.get()
while True:
try: alllegs.append(alllegsq.get_nowait())
except Empty: break
print "Done plotting all the flights."
pickle.dump((bigmap, lats, lons, alllegs), open('log.p', 'wb'))
print "Done saving the map."