-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzonal.js
571 lines (455 loc) · 20.9 KB
/
zonal.js
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
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var calculateArea = require("@turf/area")["default"];
var clone = require("@turf/clone")["default"];
var difference = require("@turf/difference")["default"];
var dissolve = require("@turf/dissolve")["default"];
var booleanPointInPolygon = require("@turf/boolean-point-in-polygon")["default"];
var _require = require("@turf/meta"),
featureEach = _require.featureEach,
geomEach = _require.geomEach; // replacement for Object.entries in case Object.entries
// isn't defined
function entries(object) {
var results = [];
for (var key in object) {
results.push([key, object[key]]);
}
return results;
}
function values(object) {
var results = [];
for (var key in object) {
results.push(object[key]);
}
return results;
}
function getClassGeometryType(geom) {
switch (geom.type) {
case "Polygon":
case "MultiPolygon":
return "Polygon";
case "Point":
case "MultiPoint":
return "Point";
}
}
function getArrayKey(_ref) {
var feature = _ref.feature,
index = _ref.index,
geometry = _ref.geometry,
props = _ref.props;
if (props) {
var key = [];
props.forEach(function (prop) {
if (typeof prop === "string") {
key.push(feature.properties[prop]);
} else if (typeof prop === "function") {
key.push(prop({
feature: feature,
geometry: geometry
}));
}
});
return key;
} else {
return [index];
}
}
function unarray(arr) {
return arr.length === 1 ? arr[0] : arr;
} // https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript
function hash(string) {
var hash = 0;
for (var i = 0; i < string.length; i++) {
var chr = string.charCodeAt(i);
hash = (hash << 5) - hash + chr;
}
return hash;
} // randomly returns either 1 or -1
var randSign = function randSign() {
return Math.random() < 0.5 ? 1 : -1;
};
var shift = function shift() {
return randSign() * Math.random() * 1e-7;
};
var shiftRing = function shiftRing(ring) {
return ring.map(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
x = _ref3[0],
y = _ref3[1];
return [x + shift(), y + shift()];
});
};
var shiftPolygon = function shiftPolygon(rings) {
return rings.map(shiftRing);
};
var shiftMultiPolygon = function shiftMultiPolygon(polygons) {
return polygons.map(shiftPolygon);
};
function shiftGeometry(geom) {
if (geom.type === "Polygon") {
geom.coordinates = shiftPolygon(geom.coordinates);
} else if (geom.type === "MultiPolygon") {
geom.coordinates = shiftMultiPolygon(geom.coordinates);
}
return geom;
} // assumptions
// - zones is a GeoJSON with polygons
// - classes are either all polygons/multi-polygons or all points (not mix of polygons and points)
function calculate(_ref4) {
var zones = _ref4.zones,
zone_properties = _ref4.zone_properties,
classes = _ref4.classes,
class_properties = _ref4.class_properties,
class_geometry_type = _ref4.class_geometry_type,
_ref4$include_zero_co = _ref4.include_zero_count,
include_zero_count = _ref4$include_zero_co === void 0 ? false : _ref4$include_zero_co,
_ref4$include_zero_ar = _ref4.include_zero_area,
include_zero_area = _ref4$include_zero_ar === void 0 ? false : _ref4$include_zero_ar,
_ref4$include_null_cl = _ref4.include_null_class_rows,
include_null_class_rows = _ref4$include_null_cl === void 0 ? true : _ref4$include_null_cl,
_ref4$class_propertie = _ref4.class_properties_delimiter,
class_properties_delimiter = _ref4$class_propertie === void 0 ? "," : _ref4$class_propertie,
_ref4$dissolve_classe = _ref4.dissolve_classes,
dissolve_classes = _ref4$dissolve_classe === void 0 ? false : _ref4$dissolve_classe,
_ref4$preserve_featur = _ref4.preserve_features,
preserve_features = _ref4$preserve_featur === void 0 ? true : _ref4$preserve_featur,
_ref4$remove_features = _ref4.remove_features_with_no_overlap,
remove_features_with_no_overlap = _ref4$remove_features === void 0 ? false : _ref4$remove_features,
on_before_each_zone_feature = _ref4.on_before_each_zone_feature,
on_after_each_zone_feature = _ref4.on_after_each_zone_feature,
feature_filter = _ref4.feature_filter,
_ref4$debug_level = _ref4.debug_level,
debug_level = _ref4$debug_level === void 0 ? 0 : _ref4$debug_level;
if (!classes) throw new Error("[zonal] classes are missing or empty");
if (!zones) throw new Error("[zonal] zones are missing or empty");
if (Array.isArray(zone_properties) && zone_properties.length === 0) {
throw new Error("[zonal] zone_properties is an empty array");
}
if (Array.isArray(class_properties) && class_properties.length === 0) {
throw new Error("[zonal] class_properties is an empty array");
}
if (typeof zone_properties === "string") {
throw new Error("[zonal] zone_properties is a string. it should be an array.");
}
if (typeof class_properties === "string") {
throw new Error("[zonal] class_properties is a string. it should be an array.");
}
if (preserve_features && remove_features_with_no_overlap) {
throw new Error("[zonal] you can't preserve features while also removing features that don't overlap classes");
}
if ([undefined, null].includes(zone_properties)) {
console.warn("[zonal] you didn't pass in zone_properties, so defaulting to the zonal feature index number");
}
if ([undefined, null].includes(class_properties)) {
console.warn("[zonal] you didn't pass in class_properties, so defaulting to the class feature index number");
} // stats keyed by the unique zone+class combo id
// e.g. { '["AK","Hot"]': 10, '["AK","Cold"]': 342 }
// e.g. { [combo_id]: { area: <Number> }}
var stats = {}; // { [zone_id]: <total_area_of_zone_in_square_meters> }
var zone_to_area = {}; // { [class_id]: [<array of polygons or points>] }
var class_to_geometries = {};
if (Array.isArray(class_properties) && class_properties.length === 1 && dissolve_classes) {
classes = dissolve(classes, {
propertyName: class_properties[0]
});
if (debug_level >= 1) console.log("[zonal] dissolved classes");
} // group class geometries into dictionary objects
featureEach(classes, function (class_feature, class_feature_index) {
geomEach(class_feature, function (class_geometry, class_geometry_index) {
var _class_to_geometries$;
var class_array = getArrayKey({
feature: class_feature,
geometry: class_geometry,
props: class_properties,
index: class_feature_index
}); // convert class id array to string
var class_id = JSON.stringify(class_array); // is the class type points, lines or polygons?
if (!class_geometry_type) class_geometry_type = getClassGeometryType(class_geometry); // unexpected class geometry change, like a point within a collection of polygons
if (getClassGeometryType(class_geometry) !== class_geometry_type) {
console.warn("[zonal] we encountered an unexpected class geometry, so we're skipping it");
return;
}
var class_geometry_hash = hash(JSON.stringify(class_geometry.coordinates));
(_class_to_geometries$ = class_to_geometries[class_id]) !== null && _class_to_geometries$ !== void 0 ? _class_to_geometries$ : class_to_geometries[class_id] = {};
class_to_geometries[class_id][class_geometry_hash] = class_geometry;
});
});
if (debug_level >= 1) console.log("[zonal] grouped geometries by class"); // zones must be one or more features with polygon geometries
// like administrative districts
featureEach(zones, function (zone_feature, zone_feature_index) {
if (feature_filter && feature_filter({
feature: zone_feature,
index: zone_feature_index
}) === false) {
return;
}
if (typeof on_before_each_zone_feature === "function") {
on_before_each_zone_feature({
feature: zone_feature,
feature_index: zone_feature_index,
stats: stats,
zone_to_area: zone_to_area
});
}
geomEach(zone_feature, function (zone_geometry, geometry_index) {
var _zone_feature$propert, _zone_to_area$zone_id;
// sometimes the same zone could be split up amonst multiple features
// for example, you could have a country with multiple islands
var zone_array = getArrayKey({
feature: zone_feature,
geometry: zone_geometry,
props: zone_properties,
index: zone_feature_index
});
var zone_id = JSON.stringify(zone_array);
(_zone_feature$propert = zone_feature.properties) !== null && _zone_feature$propert !== void 0 ? _zone_feature$propert : zone_feature.properties = {};
zone_feature.properties["zonal:zone_id"] = zone_array; // track the total area of the zone across all its features
(_zone_to_area$zone_id = zone_to_area[zone_id]) !== null && _zone_to_area$zone_id !== void 0 ? _zone_to_area$zone_id : zone_to_area[zone_id] = 0;
var zone_geometry_area = calculateArea(zone_geometry);
zone_to_area[zone_id] += zone_geometry_area; // this is the remaining polygonal area of the zone
// after you have subtracted the overlap with classes
// it will be used to compute the area without a class
// for example, if you have wind speed polygons
// you might want to know how much area is unaffected
var remaining_zone_geometry_for_all_classes = zone_geometry;
entries(class_to_geometries).forEach(function (_ref5) {
var _ref6 = _slicedToArray(_ref5, 2),
class_id = _ref6[0],
class_geometries = _ref6[1];
// unique identifier for the zone + class combo
// there will be a row in the table for each zone + class combo
var combo_id = JSON.stringify([zone_id, class_id]);
var remaining_zone_geometry_for_specific_class = zone_geometry;
Object.values(class_geometries).forEach(function (class_geometry) {
if (class_geometry_type === "Point") {
var _stats$combo_id;
(_stats$combo_id = stats[combo_id]) !== null && _stats$combo_id !== void 0 ? _stats$combo_id : stats[combo_id] = {
count: 0
};
var xy = class_geometry.coordinates;
var inside = booleanPointInPolygon(xy, zone_geometry);
if (inside) {
// increase number of times the combo is found
stats[combo_id].count++;
}
} else if (class_geometry_type === "Polygon") {
if (remaining_zone_geometry_for_all_classes) {
try {
remaining_zone_geometry_for_all_classes = difference(remaining_zone_geometry_for_all_classes, class_geometry);
} catch (error) {
remaining_zone_geometry_for_all_classes = difference(remaining_zone_geometry_for_all_classes, shiftGeometry(clone(class_geometry)));
}
}
if (remaining_zone_geometry_for_specific_class) {
try {
remaining_zone_geometry_for_specific_class = difference(remaining_zone_geometry_for_specific_class, class_geometry);
} catch (error) {
remaining_zone_geometry_for_all_classes = difference(remaining_zone_geometry_for_specific_class, shiftGeometry(clone(class_geometry)));
}
}
}
});
if (class_geometry_type === "Polygon") {
var _stats$combo_id2;
(_stats$combo_id2 = stats[combo_id]) !== null && _stats$combo_id2 !== void 0 ? _stats$combo_id2 : stats[combo_id] = {
area: 0
};
var remaining_area = remaining_zone_geometry_for_specific_class ? calculateArea(remaining_zone_geometry_for_specific_class) : 0; // there's no way you can have more remaining than the actual size of the zone
// this happens because of floating point arithmetic issues
if (remaining_area > zone_geometry_area) remaining_area = zone_geometry_area; // area where zone geometry and class overlap
stats[combo_id].area += Math.round(zone_geometry_area - remaining_area);
}
}); // after we've gone through all the classes
// see what's left and save the area of the part of the zone
// that aren't overlapped by a class
if (class_geometry_type === "Polygon") {
var _stats$zone_without_c;
var zone_without_class_id = JSON.stringify([zone_id, null]);
(_stats$zone_without_c = stats[zone_without_class_id]) !== null && _stats$zone_without_c !== void 0 ? _stats$zone_without_c : stats[zone_without_class_id] = {
area: 0
};
stats[zone_without_class_id].area += remaining_zone_geometry_for_all_classes ? Math.round(calculateArea(remaining_zone_geometry_for_all_classes)) : 0;
}
});
if (typeof on_after_each_zone_feature === "function") {
on_after_each_zone_feature({
feature: zone_feature,
feature_index: zone_feature_index,
stats: stats,
zone_to_area: zone_to_area
});
}
}); // calculate percentages
entries(stats).forEach(function (_ref7) {
var _ref8 = _slicedToArray(_ref7, 2),
combo_id = _ref8[0],
combo_stats = _ref8[1];
var _JSON$parse = JSON.parse(combo_id),
_JSON$parse2 = _slicedToArray(_JSON$parse, 2),
zone_id = _JSON$parse2[0],
class_id = _JSON$parse2[1];
if ("area" in combo_stats) {
combo_stats.percentage = combo_stats.area / Math.round(zone_to_area[zone_id]);
}
}); // reformat stats for return
var columns = [];
var first_pass = true;
var rows = [];
var _loop = function _loop(combo_id) {
var combo_stats = stats[combo_id];
var _JSON$parse5 = JSON.parse(combo_id),
_JSON$parse6 = _slicedToArray(_JSON$parse5, 2),
zone_id = _JSON$parse6[0],
class_id = _JSON$parse6[1]; // convert zone_id from string to array
zone_id = JSON.parse(zone_id); // convert class id from string to array
class_id = JSON.parse(class_id);
if (include_null_class_rows === false && class_id === null) {
return "continue";
}
var row = {};
zone_id.map(function (it, i) {
var key = Array.isArray(zone_properties) ? zone_properties[i] : "index";
var zone_key = "zone:" + key;
row[zone_key] = it;
if (first_pass) columns.push(zone_key);
});
(class_id || [null]).map(function (it, i) {
var key = Array.isArray(class_properties) ? class_properties[i] : "index";
var class_key = "class:" + key;
row[class_key] = it;
if (first_pass) columns.push(class_key);
});
for (var stat_name in combo_stats) {
var stat_key = "stat:" + stat_name;
row[stat_key] = combo_stats[stat_name];
if (first_pass) columns.push(stat_key);
}
rows.push(row);
first_pass = false;
};
for (var combo_id in stats) {
var _ret = _loop(combo_id);
if (_ret === "continue") continue;
}
if (!include_zero_count) {
rows = rows.filter(function (row) {
return row["stat:count"] !== 0;
});
}
if (!include_zero_area) {
rows = rows.filter(function (row) {
return row["stat:area"] !== 0;
});
} // sort rows by columns from left to right
rows.sort(function (a, b) {
for (var c = 0; c < columns.length; c++) {
var col = columns[c];
var aval = a[col];
var bval = b[col];
if (aval === null && bval !== null) return 1;else if (aval !== null && bval === null) return -1;
if (a[col] > b[col]) return 1;else if (a[col] < b[col]) return -1;
}
return 0;
});
var results = {
table: {
columns: columns,
rows: rows
}
};
results.geojson = zones; // group stats by zone
var zone_id_to_stats = {};
for (var _combo_id in stats) {
var _zone_id_to_stats$zon;
var combo_stats = stats[_combo_id];
var _JSON$parse3 = JSON.parse(_combo_id),
_JSON$parse4 = _slicedToArray(_JSON$parse3, 2),
zone_id = _JSON$parse4[0],
class_id = _JSON$parse4[1];
(_zone_id_to_stats$zon = zone_id_to_stats[zone_id]) !== null && _zone_id_to_stats$zon !== void 0 ? _zone_id_to_stats$zon : zone_id_to_stats[zone_id] = {};
zone_id_to_stats[zone_id][class_id] = combo_stats;
} // aggregate statistics
var agg_stats = {};
for (var _zone_id in zone_id_to_stats) {
var zone_stats = {};
var pairs = entries(zone_id_to_stats[_zone_id]);
var sorted_by_area = pairs.filter(function (it) {
return !["null", '["null"]'].includes(it[0]);
}).filter(function (it) {
return it[1].area !== 0;
}) // filter out zone-class combinations that don't exist
.sort(function (a, b) {
return a[1].area - b[1].area;
});
if (sorted_by_area.length > 0) {
zone_stats.minority = unarray(JSON.parse(sorted_by_area[0][0]));
zone_stats.majority = unarray(JSON.parse(sorted_by_area[sorted_by_area.length - 1][0]));
}
var zone_area = zone_to_area[_zone_id];
if (class_geometry_type === "Polygon") {
var unclassed_percentage = pairs.find(function (pair) {
return pair[0] === "null";
})[1].percentage;
zone_stats.percentage = 1 - unclassed_percentage;
zone_stats.sum = Math.round(zone_stats.percentage * zone_area);
agg_stats[_zone_id] = zone_stats;
}
}
if (!preserve_features) zones = clone(zones);
var delete_these_features = [];
featureEach(zones, function (zone_feature, zone_feature_index) {
var props = zone_feature.properties;
var zone_id = JSON.stringify(props["zonal:zone_id"]);
props["zonal:stat:area"] = Math.round(zone_to_area[zone_id]);
entries(agg_stats[zone_id]).forEach(function (_ref9) {
var _ref10 = _slicedToArray(_ref9, 2),
stat_name = _ref10[0],
stat_value = _ref10[1];
props["zonal:stat:" + stat_name] = stat_value;
});
props["zonal:stat:classes"] = entries(zone_id_to_stats[zone_id]).reduce(function (acc, _ref11) {
var _ref12 = _slicedToArray(_ref11, 2),
key = _ref12[0],
stats = _ref12[1];
key = JSON.parse(key);
key = Array.isArray(key) ? key.join(class_properties_delimiter) : key;
if (stats.area > 0) acc[key] = stats;
return acc;
}, {});
if (remove_features_with_no_overlap) {
var class_keys = Object.keys(props["zonal:stat:classes"]);
if (class_keys.length === 0 || class_keys[0] === "null") {
// don't want to delete in the middle of a for loop
// so save the index to delete later
delete_these_features.push(zone_feature_index);
}
}
});
if (delete_these_features.length > 0) {
if (zones.type === "Feature") {
zones = null;
} else if (zones.type === "FeatureCollection") {
zones.features = zones.features.filter(function (_, i) {
return !delete_these_features.includes(i);
});
}
}
results.geojson = zones;
return results;
}
var zonal = {
calculate: calculate
};
if (typeof define === "function" && define.amd) define(function () {
return zonal;
});
if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object") module.exports = zonal;
if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object") window.zonal = zonal;
if ((typeof self === "undefined" ? "undefined" : _typeof(self)) === "object") self.zonal = zonal;