Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

deploy.py 4.6 KB

You have to be logged in to leave a comment. Sign In
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
  1. import json
  2. import requests
  3. import numpy as np
  4. from datetime import datetime
  5. from collections import defaultdict
  6. import torch
  7. from epa_seq2seq_model import EpaSeq2Seq
  8. def construct_url(endpoint, bounds, dataset, start_time, end_time):
  9. lat_lo, lat_hi = bounds['latitude']
  10. lon_lo, lon_hi = bounds['longitude']
  11. stime = start_time.strftime('%Y-%m-%dT%H:%M:%SZ')
  12. etime = end_time.strftime('%Y-%m-%dT%H:%M:%SZ')
  13. bstr = f'{lon_lo},{lat_lo},{lon_hi},{lat_hi}'
  14. args = f'ds={dataset}&b={bstr}&startTime={stime}&endTime={etime}'
  15. return f'{endpoint}?{args}&lowPassFilter=False'
  16. def grid_data(data):
  17. latitudes = set([])
  18. longitudes = set([])
  19. times = set([])
  20. datadict = defaultdict(lambda: np.nan)
  21. for item in data:
  22. lat = item['latitude']
  23. lon = item['longitude']
  24. time = item['time']
  25. value = item['data'][0]['variable']
  26. latitudes.add(lat)
  27. longitudes.add(lon)
  28. times.add(time)
  29. datadict[lat, lon, time] = value
  30. latitudes = sorted(latitudes)
  31. longitudes = sorted(longitudes)
  32. times = sorted(times)
  33. D = np.array([
  34. [
  35. [
  36. datadict[lat, lon, time]
  37. for lon in longitudes
  38. ]
  39. for lat in latitudes
  40. ]
  41. for time in times
  42. ], dtype=np.float32)
  43. return D, (times, latitudes, longitudes)
  44. def fetch_data(config):
  45. data = {}
  46. start = datetime(2020, 9, 15)
  47. end = datetime(2020, 9, 16)
  48. for dname, dinfo in config['datasets'].items():
  49. url = construct_url(
  50. config['endpoint'], config['bounds'],
  51. dinfo['dataset'], start, end
  52. )
  53. print(f'Fetching "{url}"...')
  54. response = requests.get(url)
  55. raw = response.json()
  56. print(f'...done.')
  57. gridded, axes = grid_data(raw)
  58. if 'factor' in dinfo:
  59. gridded *= dinfo['factor']
  60. data[dname] = (gridded, axes)
  61. return data
  62. def format_input(config, in_channels, window_size):
  63. datasets = fetch_data(config)
  64. relevant = {
  65. k: v for k, v in datasets.items() if k in in_channels
  66. }
  67. common_times = set.intersection(*[
  68. set(ax[0]) for _, ax in datasets.values()
  69. ])
  70. assert len(common_times) >= window_size
  71. latitudes = None
  72. longitudes = None
  73. times = sorted(common_times)
  74. raw = {}
  75. for k, (data, axes) in relevant.items():
  76. time, lat, lon = axes
  77. if latitudes is None:
  78. latitudes = lat
  79. longitudes = lon
  80. else:
  81. assert np.allclose(lat, latitudes)
  82. assert np.allclose(lon, longitudes)
  83. # Sub-select common times
  84. idx = np.array([ti in common_times for ti in time])
  85. raw[k] = data[idx, ...]
  86. X = np.stack([
  87. raw[c][-window_size:]
  88. for c in in_channels
  89. ], dtype=np.float32)
  90. frame_size = X.shape[-2:]
  91. return X, frame_size, (times[-window_size:], latitudes, longitudes)
  92. def load_config(configpath):
  93. with open(configpath, 'r') as f:
  94. return json.load(f)
  95. def predict(event, context):
  96. body = event['body']
  97. config_path = body['configuration_path']
  98. deploy_config = load_config(config_path)
  99. model_path = deploy_config['model_path']
  100. # Load model
  101. device = torch.device('cpu')
  102. checkpoint = torch.load(model_path, map_location=device)
  103. config = checkpoint['config']
  104. window_size = config['sequence_length']
  105. in_channels = config['in_channels']
  106. out_channels = config['out_channels']
  107. model_params = config['model_params']
  108. model_params['device'] = device
  109. X, frame_size, axes = format_input(deploy_config, in_channels, window_size)
  110. X = torch.tensor(X[np.newaxis, ...])
  111. model = EpaSeq2Seq(
  112. in_channels=len(in_channels),
  113. out_channels=len(out_channels),
  114. frame_size=frame_size,
  115. **model_params
  116. )
  117. model.load_state_dict(checkpoint['model_state_dict'])
  118. model.to(device)
  119. model.eval()
  120. ypred = model(X).detach().numpy()[0, -1, ...]
  121. out_data = {
  122. 'lat': axes[1],
  123. 'lon': axes[2],
  124. 'variables': {
  125. k: y.tolist()
  126. for k, y in zip(out_channels, ypred)
  127. }
  128. }
  129. result = {
  130. 'data': out_data,
  131. }
  132. return {
  133. 'statusCode': 200,
  134. 'body': result,
  135. }
  136. if __name__ == '__main__':
  137. event = {
  138. 'body': {
  139. 'configuration_path': 'config/deploy_config.json',
  140. }
  141. }
  142. response = predict(event, None)
  143. pred = response['body']['data']['variables']['PM25']
  144. import matplotlib.pyplot as plt
  145. Y = np.array(pred)
  146. plt.imshow(np.flipud(Y))
  147. plt.show()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...