-
Notifications
You must be signed in to change notification settings - Fork 1
/
bundle.js
546 lines (482 loc) · 16.1 KB
/
bundle.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
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
const calcStats = require("calc-stats");
const iterPixels = require("./iter-pixels");
module.exports = function calcBandStats({ image, bandIndex, calcStatsOptions = {} }) {
const noDataValue = image.getGDALNoData();
const pixels = iterPixels({ image, sample: bandIndex });
// clone to preserve immutabilty
calcStatsOptions = { ...calcStatsOptions };
calcStatsOptions.async = true;
if (noDataValue !== null) calcStatsOptions.noData = noDataValue;
return calcStats(pixels, calcStatsOptions);
};
},{"./iter-pixels":4,"calc-stats":6}],2:[function(require,module,exports){
module.exports = function getGDALStats(image, bandIndex) {
if (typeof bandIndex !== "number") throw new Error("you must specify bandIndex");
const bandStats = {};
const gdalMetadata = image.getGDALMetadata(bandIndex);
if (gdalMetadata) {
if (["string", "number"].includes(typeof gdalMetadata.STATISTICS_MAXIMUM)) {
const max = Number(gdalMetadata.STATISTICS_MAXIMUM);
if (!isNaN(max)) bandStats.max = max;
}
if (["string", "number"].includes(typeof gdalMetadata.STATISTICS_MINIMUM)) {
const min = Number(gdalMetadata.STATISTICS_MINIMUM);
if (!isNaN(min)) bandStats.min = min;
}
if (["string", "number"].includes(typeof gdalMetadata.STATISTICS_MEAN)) {
const mean = Number(gdalMetadata.STATISTICS_MEAN);
if (!isNaN(mean)) bandStats.mean = mean;
}
if (["string", "number"].includes(typeof gdalMetadata.STATISTICS_MEAN)) {
const median = Number(gdalMetadata.STATISTICS_MEDIAN);
if (!isNaN(median)) bandStats.median = median;
}
if (["string", "number"].includes(typeof gdalMetadata.STATISTICS_STDDEV)) {
const stddev = Number(gdalMetadata.STATISTICS_STDDEV);
if (!isNaN(stddev)) bandStats.stddev = stddev;
}
}
return bandStats;
};
},{}],3:[function(require,module,exports){
const getGDALStats = require("./get-gdal-stats");
const calcBandStats = require("./calc-band-stats");
/**
* @name getStats
* @param {Object} image - the image object from tiff.getImage() using the geotiff.js library
* @param {Object} options
* @param {Object} options.debug - set to true to log more information
* @param {Array<String>} options.enough - if these stats are in the GDAL Metadata, then we will avoid running calcStats on all the images' pixels. default is ["min", "max"]. valid values are "min", "max", "median", "mean", "sum", "mode", "modes"
* @param {Object} options.calcStatsOptions - options to pass along to [calc-stats](https://github.com/danieljdufour/calc-stats#advanced-usage)
* @returns {Array<Object>} - Array of Statistics Objects
*/
async function getStats(image, options = {}) {
// support old getStats(image, debug)
if (options === true) options = { calcStatsOptions: undefined, debug: true };
const { debug, enough = ["min", "max"] } = options || {};
if (debug) console.log("[geotiff-stats] debug:", debug);
const calcStatsOptions = typeof options.calcStatsOptions === "object" ? { ...options.calcStatsOptions } : {};
const noDataValue = image.getGDALNoData();
if (debug) console.log("[geotiff-stats] noDataValue:", noDataValue);
const samplesPerPixel = image.getSamplesPerPixel();
if (debug) console.log("[geotiff-stats] samplesPerPixel:", samplesPerPixel);
const stats = {
bands: []
};
for (let bandIndex = 0; bandIndex < samplesPerPixel; bandIndex++) {
if (debug) console.log("[geotiff-stats] bandIndex:", bandIndex);
let bandStats = getGDALStats(image, bandIndex);
const isFloat = image.getSampleFormat(bandIndex) === 3;
const sufficient = enough.every(key => typeof bandStats[key] === "number");
if (debug) console.log("[geotiff-stats] sufficient:", sufficient);
if (!sufficient) {
if (debug)
console.log(
"[geotiff-stats] we weren't able to parse enough stats from the image's metadata, so running calcStats"
);
// let rangeFilter;
// if (typeof bandStats.max === "number" && typeof bandStats.min === "number") {
// rangeFilter = ({ value }) => value >= bandStats.min && value <= bandStats.max;
// } else if (typeof bandStats.max === "number") {
// rangeFilter = ({ value }) => value <= bandStats.max;
// } else if (typeof bandStats.min === "number") {
// rangeFilter = ({ value }) => value >= bandStats.min;
// }
let signFilter;
if (isFloat && typeof bandStats.min === "number" && bandStats.min >= 0) {
// sometimes there's an inconsistency in the GDAL NoData value for 32-bit floating point rasters
// and I'm not sure why, but we can fix it
// if all the values are positive (according to the GDAL Metadata), except for the No Data Value,
// then if we see a negative number, it's probably going to supposed to be no data
signFilter = ({ value }) => value >= 0;
}
if (typeof signFilter === "function") {
if (typeof calcStatsOptions.filter === "function") {
const userProvidedFilter = calcStatsOptions.filter;
calcStatsOptions.filter = data => {
return signFilter(data) && userProvidedFilter(data);
};
} else {
calcStatsOptions.filter = signFilter;
}
}
const calculated = await calcBandStats({ image, bandIndex, calcStatsOptions });
Object.assign(bandStats, calculated);
}
stats.bands.push(bandStats);
}
if (debug) console.log("[geotiff-stats] returning: " + JSON.stringify(stats));
return stats;
}
if (typeof module === "object") module.exports = { getStats };
if (typeof window === "object") window.getStats = getStats;
},{"./calc-band-stats":1,"./get-gdal-stats":2}],4:[function(require,module,exports){
const { wrapNextFunction } = require("iter-fun");
const getGDALStats = require("./get-gdal-stats");
const iterTiles = require("./iter-tiles");
module.exports = function iterPixels({ image, sample }) {
if (typeof sample !== "number") throw new Error("you must specify a bandIndex");
const height = image.getHeight();
const width = image.getWidth();
const tileWidth = image.getTileWidth();
const tileHeight = image.getTileHeight();
const numTilesPerRow = Math.ceil(width / tileWidth);
const numTilesPerCol = Math.ceil(height / tileHeight);
const numTiles = numTilesPerRow * numTilesPerCol;
let nums;
let i = -1;
let iend = 0;
let tileRequests = 0;
let tiles = iterTiles(image, [sample]);
return wrapNextFunction(() => {
i++;
if (i === iend) {
if (tileRequests === numTiles) {
return { done: true };
} else {
return {
done: false,
value: tiles.next().value.then(tile => {
tileRequests++;
nums = tile[0];
i = 0;
iend = nums.length;
return nums[i];
})
};
}
} else {
return {
done: false,
value: nums[i]
};
}
});
};
},{"./get-gdal-stats":2,"./iter-tiles":5,"iter-fun":8}],5:[function(require,module,exports){
const { wrapNextFunction } = require("iter-fun");
module.exports = function iterTiles(image, samples) {
const height = image.getHeight();
const width = image.getWidth();
const tileWidth = image.getTileWidth();
const tileHeight = image.getTileHeight();
const numTilesPerRow = Math.ceil(width / tileWidth);
const numTilesPerCol = Math.ceil(height / tileHeight);
const numTiles = numTilesPerRow * numTilesPerCol;
let tileIndex = -1;
const iterTiles = wrapNextFunction(function next() {
try {
tileIndex++;
if (tileIndex >= numTiles) {
return { value: false, done: true };
} else {
const row = Math.floor(tileIndex / numTilesPerRow);
const column = tileIndex % numTilesPerRow;
const xmin = column * tileWidth;
const ymin = row * tileHeight;
const xmax = xmin + tileWidth;
const ymax = ymin + tileHeight;
const imageWindow = [xmin, ymin, Math.min(width, xmax), Math.min(height, ymax)];
const rasters = image.readRasters({
samples,
window: imageWindow
});
return { value: rasters, done: false };
}
} catch (error) {
console.error(error);
}
});
return iterTiles;
};
},{"iter-fun":8}],6:[function(require,module,exports){
const { getOrCreateIterator } = require("iter-fun");
const fasterMedian = require("faster-median");
function calcStats(
data,
{
async = false,
noData = undefined,
filter = undefined,
calcHistogram = true,
calcMax = true,
calcMean = true,
calcMedian = true,
calcMin = true,
calcMode = true,
calcModes = true,
calcSum = true
} = { debugLevel: 0 }
) {
const iter = getOrCreateIterator(data);
let needCount = calcMean || calcMedian || typeof filter === "function";
let needHistogram = calcHistogram || calcMedian || calcMode || calcModes;
let needSum = calcSum || calcMean;
let count = 0;
let index = 0;
let min;
let max;
let sum = 0;
const histogram = {};
// after it processes filtering
const process = value => {
if (needCount) count++;
if (calcMin && (min === undefined || value < min)) min = value;
if (calcMax && (max === undefined || value > max)) max = value;
if (needSum) sum += value;
if (needHistogram) {
if (value in histogram) histogram[value].ct++;
else histogram[value] = { n: value, ct: 1 };
}
};
let step;
if (typeof noData === "number" && typeof filter === "function") {
step = value => {
index++;
if (value !== noData && filter({ count, index, value }) === true) {
process(value);
}
};
} else if (typeof noData === "number") {
step = value => value !== noData && process(value);
} else if (typeof filter === "function") {
step = value => {
index++;
if (filter({ count, index, value }) === true) {
process(value);
}
};
} else {
step = process;
}
const finish = () => {
const results = {};
if (calcMedian)
results.median = fasterMedian({ counts: histogram, total: count });
if (calcMin) results.min = min;
if (calcMax) results.max = max;
if (calcSum) results.sum = sum;
if (calcMean) results.mean = sum / count;
if (calcHistogram) results.histogram = histogram;
if (calcMode || calcModes) {
let highest_count = 0;
let modes = [];
for (let key in histogram) {
const { n, ct } = histogram[key];
if (ct === highest_count) {
modes.push(n);
} else if (ct > highest_count) {
highest_count = ct;
modes = [n];
}
}
if (calcModes) results.modes = modes;
// compute mean value of all the most popular numbers
if (calcMode)
results.mode = modes.reduce((acc, n) => acc + n, 0) / modes.length;
}
return results;
};
if (async) {
return (async () => {
for await (let value of iter) step(value);
return finish();
})();
} else {
for (let value of iter) step(value);
return finish();
}
}
module.exports = calcStats;
},{"faster-median":7,"iter-fun":8}],7:[function(require,module,exports){
const countWithTotal = ({ nums, no_data }) => {
let len = nums.length;
const counts = {};
let total = 0;
if (no_data !== undefined) {
for (let i = 0; i < len; i++) {
const n = nums[i];
if (n !== no_data) {
total++;
if (n in counts) counts[n].ct++;
else counts[n] = { n, ct: 1 };
}
}
} else {
for (let i = 0; i < len; i++) {
const n = nums[i];
total++;
if (n in counts) counts[n].ct++;
else counts[n] = { n, ct: 1 };
}
}
return { counts, total };
};
const median_of_a_few = ({ nums, no_data }) => {
nums = nums.filter(n => n !== no_data).sort((a, b) => a - b);
switch (nums.length) {
case 0:
return undefined;
case 1:
return nums[0];
default:
const mid = nums.length / 2;
if (nums.length % 2 === 0) {
return (nums[mid - 1] + nums[mid]) / 2;
} else {
return nums[Math.floor(mid)];
}
}
};
const median_of_a_lot = ({ counts, nums, no_data, total }) => {
if (counts === undefined || total === undefined) {
({ counts, total } = countWithTotal({ nums, no_data }));
}
// sort counts by value
const countArray = Object.values(counts).sort((a, b) => a.n - b.n);
const half = total / 2;
const number_of_unique_values = countArray.length;
if (number_of_unique_values === 0) {
return undefined;
} else if (number_of_unique_values === 1) {
return countArray[0].n;
} else {
let x = 0;
if (total % 2 === 0) {
for (let i = 0; i < number_of_unique_values; i++) {
const { n, ct } = countArray[i];
x += ct;
if (x > half) {
// handle if odd or even
// just barely pass cut off
if (x - ct === half) {
return (countArray[i - 1].n + n) / 2;
} else {
return n;
}
}
}
} else {
for (let i = 0; i < number_of_unique_values; i++) {
const { n, ct } = countArray[i];
x += ct;
if (x > half) return n;
}
}
}
};
const fasterMedian = ({ nums, no_data, threshold = 50, counts, total }) => {
if (counts !== undefined || total !== undefined || nums.length > threshold)
return median_of_a_lot({ counts, total, nums, no_data });
else return median_of_a_few({ nums, no_data });
};
if (typeof module === "object") module.exports = fasterMedian;
if (typeof window === "object") window.fasterMedian = fasterMedian;
if (typeof self === "object") self.fasterMedian = fasterMedian;
},{}],8:[function(require,module,exports){
function addSymbolIterator(obj) {
try {
obj[Symbol.iterator] = function () {
return this;
};
} catch (error) {
// pass
}
}
function addSymbolIteratorFallback(obj) {
obj["@@iterator"] = function () {
return this;
};
}
function wrapNextFunction(next) {
const iter = { next };
addSymbolIterator(iter);
addSymbolIteratorFallback(iter);
return iter;
}
function isArray(data) {
try {
return data.constructor.name.endsWith("Array");
} catch {
return false;
}
}
function hasNext(data) {
try {
return typeof data.next === "function";
} catch {
return false;
}
}
function hasIterator(data) {
try {
return "@@iterator" in data;
} catch {
return false;
}
}
function hasSymbolIterator(data) {
try {
return Symbol.iterator in data.constructor.prototype;
} catch {
return false;
}
}
function isIterator(data) {
try {
return (
Symbol.iterator in data &&
typeof data.next === "function" &&
data.propertyIsEnumerable("next") === false
);
} catch {
return false;
}
}
function getIterator(data) {
const iter = data["@@iterator"];
if (hasNext(iter)) {
return iter;
} else if (typeof iter === "function") {
return iter();
}
}
function createIterator(data) {
let i = 0;
let len = data.length;
const next = () =>
i++ < len ? { value: data[i], done: false } : { done: true };
return wrapNextFunction(next);
}
function getOrCreateIterator(data) {
if (isIterator(data)) {
return data;
} else if (hasSymbolIterator(data)) {
return data[Symbol.iterator]();
} else if (hasNext(data)) {
return wrapNextFunction(data.next);
} else if (hasIterator(data)) {
return getIterator(data);
} else if (typeof data === "string" || isArray(data)) {
return createIterator(data);
} else {
throw "[iter-fun] unable to determine iterator";
}
}
if (typeof module === "object") {
module.exports = {
addSymbolIterator,
addSymbolIteratorFallback,
isIterator,
isArray,
hasNext,
hasSymbolIterator,
hasIterator,
getIterator,
createIterator,
getOrCreateIterator,
wrapNextFunction
};
}
},{}]},{},[3]);