This repository has been archived by the owner on Oct 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
utils.ts
693 lines (631 loc) · 17.6 KB
/
utils.ts
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
/*
Copyright 2019 City of Los Angeles.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// utility functions
import circleToPolygon from 'circle-to-polygon'
import pointInPoly from 'point-in-polygon'
import {
UUID,
Timestamp,
VehicleEvent,
Telemetry,
BoundingBox,
Geography,
Rule,
VEHICLE_EVENTS,
VEHICLE_STATUSES,
EVENT_STATUS_MAP,
VEHICLE_STATUS,
BBox
} from '@mds-core/mds-types'
import { TelemetryRecord } from '@mds-core/mds-db/types'
import log from '@mds-core/mds-logger'
import { MultiPolygon, Polygon, FeatureCollection, Geometry, Feature } from 'geojson'
const RADIUS = 30.48 // 100 feet, in meters
const NUMBER_OF_EDGES = 32 // Number of edges to add, geojson doesn't support real circles
function isUUID(s: unknown): s is UUID {
if (typeof s !== 'string') {
return false
}
return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(s)
}
function round(value: string | number, decimals: number) {
return Number(
`${Math.round(Number(`${typeof value !== 'number' ? parseFloat(value) : value}e${decimals}`))}e-${decimals}`
)
}
function isPct(val: unknown): val is number {
if (typeof val !== 'number') {
return false
}
return val >= 0 && val <= 1
}
// this is a real-time API, so timestamps should be now +/- some factor, let's start with 24h
function isTimestamp(val: unknown): val is Timestamp {
if (typeof val !== 'number') {
log.info('timestamp not an number')
return false
}
if (val < 1420099200000) {
log.info('timestamp is prior to 1/1/2015; this is almost certainly seconds, not milliseconds')
return false
}
return true
}
function seconds(n: number) {
if (typeof n !== 'number') {
throw new Error('timespan must be a number')
}
return n * 1000
}
function minutes(n: number) {
return seconds(n) * 60
}
function hours(n: number) {
return minutes(n) * 60
}
function days(n: number) {
return hours(n) * 24
}
/**
* @param {number} minimum
* @param {number} maximum
* @return {number} random value in minimum...maximum
*/
function rangeRandom(min: number, max: number) {
if (typeof min !== 'number' || typeof max !== 'number') {
throw new Error(`rangeRandom: min, max must be numbers, not ${min}, ${max}`)
}
return min + (max - min) * Math.random()
}
/**
* @param {number} minimum
* @param {number} maximum
* @return {number} random value in minimum...maximum
*/
function rangeRandomInt(min: number, max?: number) {
if (max === undefined) {
return Math.floor(rangeRandom(0, min))
}
return Math.floor(rangeRandom(min, max))
}
function randomElement<T>(list: T[]) {
return list[rangeRandomInt(list.length)]
}
function head<T>(list: T[]) {
if (!Array.isArray(list)) {
throw new Error('not a list')
}
return list[0]
}
function tail<T>(list: T[]) {
if (!Array.isArray(list)) {
throw new Error('not a list')
}
return list[list.length - 1]
}
/**
* @param {MultiPolygon}
* @return {bbox}
*/
function calcBBox(geometry: Geometry): BBox {
// log.debug('calcBBox', geometry.type)
let latMin = 10000
let latMax = -10000
let lngMin = 10000
let lngMax = -10000
function expand(poly: number[][]) {
if (!Array.isArray(poly)) {
throw new Error('poly is not a list')
}
if (typeof poly[0][0] !== 'number' || typeof poly[0][1] !== 'number') {
throw new Error('poly is not a list of [num,num]')
}
for (const pair of poly) {
const [lng, lat] = pair
if (latMin > lat) {
latMin = lat
}
if (latMax < lat) {
latMax = lat
}
if (lngMin > lng) {
lngMin = lng
}
if (lngMax < lng) {
lngMax = lng
}
}
}
let poly
switch (geometry.type) {
case 'Polygon':
;[poly] = geometry.coordinates
expand(poly)
break
case 'MultiPolygon':
{
const coords = geometry.coordinates
for (const polyWithHoles of coords) {
;[poly] = polyWithHoles
expand(poly)
}
}
break
default:
throw new Error(`calcBBox does not (yet) handle geometry of type ${geometry.type}`)
}
return {
latMin,
latMax,
lngMin,
lngMax
}
}
function pointInPolyWithHoles(pt: [number, number], polyWithHoles: number[][][]): boolean {
const poly = polyWithHoles[0]
// log('testing', pt, 'in', poly, 'in', polyWithHoles)
if (pointInPoly(pt, poly)) {
// log('pt in poly')
const holes = polyWithHoles.slice(1)
for (const hole of holes) {
if (pointInPoly(pt, hole)) {
// log('pt in hole')
return false
}
}
// log('pt in poly but not holes')
return true
}
// log('pt in none polys')
return false
}
/**
* @param {Point or [number, number]}
* @param {MultiPolygon}
* @return {true iff the point is somewhere in the list of polygons and not in the list of holes}
*/
function pointInMultiPolygon(pt: [number, number], multipoly: MultiPolygon): boolean {
return multipoly.coordinates.some((polyWithHoles: number[][][]) => pointInPolyWithHoles(pt, polyWithHoles))
}
/**
* @param {Point or [number, number]}
* @param {Polygon}
* @return {true iff the point is somewhere in the list of polygons and not in the list of holes}
*/
function pointInPolygon(pt: [number, number], poly: Polygon): boolean {
return pointInPolyWithHoles(pt, poly.coordinates)
}
function pointInGeometry(pt: [number, number], shape: Geometry): boolean {
if (shape.type === 'MultiPolygon') {
return pointInMultiPolygon(pt, shape)
}
if (shape.type === 'Polygon') {
return pointInPolygon(pt, shape)
}
if (shape.type === 'Point') {
if (pointInPolygon(pt, circleToPolygon(shape.coordinates, RADIUS, NUMBER_OF_EDGES))) {
return true
}
return false
}
throw new Error(`cannot check point in shape for type ${shape.type}`)
}
function pointInFeatureCollection(pt: [number, number], fc: FeatureCollection): boolean {
return fc.features.some((feature: Feature) => pointInGeometry(pt, feature.geometry))
}
function pointInShape(
pt: [number, number] | { lat: number; lng: number },
shape: Geometry | FeatureCollection
): boolean {
const point: [number, number] = Array.isArray(pt) ? pt : [pt.lng, pt.lat]
console.log('pointinshape')
console.log(point)
console.log(shape)
console.log('')
if (shape.type === 'Point') {
if (pointInPolygon(point, circleToPolygon(shape.coordinates, RADIUS, NUMBER_OF_EDGES))) {
return true
}
return false
}
if (shape.type === 'MultiPolygon') {
return pointInMultiPolygon(point, shape)
}
if (shape.type === 'Polygon') {
return pointInPolygon(point, shape)
}
if (shape.type === 'FeatureCollection') {
return pointInFeatureCollection(point, shape)
}
return pointInGeometry(point, shape)
}
/**
* @param {MultiPolygon}
* @return {Point} random point within the MultiPolygon
*/
function makePointInShape(shape: Geometry): { lat: number; lng: number } {
if (!shape) {
throw new Error('no shape')
}
const shapeToCreate = shape.type === 'Point' ? circleToPolygon(shape.coordinates, RADIUS, NUMBER_OF_EDGES) : shape
const bbox = calcBBox(shapeToCreate)
let tries = 0
while (tries < 1000) {
const pt: [number, number] = [rangeRandom(bbox.lngMin, bbox.lngMax), rangeRandom(bbox.latMin, bbox.latMax)]
console.log('make point in shape: ***')
console.log('is pointInShape?', pointInShape(pt, shape))
console.log(pt, shape)
console.log('*******')
if (pointInShape(pt, shape)) {
return {
lng: pt[0],
lat: pt[1]
}
}
tries += 1
}
throw new Error('tried 1000 times to put a point in poly and failed')
}
/**
* [rad description]
* @param {[type]} _deg [description]
* @return {[type]} [description]
*/
function rad(_deg: number): number {
return (_deg * Math.PI) / 180
}
/**
* [deg description]
* @param {[type]} _rad [description]
* @return {[type]} [description]
*/
function deg(_rad: number): number {
return (_rad * 180) / Math.PI
}
/**
* @param {Point}
* @param {distance in meters}
* @param {bearing in degrees}
*/
function addDistanceBearing<T extends { lat: number; lng: number }>(pt: T, distance: number, bearing: number) {
// log('addDistanceBearing', pt, distance, bearing)
if (Number.isNaN(distance)) {
throw new Error('bad distance')
}
if (Number.isNaN(bearing)) {
throw new Error('bad bearing')
}
const R = 6378100 // Radius of the Earth, in meters
const B = rad(bearing)
const lat1 = rad(pt.lat)
const lng1 = rad(pt.lng)
const xx = Math.sin(lat1) * Math.cos(distance / R) + Math.cos(lat1) * Math.sin(distance / R) * Math.cos(B)
const lat2 = Math.asin(xx)
const num = Math.sin(B) * Math.sin(distance / R) * Math.cos(lat1)
const den = Math.cos(distance / R) - Math.sin(lat1) * Math.sin(lat2)
const lng2 = lng1 + Math.atan2(num, den)
return Object.assign({}, pt, {
lat: deg(lat2),
lng: deg(lng2)
})
}
/**
* [getRandomSubarray description]
* @param {[type]} array [description]
* @param {[type]} size [description]
* @return {[type]} [description]
*/
function getRandomSubarray<T>(array: T[], size: number): T[] {
const shuffled = array.slice()
const min = array.length - size
for (let i = array.length; i > min; i -= 1) {
const index = Math.floor((i + 1) * Math.random())
const temp = shuffled[index]
shuffled[index] = shuffled[i]
shuffled[i] = temp
}
return shuffled.slice(min)
}
/**
* @param {string describing a bounding box}
* @return {bounding box}
*/
function parseBBox(bbox_str: string): { lngMin: number; lngMax: number; latMin: number; latMax: number } | null {
// [sw point, ne point]
// e.g. '[[-73.9876, 40.7661],[-73.9876, 40.7661]]'
if (!bbox_str || typeof bbox_str !== 'string') {
return null
}
const parts = bbox_str
.replace(/[[\] ]+/g, '')
.split(',')
.map(parseFloat)
if (parts.length !== 4) {
return null
}
const [lng1, lat1, lng2, lat2] = parts
return {
lngMin: Math.min(lng1, lng2),
lngMax: Math.max(lng1, lng2),
latMin: Math.min(lat1, lat2),
latMax: Math.max(lat1, lat2)
}
}
function capitalizeFirst(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1)
}
function nullKeys<T>(obj: { [key: string]: T }): string[] {
return Object.keys(obj).filter(key => obj[key] === null || obj[key] === undefined)
}
function stripNulls<T extends {}>(obj: { [x: string]: unknown }): Partial<T> {
return nullKeys(obj).reduce((stripped, key) => {
const { [key]: nullkey, ...rest } = stripped
return rest
}, obj) as Partial<T>
}
function isFloat(n: unknown): boolean {
return typeof n === 'number' || (typeof n === 'string' && !Number.isNaN(parseFloat(n)))
}
function now(): Timestamp {
return Date.now()
}
// dumb subset of lodash range()
function range(n: number) {
return [...Array(n).keys()]
}
function nonNegInt(val: string, def: number): number {
if (def === undefined) {
throw new Error('nonNegInt: no default value')
}
if (val === undefined) {
return def
}
const parsed = parseInt(val)
if (Number.isInteger(parsed) && parsed >= 0) {
return parsed
}
throw new Error(`invalid nonNegInt "${val}"`)
}
function yesterday(): Timestamp {
return Date.now() - days(1)
}
// shortcut for making a string form of comma-separated values
function csv<T>(list: T[] | Readonly<T[]>): string {
return list.join(', ')
}
// utility for adding counts to maps
function inc(map: { [key: string]: number }, key: string) {
return Object.assign(map, { [key]: map[key] ? map[key] + 1 : 1 })
}
function convertTelemetryToTelemetryRecord(telemetry: Telemetry): TelemetryRecord {
const {
device_id,
provider_id,
timestamp,
gps: { lat, lng, altitude, heading, speed, accuracy },
charge,
recorded = now()
} = telemetry
return {
device_id,
provider_id,
timestamp,
lat,
lng,
altitude,
heading,
speed,
accuracy,
charge,
recorded
}
}
function convertTelemetryRecordToTelemetry(telemetryRecord: TelemetryRecord): Telemetry {
const {
device_id,
provider_id,
timestamp,
lat,
lng,
altitude,
heading,
speed,
accuracy,
charge,
recorded
} = telemetryRecord
return {
device_id,
provider_id,
timestamp,
gps: { lat, lng, altitude, heading, speed, accuracy },
charge,
recorded
}
}
function pathsFor(path: string): string[] {
const { PATH_PREFIX } = process.env
return [path, PATH_PREFIX + path, `${PATH_PREFIX}/dev${path}`]
}
function isInsideBoundingBox(telemetry: Telemetry | undefined | null, bbox: BoundingBox): boolean {
if (telemetry && telemetry.gps) {
const { lat, lng } = telemetry.gps
if (!lat || !lng) {
return false
}
const [[lng1, lat1], [lng2, lat2]] = bbox
const latMin = Math.min(lat1, lat2)
const latMax = Math.max(lat1, lat2)
const lngMin = Math.min(lng1, lng2)
const lngMax = Math.max(lng1, lng2)
return latMin <= lat && lat <= latMax && lngMin <= lng && lng <= lngMax
}
return false
}
function isStateTransitionValid(eventA: VehicleEvent, eventB: VehicleEvent) {
switch (EVENT_STATUS_MAP[eventA.event_type]) {
case VEHICLE_STATUSES.available:
switch (eventB.event_type) {
case VEHICLE_EVENTS.deregister:
return true
case VEHICLE_EVENTS.agency_pick_up:
return true
case VEHICLE_EVENTS.service_end:
return true
case VEHICLE_EVENTS.trip_start:
return true
default:
return false
}
case VEHICLE_STATUSES.elsewhere:
switch (eventB.event_type) {
case VEHICLE_EVENTS.trip_enter:
return true
case VEHICLE_EVENTS.provider_pick_up:
return true
case VEHICLE_EVENTS.deregister:
return true
case VEHICLE_EVENTS.provider_drop_off:
return true
default:
return false
}
case VEHICLE_STATUSES.inactive:
switch (eventB.event_type) {
default:
return false
}
case VEHICLE_STATUSES.removed:
switch (eventB.event_type) {
case VEHICLE_EVENTS.register:
return true
case VEHICLE_EVENTS.trip_enter:
return true
case VEHICLE_EVENTS.provider_drop_off:
return true
case VEHICLE_EVENTS.deregister:
return true
default:
return false
}
case VEHICLE_STATUSES.reserved:
switch (eventB.event_type) {
case VEHICLE_EVENTS.trip_start:
return true
case VEHICLE_EVENTS.cancel_reservation:
return true
default:
return false
}
case VEHICLE_STATUSES.trip:
switch (eventB.event_type) {
case VEHICLE_EVENTS.trip_leave:
return true
case VEHICLE_EVENTS.trip_end:
return true
default:
return false
}
case VEHICLE_STATUSES.unavailable:
switch (eventB.event_type) {
case VEHICLE_EVENTS.service_start:
return true
case VEHICLE_EVENTS.deregister:
return true
case VEHICLE_EVENTS.agency_pick_up:
return true
case VEHICLE_EVENTS.provider_pick_up:
return true
default:
return false
}
default:
return false
}
}
function getPolygon(geographies: Geography[], geography: string): Geometry | FeatureCollection {
const res = geographies.find((location: Geography) => {
return location.geography_id === geography
})
if (res === undefined) {
throw new Error(`Geography ${geography} not found in ${geographies}!`)
}
if (res.geography_json.type !== 'FeatureCollection') {
return res.geography_json.geometry
}
return res.geography_json
}
function isInStatesOrEvents(rule: Rule, event: VehicleEvent): boolean {
const status = rule.statuses[EVENT_STATUS_MAP[event.event_type] as VEHICLE_STATUS]
return (
Object.keys(rule.statuses).includes(EVENT_STATUS_MAP[event.event_type]) &&
status !== undefined &&
(status.length === 0 || (status as string[]).includes(event.event_type))
)
}
function routeDistance(coordinates: { lat: number; lng: number }[]): number {
const R = 6371000 // Earth's mean radius in meters
return (coordinates || [])
.map(coordinate => [rad(coordinate.lat), rad(coordinate.lng)])
.reduce((distance, point, index, points) => {
if (index > 0) {
const [lat1, lng1] = points[index - 1]
const [lat2, lng2] = point
const [dlat, dlng] = [lat2 - lat1, lng2 - lng1]
const a = Math.sin(dlat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dlng / 2) ** 2
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
const d = R * c
return distance + d
}
return distance
}, 0)
}
export {
isUUID,
isPct,
isTimestamp,
rangeRandom,
rangeRandomInt,
randomElement,
addDistanceBearing,
pointInShape,
makePointInShape,
getRandomSubarray,
round,
parseBBox,
capitalizeFirst,
nullKeys,
stripNulls,
isFloat,
now,
range,
nonNegInt,
days,
hours,
minutes,
seconds,
yesterday,
csv,
inc,
pathsFor,
isInsideBoundingBox,
head,
tail,
isStateTransitionValid,
pointInGeometry,
convertTelemetryToTelemetryRecord,
convertTelemetryRecordToTelemetry,
getPolygon,
isInStatesOrEvents,
routeDistance
}