Skip to content

perf(engine,coordinates): vectorize Impact.impact_at_reg CSR reduction and points_to_raster boxes - #1350

Merged
peanutfun merged 2 commits into
CLIMADA-project:developfrom
napattan:perf/vectorize-impact-at-reg-and-points-to-raster
Nov 16, 2026
Merged

peanutfun merged 2 commits into
CLIMADA-project:developfrom
napattan:perf/vectorize-impact-at-reg-and-points-to-raster

Conversation

@napattan

@napattan napattan commented Nov 6, 2026 •

Copy link
Copy Markdown

Changes proposed in this PR:

  • Vectorize Impact.impact_at_reg in climada/engine/impact.py by replacing the per-region Python list comprehension ([self.imp_mat[:, np.where(agg_regions == reg)[0]].sum(1) for reg in agg_reg_unique]) with np.unique(agg_regions, return_inverse=True) and a single CSR sparse indicator matrix multiplication (self.imp_mat @ reg_ind).toarray().
  • Vectorize the bounding-box construction inside points_to_raster in climada/util/coordinates.py (apply_box) by replacing row-wise df_exp.apply(lambda r: ..., axis=1) (Point(...).buffer(res / 2).envelope) with shapely.box(lon - res / 2, lat - res / 2, lon + res / 2, lat + res / 2).
  • Remove the redundant df_geom test block in climada/util/test/test_coordinates.py and replace the duplicated list-comprehension check in climada/engine/test/test_impact.py (TestImpactReg.test_agg_regions) with direct per-event assertions against self.imp.at_event and self.imp.imp_mat.toarray().

Benchmark Verification Script

import time
import geopandas as gpd
import numpy as np
from scipy import sparse

from climada.engine.impact import Impact
import climada.util.coordinates as u_coord


def bench_impact_at_reg(n_runs=10):
    rng = np.random.default_rng(42)
    n_events, n_exp, n_regions = 2_000, 50_000, 100
    imp_mat = sparse.random(
        n_events, n_exp, density=0.005, format="csr", random_state=rng, dtype=np.float64
    )
    agg_regions = rng.choice([f"REG_{i:03d}" for i in range(n_regions)], size=n_exp)

    imp = Impact(
        event_id=np.arange(1, n_events + 1),
        event_name=[f"ev_{i}" for i in range(1, n_events + 1)],
        date=np.arange(1, n_events + 1),
        frequency=np.ones(n_events) / n_events,
        coord_exp=np.zeros((n_exp, 2)),
        crs="EPSG:4326",
        eai_exp=np.zeros(n_exp),
        at_event=np.asarray(imp_mat.sum(axis=1)).ravel(),
        tot_value=1.0,
        aai_agg=0.0,
        unit="USD",
        imp_mat=imp_mat,
    )

    timings_ms = []
    for _ in range(n_runs):
        t0 = time.perf_counter()
        imp.impact_at_reg(agg_regions)
        timings_ms.append((time.perf_counter() - t0) * 1000.0)

    print(
        f"Impact.impact_at_reg ({n_events}x{n_exp}, {n_regions} regions): "
        f"median={np.median(timings_ms):.2f} ms "
        f"(mean={np.mean(timings_ms):.2f} ± {np.std(timings_ms):.2f} ms)"
    )


def bench_points_to_raster(n_runs=7):
    gx, gy = np.meshgrid(np.linspace(5.0, 14.95, 200), np.linspace(45.0, 49.95, 100))
    rng = np.random.default_rng(42)
    df_val = gpd.GeoDataFrame(
        {
            "latitude": gy.ravel(),
            "longitude": gx.ravel(),
            "value": rng.uniform(1.0, 100.0, size=gx.size),
        }
    )
    res = 0.05

    timings_ms = []
    for _ in range(n_runs):
        t0 = time.perf_counter()
        u_coord.points_to_raster(df_val, val_names=["value"], res=res, raster_res=res)
        timings_ms.append((time.perf_counter() - t0) * 1000.0)

    print(
        f"points_to_raster ({len(df_val)} pts, res={res}): "
        f"median={np.median(timings_ms):.2f} ms "
        f"(mean={np.mean(timings_ms):.2f} ± {np.std(timings_ms):.2f} ms)"
    )


