Skip to content

Vectorize lorenz_curve and gini - #702

Closed
Smit-create wants to merge 1 commit into
QuantEcon:mainfrom
Smit-create:opt
Closed

Smit-create wants to merge 1 commit into
QuantEcon:mainfrom
Smit-create:opt

Conversation

@Smit-create

@Smit-create Smit-create commented Apr 19, 2023 •

Copy link
Copy Markdown
Member
  • Replaced the python loops with vectorized code for enhancing the performance in lorenz_curve and gini_coefficient.

@coveralls

coveralls commented Apr 19, 2023 •

Copy link
Copy Markdown

Coverage Status

Coverage: 92.988% (+0.01%) from 92.975% when pulling c448868 on Smit-create:opt into eeb0865 on QuantEcon:main.

@Smit-create
Smit-create requested review from jstac, mmcky and oyamad April 20, 2023 06:23

@oyamad oyamad 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.

Maybe add tests?

@Smit-create

Copy link
Copy Markdown
Member Author

@oyamad

oyamad commented Apr 23, 2023

Copy link
Copy Markdown
Member

Is this adding new features or refactoring the code?

@Smit-create

Copy link
Copy Markdown
Member Author

This is just refactoring the code and removing some for loops for performance optimizations.

@oyamad

oyamad commented Apr 24, 2023

Copy link
Copy Markdown
Member

@Smit-create It is usually advised to use for loops (and avoid creation of intermediate arrays) in njited functions. Do you have a reason to go against that in this case?

@Smit-create

Copy link
Copy Markdown
Member Author

It is usually advised to use for loops (and avoid creation of intermediate arrays) in njited functions.

I found this better in terms of time performance as this is vectorized version while the extra space complexity (creating new arrays) is still the same for both the functions -- O(n)

@mmcky

mmcky commented Apr 27, 2023

Copy link
Copy Markdown
Contributor

@Smit-create thanks for opening this PR.

Would you mind to update the top level comment box with a description of the change and document the performance improvements you mention in this thread so it's clear what this change is about.

@Smit-create

Copy link
Copy Markdown
Member Author

Thanks @mmcky. Done

@mmcky

mmcky commented Oct 24, 2023

Copy link
Copy Markdown
Contributor

@Smit-create I haven't merged this as it isn't clear what level of performance improvement is being made. Is it 2% or 20% for example, it would be helpful to have timings between the different versions to make an assessment here. @oyamad makes a good point around njit so we need a clear reason to change to vectorized code.

@mmcky
mmcky requested a review from Copilot August 16, 2025 01:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR vectorizes the lorenz_curve and gini_coefficient functions to improve performance by replacing Python loops with NumPy vectorized operations. The changes eliminate explicit iteration in favor of array operations that can be optimized by NumPy's underlying C implementations.

Key changes:

  • Replace manual loop-based cumulative calculations in lorenz_curve with vectorized NumPy operations
  • Optimize gini_coefficient by reducing nested loops and using vectorized absolute difference calculations
  • Remove trailing whitespace

You can also share your feedback on Copilot code review for a chance to win a $100 gift card. Take the survey.

Comment thread quantecon/_inequality.py
"""

n = len(y)
n = y.shape[0]

Copilot AI Aug 16, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] Using y.shape[0] instead of len(y) is inconsistent with the pattern used elsewhere in the function (line 76 still uses len(y)). Consider keeping len(y) for consistency, as it works for both arrays and lists.

Suggested change
n = y.shape[0]
n = len(y)

Copilot uses AI. Check for mistakes.
Comment thread quantecon/_inequality.py
i_sum[i] += abs(y[i] - y[j])
return np.sum(i_sum) / (2 * n * np.sum(y))
i_sum += np.sum(np.abs(y[i] - y))
t_sum += y[i]

Copilot AI Aug 16, 2025

Copy link

Choose a reason for hiding this comment

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

This vectorization still contains a loop over i and computes np.abs(y[i] - y) for each element, which may not provide the expected performance improvement. Consider fully vectorizing using broadcasting: np.sum(np.abs(y[:, np.newaxis] - y[np.newaxis, :])) to eliminate the loop entirely.

Copilot uses AI. Check for mistakes.
@mmcky

mmcky commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Thanks for this @Smit-create, and apologies that it sat open for so long.

I've now benchmarked both branches to settle the question I raised above about the size of the performance improvement. The short version: the change is performance-neutral for lorenz_curve and a consistent regression for gini_coefficient, so I'm closing it. @oyamad's point about preferring for loops inside njited functions turns out to be right in this case.

Setup: numba 0.62.1, numpy 2.3.5, 10 cores, best-of-5 timings taken after JIT warm-up, Pareto(3) inputs. I ran the whole suite twice and the numbers below reproduced.

lorenz_curve — no measurable difference

n main this PR speedup
1,000 0.012 ms 0.011 ms 1.04x
10,000 0.531 ms 0.519 ms 1.02x
100,000 6.94 ms 6.96 ms 1.00x
1,000,000 86.3 ms 87.5 ms 0.99x

That spread is measurement noise. Both versions are O(n log n) dominated by the np.sort call, and the loop removed here is a trivial O(n) pass that numba already compiles to equivalent machine code. The change from len(y) to y.shape[0] also narrows the input types the function accepts, for no gain.

gini_coefficient — roughly 15% slower

n main this PR this PR vs main
1,000 0.235 ms 0.237 ms 0.99x
5,000 3.83 ms 4.54 ms 0.84x
10,000 13.8 ms 16.4 ms 0.84x
50,000 283 ms 325 ms 0.87x
100,000 1155 ms 1356 ms 0.85x

The cause is that np.sum(np.abs(y[i] - y)) allocates an n-element temporary array on every prange iteration, so the function performs n allocations of n elements each and the extra memory traffic outweighs what the vectorization buys back. The algorithm remains O(n²) either way, so this only moves the constant factor, and it moves it in the wrong direction.

Where the real win is

Gini has an O(n log n) closed form on sorted data, which is an algorithmic improvement rather than a constant-factor one:

n main (10-core parallel) O(n log n) (single-threaded) speedup
1,000 0.235 ms 0.0097 ms 24x
5,000 3.83 ms 0.222 ms 17x
10,000 13.8 ms 0.534 ms 26x
50,000 283 ms 3.29 ms 86x
100,000 1155 ms 6.89 ms 168x

The gap widens with n, and the sorted version beats the 10-core parallel implementation while running on a single thread. It agrees with the current implementation to 1e-9 on random Pareto data at all five sizes, and it satisfies the existing test_gini_coeff assertions for both Pareto and Weibull across every a in the 2–14 range that test samples from.

It also removes the library's only @njit(parallel=True), which is the browser blocker described in #926. I've updated that issue to make this rewrite the primary fix rather than the Emscripten platform gate it originally proposed.

Closing in favour of that work. Thanks again for the contribution, and for the profiling discussion in this thread — it's what led to identifying the larger win.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants