Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use spatial index to speed up #34

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 38 additions & 6 deletions lib/methods/areal-weighting.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const Turf = require('turf');
const Logger = require('../logger');
const isUndefined = require('lodash/isUndefined');
const rbush = require('rbush');

function main(source, target, options) {
target.features.forEach((d, i) => {
Expand All @@ -18,6 +19,7 @@ function arealWeighting(feature, source, options, attributeName) {
const intersectData = getIntersectingFeatures(source.features, feature);
const sourceFeatures = intersectData[0];
const intersects = intersectData[1];


intersects.forEach((d,i) => {
const Ps = parseFloat(sourceFeatures[i].properties[attributeName]);
Expand All @@ -32,18 +34,48 @@ function arealWeighting(feature, source, options, attributeName) {

function getIntersectingFeatures(sourceFeatures, targetFeature) {
let intersects = [];
let featureSimpl = targetFeature;
let sourceList = []; // source features that got intersected?

/* Create and fill the bushy tree */
var tree = rbush();
let items = [];

for (var i=0; i<sourceFeatures.length; i++) {
var bbox = Turf.extent(sourceFeatures[i]);
var item = {
minX: bbox[0],
minY: bbox[1],
maxX: bbox[2],
maxY: bbox[3],
index: i
};
items.push(item);
}

tree.load(items);

const sourceList = sourceFeatures.filter(f => {
let intersection = Turf.intersect(featureSimpl, f);
/* Quickly get the likely candidates that might intersect */
var bbox = Turf.extent(targetFeature);
var candidates = tree.search({
minX: bbox[0],
minY: bbox[1],
maxX: bbox[2],
maxY: bbox[3]
});

/* Check the candidates for actual intersection and do the rest */
for (var i=0; i<candidates.length; i++) {
var index = candidates[i].index;
var f = sourceFeatures[index];

let intersection = Turf.intersect(targetFeature, f);

if(!isUndefined(intersection)) {
intersection.properties = f.properties;
intersects.push(intersection);
sourceList.push(f);
}

return !isUndefined(intersection);
});
}

return [sourceList, intersects];
}
Expand Down