Skip to content

Commit

Permalink
fix: merge holes with neighboring polygons
Browse files Browse the repository at this point in the history
  • Loading branch information
Sujanadh committed Sep 18, 2024
1 parent 8cc7663 commit f8d7614
Showing 1 changed file with 59 additions and 2 deletions.
61 changes: 59 additions & 2 deletions fmtm_splitter/fmtm_algorithm.sql
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,8 @@ CREATE TABLE taskpolygons AS (
),

taskpolygonsnoindex AS (
SELECT (ST_DUMP(ST_POLYGONIZE(s.geom))).geom AS geom
SELECT
(ST_DUMP(ST_POLYGONIZE(s.geom))).geom AS geom
FROM simplifiedlines AS s
)

Expand All @@ -380,13 +381,68 @@ CREATE TABLE taskpolygons AS (
);

-- ALTER TABLE taskpolygons ADD PRIMARY KEY(taskid);

-- Step 1: Identify polygons without any buildings
DROP TABLE IF EXISTS no_building_polygons;
CREATE TABLE no_building_polygons AS (
SELECT tp.geom AS no_building_geom, tp.*
FROM taskpolygons tp
LEFT JOIN buildings b ON ST_Intersects(tp.geom, b.geom)
WHERE b.geom IS NULL
);

-- Step 2: Identify neighboring polygons
DROP TABLE IF EXISTS neighboring_polygons;
CREATE TABLE neighboring_polygons AS (
SELECT nb.geom AS neighbor_geom, nb.*, nb_building_count, nbp.no_building_geom
FROM taskpolygons nb
JOIN no_building_polygons nbp
ON ST_Touches(nbp.no_building_geom, nb.geom) -- Finds polygons that touch each other
LEFT JOIN (
-- Step 3: Count buildings in the neighboring polygons
SELECT nb.geom, COUNT(b.geom) AS nb_building_count
FROM taskpolygons nb
LEFT JOIN buildings b ON ST_Intersects(nb.geom, b.geom)
GROUP BY nb.geom
) AS building_counts
ON nb.geom = building_counts.geom
);

-- Step 4: Find the optimal neighboring polygon to avoid,
-- same polygons with the smallest number of buildings merging into multiple neighboring polygons
DROP TABLE IF EXISTS optimal_neighbors;
CREATE TABLE optimal_neighbors AS (
SELECT nbp.no_building_geom, nbp.neighbor_geom
FROM neighboring_polygons nbp
WHERE nbp.nb_building_count = (
SELECT MIN(nb_building_count)
FROM neighboring_polygons np
WHERE np.no_building_geom = nbp.no_building_geom
)
);

-- Step 5: Merge the small polygons with their optimal neighboring polygons
UPDATE taskpolygons tp
SET geom = ST_Union(tp.geom, nbp.no_building_geom)
FROM optimal_neighbors nbp
WHERE tp.geom = nbp.neighbor_geom;
DELETE FROM taskpolygons
WHERE geom IN (
SELECT no_building_geom
FROM no_building_polygons
);


DROP TABLE IF EXISTS no_building_polygons;
DROP TABLE IF EXISTS neighboring_polygons;

SELECT POPULATE_GEOMETRY_COLUMNS('public.taskpolygons'::regclass);
CREATE INDEX taskpolygons_idx
ON taskpolygons
USING gist (geom);
-- VACUUM ANALYZE taskpolygons;


-- Generate GeoJSON output
SELECT
JSONB_BUILD_OBJECT(
'type', 'FeatureCollection',
Expand All @@ -401,3 +457,4 @@ FROM (
) AS feature
FROM taskpolygons
) AS features;

0 comments on commit f8d7614

Please sign in to comment.