if __name__ == "__main__":
    bench_impact_at_reg()
    bench_points_to_raster()

This PR fixes # (N/A — performance optimization)

PR Author Checklist

PR Reviewer Checklist

@peanutfun peanutfun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@napattan Thank you for your contribution! Please provide Python scripts to verify your claims on the speedup. Please also use the provided pull request description template (https://github.com/CLIMADA-project/climada_python/blob/main/.github/pull_request_template.md) for a smoother review. Finally, you added a test that does not verify anything (new). Please revise before we can merge

Comment thread climada/util/test/test_coordinates.py Resolved
@peanutfun peanutfun self-assigned this Nov 9, 2026
@napattan

napattan commented Nov 9, 2026

Copy link
Copy Markdown
Author

Hi @peanutfun, thank you for taking the time to review.

My background is in landscape architecture, and I have been trying on integrating computational workflow and spatial analysis into my landscape and urban fields. Also I have used AI aided in my coding workflow and I read CLIMADA's AI policy markdown now, I take full responsibility for every line of code in this PR. I am still very new to contributing in open-source projects, I truly apologize for missing description template, issuing very unclearly, and for redundant test.

I have updated the PR description above using .github/pull_request_template.md along with the Python benchmark script and a breakdown of both the isolated apply_box speedup (69.9x) and the full end-to-end points_to_raster (2.1x) and Impact.impact_at_reg (11.7x) speedups, and pushed a commit removing the redundant df_geom test in test_coordinates.py.

If you checked and think this is unhelpful, please feel free to close this issue.
Thank you for your time. I promise to be more considerate from now on.

@peanutfun

Copy link
Copy Markdown
Member

@napattan All good, I appreciate your frankness and I'll walk you through it. Thanks for providing the benchmark code. Could you simplify it by only including the end-to-end calculations with timings? The script does not have to provide the speedup, just the run time. Then one can simply switch between branches, re-run the script, and see the timings for the actual branch code.

The speedup for impact_at_reg looks impressive, but the speedup for the end-to-end points_to_raster is significantly lower than the isolated apply_box. I guess this is because the "boxing algorithm" is not the actual bottleneck of the function?

@napattan

Copy link
Copy Markdown
Author

Thank you @peanutfun I have simplified the script in PR so it only runs the end-to-end Impact.impact_at_reg and points_to_raster calls and prints their run times on the active branch.

And your mentioning about "boxing algorithm" is correct. When profiling the function step-by-step on 20,000 points (res=0.05):

  • On develop (~1,001 ms total), the row-wise apply_box step takes ~510 ms (~51% of the total time), while rasterio.features.rasterize(...) takes ~460 ms (~46%) and df_poly.to_crs(...) takes ~20 ms.
  • Replacing df.apply with shapely.box drops the boxing step from ~510 ms to ~7 ms, which cuts the end-to-end runtime roughly in half (~1,001 ms -> ~484 ms), leaving rasterio.features.rasterize as the actual bottleneck of the function.

Thank you again.

@peanutfun

Copy link
Copy Markdown
Member

@napattan Great, thanks for simplifying the script. I can confirm a speedup of around 8x for Impact.impact_at_reg and 2x for points_to_raster on my computer. Tests are passing, so we are ready to merge. Thanks again!

@peanutfun
peanutfun merged commit a1f1440 into CLIMADA-project:develop Nov 16, 2026
7 checks passed
emanuel-schmid added a commit that referenced this pull request Nov 19, 2026
napattan added a commit to napattan/climada_python that referenced this pull request Nov 23, 2026
* re-apply CLIMADA-project#1350 vectorizations for Impact.impact_at_reg and points_to_raster
* enforce strict 1D exact-length agg_regions check matching docstring (CLIMADA-project#1357)
* update climada/test/test_util_calibrate.py for 3-point exposure fixture
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants