Python algorithm porter

From sparkeh9/DoclingDotNet · View interactive version

Python algorithm porter is an AI agent skill from the GitHub repository sparkeh9/DoclingDotNet. Strict workflow for porting Python algorithms (numpy, pandas, rtree, dict manipulation) to high-performance, zero-allocation C# equivalents.

How to use this skill

Skill file

`python-algorithm-porter` Skill

Context

When porting algorithms from upstream Python repositories (e.g., docling, docling-core, docling-ibm-models) to the .NET port, direct translation of syntax often leads to poor performance or subtle bugs. Python relies heavily on dynamic typing, implicit broadcasting (numpy), and C-backed native libraries (rtree, bisect). .NET relies on static typing, explicit memory management (Span<T>, Memory<T>), and JIT inlining.

Trigger

Use this skill whenever you are tasked with porting a specific algorithm, mathematical function, or complex data transformation from Python to C#.

Workflow

1. Isolate and Analyze (The Python Baseline)

2. Design the .NET Data Structures

3. Porting Strategies

A. Numpy/Broadcasting -> C# Loops/SIMD

Python:

# Normalize image: (img - mean) / std
img = (img / 255.0 - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]

C# Port:

B. `bisect` (Sorted Intervals) -> C# `List<T>.BinarySearch`

Python:

import bisect
bisect.insort(my_list, new_item)

C# Port:

int index = myList.BinarySearch(newItem);
if (index < 0) index = ~index;
myList.Insert(index, newItem);
C. `rtree` / `libspatialindex` -> C# Spatial Index

Python:

from rtree import index
idx = index.Index()
idx.insert(id, (l, b, r, t))
candidates = idx.intersection((query_l, query_b, query_r, query_t))

C# Port:

D. Pandas DataFrames -> C# LINQ

Python:

df.groupby('label').agg({'confidence': 'mean'})

C# Port:

items.GroupBy(x => x.Label)
     .Select(g => new { Label = g.Key, MeanConfidence = g.Average(x => x.Confidence) });

4. Implementation Rules

  1. No dynamic: Everything must be strictly typed.
  2. Zero Allocations in Loops: Avoid instantiating new objects (e.g., new List<int>()) inside tight inner loops. Reuse buffers.
  3. Explicit Math: Use Math.Max, Math.Min, Math.Abs, and Math.Round(..., MidpointRounding.AwayFromZero) strictly. Python's round() behaves differently (Banker's rounding) than standard expectations; verify the exact rounding semantics required.

5. Validation

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.