⚡️ Speed up function calculate_least_squares_polygon by 88%
          #639
        
          
      
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
📄 88% (0.88x) speedup for
calculate_least_squares_polygonininference/core/workflows/core_steps/transformations/dynamic_zones/v1.py⏱️ Runtime :
70.7 milliseconds→37.7 milliseconds(best of47runs)📝 Explanation and details
The optimized code achieves an 87% speedup through three key improvements:
1. Efficient Distance Calculations
np.linalg.norm(contour - point, axis=1)withnp.sqrt(np.einsum('ij,ij->i', contour - point, contour - point))infind_closest_indexeinsum) avoids intermediate array allocations and is more cache-friendly than broadcasting operations2. Precomputed Index Caching
closest_indicesarrayfind_closest_indexcalls during segment processing3. Optimized Matrix Construction
least_squares_line, replacesnp.vstack([x, np.ones_like(x)]).Twith direct array filling usingnp.empty()and column assignmentones_like,vstack) and transpose operationsTest Case Performance
The optimizations are particularly effective for:
The improvements scale well with input size since they reduce algorithmic complexity from O(n²) redundant distance calculations to O(n) precomputed lookups.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
workflows/unit_tests/core_steps/transformations/test_dynamic_zones.py::test_calculate_least_squares_polygonworkflows/unit_tests/core_steps/transformations/test_dynamic_zones.py::test_calculate_least_squares_polygon_with_midpoint_fraction🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-calculate_least_squares_polygon-mhc04ip1and push.