-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils_map.py
148 lines (135 loc) · 4.79 KB
/
utils_map.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
import plotly.graph_objects as go
import numpy as np
import os
### Dumb issue... we need the mapbox url which is saved as an environment variable
# On production server (heroku) this is no problem, just call os.environ['MAPBOX_URL']
# On development, my conda env does not export the environment variable correctly.
# This is because of the equals sign. So, the mapbox url is split in two and the
# equals sign is manually added (see else block below)
# I tried the following:
# - Escape with \
# - Escape with ^
# - Use single quotation marks instead of double
# - Setting up (de)activate.d w/ env_vars.sh in conda env (see https://docs.conda.io/projects/conda/en/stable/user-guide/tasks/manage-environments.html#macos-and-linux)
# Nothing worked and I don't want to waste any more time on this issue
is_production = os.environ['IS_PRODUCTION']
if is_production == 'True':
mapbox_url = os.environ['MAPBOX_URL']
else:
mapbox_url = os.environ['MAPBOX_URL1'] + '=' + os.environ['MAPBOX_URL2']
def format_number(x):
"""
Format numbers for map display purposes (highlight, hover info).
Examples:
123456 -> 123K
1234567 -> 1.23M
12.34 -> 12.3
0.123456 -> 0.12 (preference of no more than 2 decimal places)
"""
units = {
0: '',
3: 'K',
6: 'M',
9: 'B' # currently nothing at this order of magnitude
}
orders = np.array(list(units.keys()))
### Special cases
if np.isnan(x):
# mostly for NA populations
return 'Not available'
elif x == 0:
# x = 0 -> log error in a few lines
return '0'
elif x < 1:
# 0.123456 -> 0.12
return f'{x:.2f}'
log = np.log10(x)
log_floor = int(np.floor(log))
highest_order = orders[orders <= log_floor].max()
rounding = highest_order - log_floor + 2
sigfigs = f'{(x / 10**highest_order):.3g}'
# if highest_order == 0 or np.log10(sigfigs) >= 2:
# # 1.0 -> 1 (highest_order )
# # 12.0 -> 12
# # 123.0 -> 123
# sigfigs = int(sigfigs)
unit = units[highest_order]
out = '{}{}'.format(sigfigs, unit)
return out
def get_map_data(data, comm):
return (
data.loc[:, [
'community_id',
'est_fishers',
'est_buyers',
'weight_mt',
'total_price_usd'
]].groupby('community_id')
.sum()
.reset_index()
.join(comm[['community_id', 'community_name', 'community_lat', 'community_lon', 'population']].set_index('community_id'), on = 'community_id')
.reset_index(drop = True)
)
def make_map(map_data, mapbox_url):
map_data[['population', 'est_fishers', 'est_buyers', 'weight_mt', 'total_price_usd']] = map_data[['population', 'est_fishers', 'est_buyers', 'weight_mt', 'total_price_usd']].applymap(format_number)
hovertext_list = [
"Community: {}<br>\
Population: {}<br>\
Estimated fishers: {}<br>\
Estimated buyers: {}<br>\
Total catch weight (mt): {}<br>\
Total catch value (USD): {}<br>\
".format(comm_name, pop, n_fisher, n_buyer, catch_weight, catch_value) \
for comm_name, pop, n_fisher, n_buyer, catch_weight, catch_value \
in map_data[['community_name', 'population', 'est_fishers', 'est_buyers', 'weight_mt', 'total_price_usd']].apply(tuple, axis = 1)
]
########## # TODO
# Tweak the parameters here... like the 1, 5, and 15
# Where did this equation come from? I made it up. It works OK as it is rn tbh, but could be better
zoom_level = max(1, round(5 - map_data['community_lat'].std() * map_data['community_lon'].std() / 15))
fig = go.Figure()
fig.add_trace(go.Scattermapbox(
lat = map_data['community_lat'], lon = map_data['community_lon'],
mode = 'markers',
marker = go.scattermapbox.Marker(
size = 15,
color = '#6fbcc3'
),
hoverinfo = 'none'
))
fig.add_trace(go.Scattermapbox(
lat = map_data['community_lat'], lon = map_data['community_lon'],
mode = 'markers',
marker = go.scattermapbox.Marker(
size = 10,
color = '#99f2e8'
),
hoverinfo = 'text',
hovertext = hovertext_list,
))
fig.update_layout(
mapbox_style = 'white-bg',
mapbox_layers = [
{
'below': 'traces',
'sourcetype': 'raster',
'sourceattribution': 'OpenStreetMap',
'source': [mapbox_url]
}
],
mapbox = {
'center': {
'lat': map_data['community_lat'].mean(),
'lon': map_data['community_lon'].mean()
},
'zoom': zoom_level
},
showlegend = False,
margin = {
't': 0,
'r': 0,
'b': 0,
'l': 0
}
)
return fig