Skip to content

Commit

Permalink
fix index error if input gdf has own index [issue #8]
Browse files Browse the repository at this point in the history
`xa.get_pixel_overlaps()` creates a `poly_idx` column in the `gdf` that takes as its value the index of the input `gdf`. However, if there is a pre-existing index, this can lead to bad behavior, since `poly_idx` is used as an `.iloc` indexer in the `gdf`. This update instead makes `poly_idx` `np.arange(0,len(gdf))`, which will avoid this indexing issue (and hopefully not cause any more? I figured there would've been a reason I used the existing index if not a new one... fingers crossed).
  • Loading branch information
ks905383 committed Jun 30, 2021
1 parent 1f91b14 commit 65351d4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
22 changes: 22 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,28 @@ def test_get_pixel_overlaps_passthru_weights(pix_agg=pix_agg):

# Should probably test multiple polygons just to be sure...


###### get_pixel_overlaps() and aggregate() coupling tests #####
def test_get_pixel_overlaps_gdf_wpreexisting_index(pix_agg=pix_agg):
# Test to make sure it works with pre-existing indices in the gdf
# Create polygon covering multiple pixels
gdf_test = {'name':['test'],
'geometry':[Polygon([(0,0),(0,1),(1,1),(1,0),(0,0)])]}
gdf_test = gpd.GeoDataFrame(gdf_test,crs="EPSG:4326",index=np.arange(10,11))

# Get pixel overlaps
wm_out = get_pixel_overlaps(gdf_test,pix_agg)

# The index error for an incorrectly-indexed gdf is thrown in aggregate()
agg = aggregate(ds,wm_out)

# this assert uses 2.1666 because of the weighting that creates
# the pix_agg variable that this whole section has used. Doesn't really
# matter, since this is testing an index error that would've
# happened during aggregate() above.
assert np.allclose([v for v in agg.agg.test.values],2.1666,rtol=1e-4)


##### aggregate() tests #####


Expand Down
5 changes: 3 additions & 2 deletions xagg/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,9 @@ def get_pixel_overlaps(gdf_in,pix_agg):


# Add an index for each polygon as a column to make indexing easier
if 'poly_idx' not in gdf_in.columns:
gdf_in['poly_idx'] = gdf_in.index.values
#if 'poly_idx' not in gdf_in.columns:
# gdf_in['poly_idx'] = gdf_in.index.values
gdf_in['poly_idx'] = np.arange(0,len(gdf_in))

# Match up CRSes
pix_agg['gdf_pixels'] = pix_agg['gdf_pixels'].to_crs(gdf_in.crs)
Expand Down

0 comments on commit 65351d4

Please sign in to comment.