From ebedd81b30828879c5b2b06d94dfcd6d0619f0cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dennis=20G=C3=B6ries?= Date: Sat, 21 Nov 2026 19:12:34 +0100 Subject: [PATCH 1/2] perf: increase performance, less memory footprint --- src/downsample/_ltd.c | 336 ++++++++++++++------------- src/downsample/_ltob.c | 147 +++++++----- src/downsample/_lttb.c | 153 ++++++------ src/downsample/tests/test_layouts.py | 74 ++++++ 4 files changed, 416 insertions(+), 294 deletions(-) create mode 100644 src/downsample/tests/test_layouts.py diff --git a/src/downsample/_ltd.c b/src/downsample/_ltd.c index ee1b1b7..1f8b9f1 100644 --- a/src/downsample/_ltd.c +++ b/src/downsample/_ltd.c @@ -1,16 +1,27 @@ +#define PY_SSIZE_T_CLEAN #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include -#include - -#define PY_SSIZE_T_CLEAN +#include #include +#include #include #include +#include typedef struct { npy_intp start; // inclusive index in the points array npy_intp end; // exclusive index in the points array + + // Memoized SSE of this bucket together with the exact inputs it was + // computed from. The SSE only depends on the bucket range and on its two + // anchor points, so it is reused as long as none of those changed. The + // cache travels with the bucket when buckets are shifted. + npy_intp key_prev; // index of the previous anchor point + npy_intp key_start; // bucket start at computation time (-1: invalid) + npy_intp key_end; // bucket end at computation time + npy_intp key_next; // index of the next anchor point + double sse; } BucketRange; @@ -19,49 +30,58 @@ static inline double calc_triangle_area(double ax, double ay, double bx, return fabs((ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) * 0.5); } +/* The core algorithm only handles aligned, C-contiguous float64 vectors. */ +static inline int is_contiguous_double_1d(PyArrayObject *arr) { + return PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_DOUBLE && + PyArray_IS_C_CONTIGUOUS(arr) && PyArray_ISALIGNED(arr); +} + /* * Calculates the Sum of Squared Errors (SSE) for a given bucket by fitting a - * linear regression line. It includes the previously selected point (prev_pt) - * and the next anchor point (next_pt) to ensure continuity. + * linear regression line. It includes the previously selected point (prev) + * and the next anchor point (next) to ensure continuity. */ -static double calculate_sse_bucket(const double *points, npy_intp start, - npy_intp end, const double *prev_pt, - const double *next_pt) { - npy_intp bucket_len = end - start; - npy_intp total_points = bucket_len + 2; // Bucket points + prev + next +static inline double calculate_sse_bucket(const double *x, const double *y, + npy_intp start, npy_intp end, + double prev_x, double prev_y, + double next_x, double next_y) { + assert(start >= 0 && start <= end); + + const npy_intp bucket_len = end - start; + const npy_intp total_points = bucket_len + 2; // Bucket + prev + next - double sum_x = prev_pt[0] + next_pt[0]; - double sum_y = prev_pt[1] + next_pt[1]; + double sum_x = prev_x + next_x; + double sum_y = prev_y + next_y; // Accumulate sums for X and Y to find the mean (centroid) for (npy_intp i = start; i < end; i++) { - sum_x += points[i * 2]; - sum_y += points[i * 2 + 1]; + sum_x += x[i]; + sum_y += y[i]; } - double avg_x = sum_x / (double)total_points; - double avg_y = sum_y / (double)total_points; + const double avg_x = sum_x / (double)total_points; + const double avg_y = sum_y / (double)total_points; double numerator = 0.0; double denominator = 0.0; // Calculate variance/covariance for the previous point - double dx = prev_pt[0] - avg_x; - double dy = prev_pt[1] - avg_y; + double dx = prev_x - avg_x; + double dy = prev_y - avg_y; numerator += dx * dy; denominator += dx * dx; // Calculate variance/covariance for all points in the bucket for (npy_intp i = start; i < end; i++) { - dx = points[i * 2] - avg_x; - dy = points[i * 2 + 1] - avg_y; + dx = x[i] - avg_x; + dy = y[i] - avg_y; numerator += dx * dy; denominator += dx * dx; } // Calculate variance/covariance for the next point - dx = next_pt[0] - avg_x; - dy = next_pt[1] - avg_y; + dx = next_x - avg_x; + dy = next_y - avg_y; numerator += dx * dy; denominator += dx * dx; @@ -76,32 +96,20 @@ static double calculate_sse_bucket(const double *points, npy_intp start, b = avg_y - a * avg_x; // y-intercept } - // Calculate the actual Sum of Squared Errors (SSE) against the regression - // line + // Sum of Squared Errors (SSE) of the vertical residuals against the + // regression line, including both anchor points. double sse = 0.0; - // Error of previous point - double err = prev_pt[1] - (a * prev_pt[0] + b); + double err = prev_y - (a * prev_x + b); sse += err * err; - // Iterate through every point inside the current bucket's index range. for (npy_intp i = start; i < end; i++) { - // Calculate the vertical residual (error) between the actual data point - // and our fitted linear regression line equation: y = ax + b. - // - // Memory mapping for the interleaved 'points' array: - // points[i * 2] -> The actual X coordinate - // points[i * 2 + 1] -> The actual Y coordinate - // - // Math breakdown: - // (a * points[i * 2] + b) -> The predicted Y value on the trendline - // err = (Actual Y) - (Predicted Y) - err = points[i * 2 + 1] - (a * points[i * 2] + b); + // err = (Actual Y) - (Predicted Y on the trendline) + err = y[i] - (a * x[i] + b); sse += err * err; } - // Error of next point - err = next_pt[1] - (a * next_pt[0] + b); + err = next_y - (a * next_x + b); sse += err * err; return sse; @@ -111,19 +119,22 @@ static double calculate_sse_bucket(const double *points, npy_intp start, // Core Algorithm // ========================================== -static void run_ltd(const double *points, npy_intp num_points, int threshold, - double *out_x, double *out_y) { - - // Allocate contiguous arrays for buckets and their computed SSE values - BucketRange *buckets = - (BucketRange *)malloc(sizeof(BucketRange) * (threshold + 1)); - double *sse = (double *)malloc(sizeof(double) * threshold); - - // Check for memory allocation failure - if (!buckets || !sse) { - free(buckets); - free(sse); - return; +/* + * Requires `x` and `y` to be C-contiguous float64 arrays of `num_points` + * elements, `out_x` / `out_y` to hold `threshold` elements and `buckets` to + * provide room for `threshold + 1` entries (one scratch slot used while + * splitting). The function cannot fail. + */ +static void run_ltd(const double *x, const double *y, npy_intp num_points, + int threshold, BucketRange *buckets, double *out_x, + double *out_y) { + assert(x != NULL && y != NULL); + assert(out_x != NULL && out_y != NULL && buckets != NULL); + assert(threshold > 2); + assert(num_points > threshold); + + for (int i = 0; i <= threshold; i++) { + buckets[i].key_start = -1; // no cached SSE yet } // The first and last buckets are explicitly fixed to the first and last @@ -132,7 +143,7 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, buckets[0].end = 1; // Distribute the remaining points evenly across the middle buckets - double bucket_size = (double)(num_points - 2) / (threshold - 2); + const double bucket_size = (double)(num_points - 2) / (threshold - 2); for (int i = 0; i < threshold - 2; i++) { buckets[i + 1].start = (npy_intp)floor(i * bucket_size) + 1; buckets[i + 1].end = (npy_intp)floor((i + 1) * bucket_size) + 1; @@ -142,19 +153,34 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, buckets[threshold - 1].end = num_points; // Dynamic optimization iterations to adjust bucket boundaries - int num_iterations = - 10; // Empirically derived: (threshold * 10) / threshold + const int num_iterations = 10; for (int iter = 0; iter < num_iterations; iter++) { - // Step 1. Calculate SSE for all middle buckets + // Step 1. Calculate SSE for all middle buckets. A split / merge only + // touches a handful of buckets, so after the first iteration nearly + // all values are served from the per-bucket cache instead of + // re-scanning every point (identical results, O(n / threshold) work + // per iteration instead of O(n)). for (int i = 1; i < threshold - 1; i++) { - // Anchor points are the last point of previous bucket and first of - // next bucket - const double *prev_pt = &points[(buckets[i - 1].end - 1) * 2]; - const double *next_pt = &points[buckets[i + 1].start * 2]; - - sse[i] = calculate_sse_bucket(points, buckets[i].start, - buckets[i].end, prev_pt, next_pt); + BucketRange *bk = &buckets[i]; + // Anchor points are the last point of previous bucket and first + // of next bucket + const npy_intp prev_idx = buckets[i - 1].end - 1; + const npy_intp next_idx = buckets[i + 1].start; + assert(prev_idx >= 0 && prev_idx < num_points); + assert(next_idx >= 0 && next_idx < num_points); + assert(bk->end <= num_points); + + if (bk->key_start != bk->start || bk->key_end != bk->end || + bk->key_prev != prev_idx || bk->key_next != next_idx) { + bk->sse = calculate_sse_bucket(x, y, bk->start, bk->end, + x[prev_idx], y[prev_idx], + x[next_idx], y[next_idx]); + bk->key_start = bk->start; + bk->key_end = bk->end; + bk->key_prev = prev_idx; + bk->key_next = next_idx; + } } // Step 2. Find the bucket with the highest SSE (must have >1 point to @@ -162,9 +188,9 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, double max_sse = 0.0; int high_idx = -1; for (int i = 1; i < threshold - 1; i++) { - npy_intp b_len = buckets[i].end - buckets[i].start; - if (b_len > 1 && sse[i] > max_sse) { - max_sse = sse[i]; + const npy_intp b_len = buckets[i].end - buckets[i].start; + if (b_len > 1 && buckets[i].sse > max_sse) { + max_sse = buckets[i].sse; high_idx = i; } } @@ -181,7 +207,7 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, if (i == high_idx || (i + 1) == high_idx) continue; - double sum = sse[i] + sse[i + 1]; + const double sum = buckets[i].sse + buckets[i + 1].sse; if (sum < min_sum) { min_sum = sum; low_idx = i; @@ -192,21 +218,26 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, if (low_idx < 0) break; - // Step 4. Split the highest SSE bucket perfectly in half. - npy_intp total_len = buckets[high_idx].end - buckets[high_idx].start; - npy_intp half = (npy_intp)ceil((double)total_len / 2.0); - npy_intp orig_end = buckets[high_idx].end; - - // Shift all buckets to the right to make room for the newly split - // bucket - for (int i = threshold; i > high_idx + 1; i--) { - buckets[i] = buckets[i - 1]; - } + assert(high_idx >= 1 && high_idx <= threshold - 2); + assert(low_idx >= 1 && low_idx <= threshold - 3); - // Assign boundaries for the two newly split halves + // Step 4. Split the highest SSE bucket perfectly in half. + const npy_intp total_len = + buckets[high_idx].end - buckets[high_idx].start; + const npy_intp half = (npy_intp)ceil((double)total_len / 2.0); + const npy_intp orig_end = buckets[high_idx].end; + + // Shift buckets [high_idx + 1, threshold) one slot to the right to + // make room for the newly split bucket (uses the scratch slot). + memmove(&buckets[high_idx + 2], &buckets[high_idx + 1], + sizeof(BucketRange) * (size_t)(threshold - high_idx - 1)); + + // Assign boundaries for the two newly split halves. The cache keys + // no longer match, so both halves are recomputed. buckets[high_idx].end = buckets[high_idx].start + half; buckets[high_idx + 1].start = buckets[high_idx].end; buckets[high_idx + 1].end = orig_end; + buckets[high_idx + 1].key_start = -1; // Step 5. Merge the pair selected before the split. A split to its // left shifted the pair one position to the right. @@ -215,9 +246,8 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, } buckets[low_idx].end = buckets[low_idx + 1].end; - for (int i = low_idx + 1; i < threshold; i++) { - buckets[i] = buckets[i + 1]; - } + memmove(&buckets[low_idx + 1], &buckets[low_idx + 2], + sizeof(BucketRange) * (size_t)(threshold - low_idx - 1)); } // ========================================== @@ -227,8 +257,8 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, // bucket. // Always select the exact first point - out_x[0] = points[0]; - out_y[0] = points[1]; + out_x[0] = x[0]; + out_y[0] = y[0]; double last_x = out_x[0]; double last_y = out_y[0]; @@ -237,14 +267,15 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, for (int i = 1; i < threshold - 1; i++) { // 1. Calculate the average point (centroid) of the *next* bucket - npy_intp next_start = buckets[i + 1].start; - npy_intp next_end = buckets[i + 1].end; - npy_intp next_count = next_end - next_start; + const npy_intp next_start = buckets[i + 1].start; + const npy_intp next_end = buckets[i + 1].end; + const npy_intp next_count = next_end - next_start; + assert(next_start >= 0 && next_end <= num_points); double avg_next_x = 0.0, avg_next_y = 0.0; for (npy_intp k = next_start; k < next_end; k++) { - avg_next_x += points[k * 2]; - avg_next_y += points[k * 2 + 1]; + avg_next_x += x[k]; + avg_next_y += y[k]; } avg_next_x /= (double)next_count; avg_next_y /= (double)next_count; @@ -259,11 +290,8 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, npy_intp best_idx = buckets[i].start - 1; for (npy_intp j = buckets[i].start; j < buckets[i].end; j++) { - double px = points[j * 2]; - double py = points[j * 2 + 1]; - - double area = calc_triangle_area(last_x, last_y, px, py, avg_next_x, - avg_next_y); + const double area = calc_triangle_area(last_x, last_y, x[j], y[j], + avg_next_x, avg_next_y); if (area > max_area) { max_area = area; best_idx = j; @@ -272,26 +300,25 @@ static void run_ltd(const double *points, npy_intp num_points, int threshold, // Store the selected best point and update 'last_x / last_y' for the // next iteration - out_x[i] = points[best_idx * 2]; - out_y[i] = points[best_idx * 2 + 1]; - last_x = out_x[i]; - last_y = out_y[i]; + assert(best_idx >= 0 && best_idx < num_points); + last_x = x[best_idx]; + last_y = y[best_idx]; + out_x[i] = last_x; + out_y[i] = last_y; } // Always select the exact last point - npy_intp last_pt_idx = (num_points - 1) * 2; - out_x[threshold - 1] = points[last_pt_idx]; - out_y[threshold - 1] = points[last_pt_idx + 1]; - - // Clean up allocated heap memory - free(buckets); - free(sse); + out_x[threshold - 1] = x[num_points - 1]; + out_y[threshold - 1] = y[num_points - 1]; } static PyObject *largest_triangle_dynamic(PyObject *self, PyObject *args) { PyObject *x_obj, *y_obj; PyArrayObject *x = NULL, *y = NULL; + PyObject *out_x_arr = NULL, *out_y_arr = NULL; + BucketRange *buckets = NULL; + PyObject *result = NULL; int threshold; // Parse arguments: (Object, Object, Integer) @@ -305,94 +332,77 @@ static PyObject *largest_triangle_dynamic(PyObject *self, PyObject *args) { return NULL; } - // Convert input objects to contiguous C-aligned double arrays (NPY_DOUBLE) - // NPY_ARRAY_IN_ARRAY ensures we get read-only, well-behaved contiguous - // memory + // Convert input objects to aligned, C-contiguous float64 arrays. This is + // a no-op (no copy) for input that already has that layout. x = (PyArrayObject *)PyArray_FROM_OTF(x_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); - y = (PyArrayObject *)PyArray_FROM_OTF(y_obj, NPY_DOUBLE, - NPY_ARRAY_IN_ARRAY); + y = x ? (PyArrayObject *)PyArray_FROM_OTF(y_obj, NPY_DOUBLE, + NPY_ARRAY_IN_ARRAY) + : NULL; // Check if conversion failed if (!x || !y) - goto fail; + goto done; // Ensure they are 1-Dimensional and equal length if (PyArray_NDIM(x) != 1 || PyArray_NDIM(y) != 1 || !PyArray_SAMESHAPE(x, y)) { PyErr_SetString(PyExc_ValueError, "x and y must be 1D with identical shape."); - goto fail; + goto done; } - npy_intp len_points = PyArray_DIM(x, 0); + const npy_intp len_points = PyArray_DIM(x, 0); // If the data is already smaller than the threshold, just return the data // untouched if (threshold >= len_points) { - PyObject *result = PyTuple_Pack(2, x, y); - Py_DECREF(x); - Py_DECREF(y); - return result; + result = PyTuple_Pack(2, x, y); + goto done; } - // Allocate memory for interleaved points [x1, y1, x2, y2, ...] - // We interleave to maximize CPU cache locality during the math-heavy worker - // phase - npy_intp points_dims[2] = {len_points, 2}; - PyArrayObject *points = - (PyArrayObject *)PyArray_SimpleNew(2, points_dims, NPY_DOUBLE); - - if (!points) - goto fail; - - double *points_data = (double *)PyArray_DATA(points); - double *x_raw = (double *)PyArray_DATA(x); - double *y_raw = (double *)PyArray_DATA(y); - - // Perform the interleaving copy - for (npy_intp i = 0; i < len_points; i++) { - points_data[i * 2] = x_raw[i]; - points_data[i * 2 + 1] = y_raw[i]; - } - - // Allocate the output arrays + // Allocate the (uninitialized, fully overwritten) output arrays npy_intp out_dim = threshold; - PyObject *out_x_arr = PyArray_ZEROS(1, &out_dim, NPY_DOUBLE, 0); - PyObject *out_y_arr = PyArray_ZEROS(1, &out_dim, NPY_DOUBLE, 0); - - if (!out_x_arr || !out_y_arr) { - Py_XDECREF(out_x_arr); - Py_XDECREF(out_y_arr); - Py_DECREF(points); - goto fail; + out_x_arr = PyArray_SimpleNew(1, &out_dim, NPY_DOUBLE); + out_y_arr = PyArray_SimpleNew(1, &out_dim, NPY_DOUBLE); + if (!out_x_arr || !out_y_arr) + goto done; + + // Bucket work space (+1 scratch slot for splitting). Allocated while + // holding the GIL so a failure raises a proper MemoryError instead of + // silently returning garbage. + buckets = (BucketRange *)PyMem_Malloc(sizeof(BucketRange) * + ((size_t)threshold + 1)); + if (!buckets) { + PyErr_NoMemory(); + goto done; } - // Get raw C pointers to the newly allocated output arrays + // The core only deals with contiguous memory + assert(is_contiguous_double_1d(x)); + assert(is_contiguous_double_1d(y)); + assert(is_contiguous_double_1d((PyArrayObject *)out_x_arr)); + assert(is_contiguous_double_1d((PyArrayObject *)out_y_arr)); + + const double *x_raw = (const double *)PyArray_DATA(x); + const double *y_raw = (const double *)PyArray_DATA(y); double *out_x = (double *)PyArray_DATA((PyArrayObject *)out_x_arr); double *out_y = (double *)PyArray_DATA((PyArrayObject *)out_y_arr); - Py_BEGIN_ALLOW_THREADS - - run_ltd(points_data, len_points, threshold, out_x, out_y); - - Py_END_ALLOW_THREADS - - Py_DECREF(points); - Py_DECREF(x); - Py_DECREF(y); + Py_BEGIN_ALLOW_THREADS; + run_ltd(x_raw, y_raw, len_points, threshold, buckets, out_x, out_y); + Py_END_ALLOW_THREADS; // Pack the output X and Y arrays into a Python tuple and return it - PyObject *result = PyTuple_Pack(2, out_x_arr, out_y_arr); - Py_DECREF(out_x_arr); - Py_DECREF(out_y_arr); - - return result; + result = PyTuple_Pack(2, out_x_arr, out_y_arr); -fail: +done: + PyMem_Free(buckets); Py_XDECREF(x); Py_XDECREF(y); - return NULL; + Py_XDECREF(out_x_arr); + Py_XDECREF(out_y_arr); + return result; } // ========================================== diff --git a/src/downsample/_ltob.c b/src/downsample/_ltob.c index f856f25..6e2e6d2 100644 --- a/src/downsample/_ltob.c +++ b/src/downsample/_ltob.c @@ -1,19 +1,36 @@ +#define PY_SSIZE_T_CLEAN #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include +#include #include #include + static inline double calc_triangle_area(double ax, double ay, double bx, double by, double cx, double cy) { return fabs((ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) * 0.5); } +/* The core algorithm only handles aligned, C-contiguous float64 vectors. */ +static inline int is_contiguous_double_1d(PyArrayObject *arr) { + return PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_DOUBLE && + PyArray_IS_C_CONTIGUOUS(arr) && PyArray_ISALIGNED(arr); +} + // ========================================== // Core LTOB // ========================================== +/* + * Requires `x` and `y` to be C-contiguous float64 arrays of `len_points` + * elements and `result_x` / `result_y` to hold `threshold` elements. + */ static void run_ltob(const double *x, const double *y, npy_intp len_points, int threshold, double *result_x, double *result_y) { + assert(x != NULL && y != NULL); + assert(result_x != NULL && result_y != NULL); + assert(threshold > 2); + assert(len_points > threshold); // Always add the first point (handling NaNs/Infs using standard C math) result_x[0] = isfinite(x[0]) ? x[0] : 0.0; @@ -28,47 +45,61 @@ static void run_ltob(const double *x, const double *y, npy_intp len_points, // Main loop for the inner buckets for (npy_intp i = 1; i < threshold - 1; i++) { - npy_intp start_index = (npy_intp)floor(i * bucket_size); - npy_intp end_index = - (npy_intp)fmin(len_points - 1, (i + 1) * bucket_size); + const npy_intp start_index = (npy_intp)floor(i * bucket_size); + const npy_intp end_index = + (npy_intp)fmin((double)(len_points - 1), (i + 1) * bucket_size); double max_area = -1.0; npy_intp max_area_index = start_index; - // Find the point in this bucket that forms the largest triangle - // with its immediate neighbors (j-1 and j+1) - for (npy_intp j = start_index; j < end_index; j++) { + // bucket_size > 1 (len_points > threshold), so start_index >= 1, and + // end_index is capped at len_points - 1: both neighbours j - 1 and + // j + 1 are always in bounds and no per-point clamping is needed. + assert(start_index >= 1 && start_index < len_points); + assert(end_index <= len_points - 1); - // Boundary safety: ensure j-1 and j+1 don't read out of bounds - npy_intp prev_idx = (j - 1 >= 0) ? j - 1 : 0; - npy_intp next_idx = (j + 1 < len_points) ? j + 1 : len_points - 1; + // Slide a three-point window (prev, cur, next) over the bucket so + // only one new point is loaded per step. + double px = x[start_index - 1]; + double py = y[start_index - 1]; + double cx = x[start_index]; + double cy = y[start_index]; - double area = calc_triangle_area(x[prev_idx], y[prev_idx], x[j], - y[j], x[next_idx], y[next_idx]); + for (npy_intp j = start_index; j < end_index; j++) { + const double nx = x[j + 1]; + const double ny = y[j + 1]; - // Ensure we don't let Inf/NaN areas overtake the bucket logic + double area = calc_triangle_area(px, py, cx, cy, nx, ny); + // Inf/NaN areas never overtake the bucket logic if (area > max_area) { max_area = area; max_area_index = j; } + px = cx; + py = cy; + cx = nx; + cy = ny; } // Save the best point for this bucket. // If the area was unresolvable or the point itself is not finite, // fallback to 0.0 to satisfy test_inf(), test_nan(), and // test_single_inf() expectations. - if (max_area == -1.0 || !isfinite(x[max_area_index]) || - !isfinite(y[max_area_index])) { - result_x[i] = 0.0; - result_y[i] = 0.0; - } else { - result_x[i] = x[max_area_index]; - result_y[i] = y[max_area_index]; + result_x[i] = 0.0; + result_y[i] = 0.0; + if (max_area != -1.0) { + assert(max_area_index >= 0 && max_area_index < len_points); + const double bx = x[max_area_index]; + const double by = y[max_area_index]; + if (isfinite(bx) && isfinite(by)) { + result_x[i] = bx; + result_y[i] = by; + } } } // Always add the last point (handling potential NaNs/Infs) - npy_intp last_idx = len_points - 1; + const npy_intp last_idx = len_points - 1; result_x[threshold - 1] = isfinite(x[last_idx]) ? x[last_idx] : 0.0; result_y[threshold - 1] = isfinite(y[last_idx]) ? y[last_idx] : 0.0; } @@ -76,6 +107,8 @@ static void run_ltob(const double *x, const double *y, npy_intp len_points, static PyObject *largest_triangle_one_bucket(PyObject *self, PyObject *args) { PyObject *x_obj, *y_obj; PyArrayObject *x_array = NULL, *y_array = NULL; + PyObject *npx_obj = NULL, *npy_obj = NULL; + PyObject *result = NULL; int threshold; // Parse input arguments @@ -94,80 +127,70 @@ static PyObject *largest_triangle_one_bucket(PyObject *self, PyObject *args) { return NULL; } - // Safely convert inputs + // Convert inputs to aligned, C-contiguous float64 arrays. This is a + // no-op (no copy) for input that already has that layout. x_array = (PyArrayObject *)PyArray_FROM_OTF(x_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); - y_array = (PyArrayObject *)PyArray_FROM_OTF(y_obj, NPY_DOUBLE, - NPY_ARRAY_IN_ARRAY); + y_array = x_array ? (PyArrayObject *)PyArray_FROM_OTF( + y_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY) + : NULL; if (!x_array || !y_array) - goto fail; + goto done; // Validation if (PyArray_NDIM(x_array) != 1 || PyArray_NDIM(y_array) != 1) { PyErr_SetString(PyExc_ValueError, "x and y must be 1-dimensional."); - goto fail; + goto done; } if (!PyArray_SAMESHAPE(x_array, y_array)) { PyErr_SetString(PyExc_ValueError, "x and y must have the same shape."); - goto fail; + goto done; } - npy_intp len_points = PyArray_DIM(x_array, 0); + const npy_intp len_points = PyArray_DIM(x_array, 0); // If threshold is greater than or equal to data size, return arrays // unchanged if (threshold >= len_points || len_points <= 2) { - PyObject *result = PyTuple_Pack(2, x_array, y_array); - Py_DECREF(x_array); - Py_DECREF(y_array); - return result; + result = PyTuple_Pack(2, x_array, y_array); + goto done; } - // Extract raw pointers to the input data - const double *x = (double *)PyArray_DATA(x_array); - const double *y = (double *)PyArray_DATA(y_array); - - // Allocate memory for the output arrays using NumPy's safe allocator + // Allocate the (uninitialized, fully overwritten) output arrays npy_intp dims[1] = {threshold}; - PyObject *npx_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE); - PyObject *npy_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE); - + npx_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE); + npy_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE); if (!npx_obj || !npy_obj) { - Py_XDECREF(npx_obj); - Py_XDECREF(npy_obj); - goto fail; + goto done; } - // Extract raw pointers to the output arrays + // The core only deals with contiguous memory + assert(is_contiguous_double_1d(x_array)); + assert(is_contiguous_double_1d(y_array)); + assert(is_contiguous_double_1d((PyArrayObject *)npx_obj)); + assert(is_contiguous_double_1d((PyArrayObject *)npy_obj)); + + const double *x = (const double *)PyArray_DATA(x_array); + const double *y = (const double *)PyArray_DATA(y_array); double *result_x = (double *)PyArray_DATA((PyArrayObject *)npx_obj); double *result_y = (double *)PyArray_DATA((PyArrayObject *)npy_obj); // ========================================== // Release the GIL and do the heavy lifting // ========================================== - Py_BEGIN_ALLOW_THREADS - - run_ltob(x, y, len_points, threshold, result_x, result_y); - - Py_END_ALLOW_THREADS - // ========================================== + Py_BEGIN_ALLOW_THREADS; + run_ltob(x, y, len_points, threshold, result_x, result_y); + Py_END_ALLOW_THREADS; - // Pack the newly filled arrays into a tuple - PyObject *result = PyTuple_Pack(2, npx_obj, npy_obj); + // Pack the newly filled arrays into a tuple + result = PyTuple_Pack(2, npx_obj, npy_obj); - // Clean up our local references - Py_DECREF(x_array); - Py_DECREF(y_array); - Py_DECREF(npx_obj); - Py_DECREF(npy_obj); - - return result; - -fail: - // Jump target for memory cleanup on failure +done: Py_XDECREF(x_array); Py_XDECREF(y_array); - return NULL; + Py_XDECREF(npx_obj); + Py_XDECREF(npy_obj); + return result; } // ========================================== diff --git a/src/downsample/_lttb.c b/src/downsample/_lttb.c index a27ef2d..e074bc5 100644 --- a/src/downsample/_lttb.c +++ b/src/downsample/_lttb.c @@ -1,5 +1,7 @@ +#define PY_SSIZE_T_CLEAN #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include +#include #include #include #include @@ -10,12 +12,26 @@ static inline double calc_triangle_area(double ax, double ay, double bx, return fabs((ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) * 0.5); } +/* The core algorithm only handles aligned, C-contiguous float64 vectors. */ +static inline int is_contiguous_double_1d(PyArrayObject *arr) { + return PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_DOUBLE && + PyArray_IS_C_CONTIGUOUS(arr) && PyArray_ISALIGNED(arr); +} + // ========================================== // Core Algorithm // ========================================== +/* + * Requires `x` and `y` to be C-contiguous float64 arrays of `len_points` + * elements and `result_x` / `result_y` to hold `threshold` elements. + */ static void run_lttb(const double *x, const double *y, npy_intp len_points, int threshold, double *result_x, double *result_y) { + assert(x != NULL && y != NULL); + assert(result_x != NULL && result_y != NULL); + assert(threshold > 2); + assert(len_points > threshold); // Bucket size calculation. (Total points - 2 margins) / (Buckets - 2 // margins) @@ -26,68 +42,72 @@ static void run_lttb(const double *x, const double *y, npy_intp len_points, result_y[0] = npy_isfinite(y[0]) ? y[0] : 0.0; npy_intp a = 0; // Index of the selected point from the previous bucket - npy_intp next_a = 0; + + // Boundaries of the *current* bucket. The end of the current bucket is + // identical to the start of the next (averaging) bucket, so each + // boundary is computed only once and carried over to the next iteration. + npy_intp range_start = (npy_intp)(floor((npy_intp)0 * every) + 1); + npy_intp range_end = (npy_intp)(floor((npy_intp)1 * every) + 1); for (npy_intp i = 0; i < threshold - 2; ++i) { // 1. Calculate the average point (centroid) of the *next* bucket - double avg_x = 0.0; - double avg_y = 0.0; - - npy_intp avg_start = (npy_intp)(floor((i + 1) * every) + 1); - npy_intp avg_end = (npy_intp)(floor((i + 2) * every) + 1); + const npy_intp avg_start = range_end; + const npy_intp next_range_end = + (npy_intp)(floor((i + 2) * every) + 1); + npy_intp avg_end = next_range_end; if (avg_end >= len_points) { avg_end = len_points; } - npy_intp avg_length = avg_end - avg_start; - + double avg_x = 0.0; + double avg_y = 0.0; for (npy_intp j = avg_start; j < avg_end; j++) { avg_x += x[j]; avg_y += y[j]; } - // Multiply by inverse instead of dividing (faster on most CPU - // architectures) - double inv_length = 1.0 / (double)avg_length; + // Multiply by inverse instead of dividing + const double inv_length = 1.0 / (double)(avg_end - avg_start); avg_x *= inv_length; avg_y *= inv_length; - // 2. Determine the boundaries of the *current* bucket - npy_intp range_start = (npy_intp)(floor((i + 0) * every) + 1); - npy_intp range_end = (npy_intp)(floor((i + 1) * every) + 1); + // 2. Find the point in the current bucket that forms the largest + // triangle with the previous anchor and the next bucket's centroid. + assert(range_start >= 1 && range_end <= len_points); + const double ax = x[a]; + const double ay = y[a]; double max_area = -1.0; - double max_area_point_x = 0.0; - double max_area_point_y = 0.0; + npy_intp best = -1; - // Anchor point (from previous iteration) - double ax = x[a]; - double ay = y[a]; - - // 3. Find the point in the current bucket that forms the largest - // triangle for (npy_intp k = range_start; k < range_end; k++) { double area = calc_triangle_area(ax, ay, x[k], y[k], avg_x, avg_y); if (area > max_area) { max_area = area; - max_area_point_x = x[k]; - max_area_point_y = y[k]; - next_a = k; // Save index to use as anchor for the next bucket + best = k; } } - // Store the selected point - result_x[i + 1] = max_area_point_x; - result_y[i + 1] = max_area_point_y; + // 3. Store the selected point. If no area was comparable (NaN), the + // point is reported as 0.0 and the anchor stays unchanged. + if (best >= 0) { + result_x[i + 1] = x[best]; + result_y[i + 1] = y[best]; + a = best; + } else { + result_x[i + 1] = 0.0; + result_y[i + 1] = 0.0; + } - // Update anchor index for the next bucket - a = next_a; + // Advance to the next bucket + range_start = avg_start; + range_end = next_range_end; } // Always add the last point (handling potential NaNs/Infs) - npy_intp last_idx = len_points - 1; + const npy_intp last_idx = len_points - 1; result_x[threshold - 1] = npy_isfinite(x[last_idx]) ? x[last_idx] : 0.0; result_y[threshold - 1] = npy_isfinite(y[last_idx]) ? y[last_idx] : 0.0; } @@ -96,6 +116,8 @@ static PyObject *largest_triangle_three_buckets(PyObject *self, PyObject *args) { PyObject *x_obj, *y_obj; PyArrayObject *x_array = NULL, *y_array = NULL; + PyObject *npx_obj = NULL, *npy_obj = NULL; + PyObject *result = NULL; int threshold; // Parse input arguments @@ -115,76 +137,69 @@ static PyObject *largest_triangle_three_buckets(PyObject *self, return NULL; } - // Convert inputs to continuous memory C-arrays safely + // Convert inputs to aligned, C-contiguous float64 arrays. This is a + // no-op (no copy) for input that already has that layout. x_array = (PyArrayObject *)PyArray_FROM_OTF(x_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); - y_array = (PyArrayObject *)PyArray_FROM_OTF(y_obj, NPY_DOUBLE, - NPY_ARRAY_IN_ARRAY); + y_array = x_array ? (PyArrayObject *)PyArray_FROM_OTF( + y_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY) + : NULL; if (!x_array || !y_array) { PyErr_SetString(PyExc_ValueError, "Failed to convert inputs to NumPy arrays."); - goto fail; + goto done; } // Validation if (PyArray_NDIM(x_array) != 1 || PyArray_NDIM(y_array) != 1) { PyErr_SetString(PyExc_ValueError, "x and y must be 1-dimensional."); - goto fail; + goto done; } if (!PyArray_SAMESHAPE(x_array, y_array)) { PyErr_SetString(PyExc_ValueError, "x and y must have the same shape."); - goto fail; + goto done; } - npy_intp len_points = PyArray_DIM(x_array, 0); + const npy_intp len_points = PyArray_DIM(x_array, 0); // If threshold exceeds the number of points, just return original data if (threshold >= len_points || len_points <= 2) { - PyObject *result = PyTuple_Pack(2, x_array, y_array); - Py_DECREF(x_array); - Py_DECREF(y_array); - return result; + result = PyTuple_Pack(2, x_array, y_array); + goto done; } - // Extract raw pointers from the input arrays - const double *x = (double *)PyArray_DATA(x_array); - const double *y = (double *)PyArray_DATA(y_array); - - // Allocate memory for the output array directly through NumPy + // Allocate the (uninitialized, fully overwritten) output arrays npy_intp dims[1] = {threshold}; - PyObject *npx_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE); - PyObject *npy_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE); - + npx_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE); + npy_obj = PyArray_SimpleNew(1, dims, NPY_DOUBLE); if (!npx_obj || !npy_obj) { - Py_XDECREF(npx_obj); - Py_XDECREF(npy_obj); - goto fail; + goto done; } - // Extract raw pointers to the output arrays + // The core only deals with contiguous memory + assert(is_contiguous_double_1d(x_array)); + assert(is_contiguous_double_1d(y_array)); + assert(is_contiguous_double_1d((PyArrayObject *)npx_obj)); + assert(is_contiguous_double_1d((PyArrayObject *)npy_obj)); + + const double *x = (const double *)PyArray_DATA(x_array); + const double *y = (const double *)PyArray_DATA(y_array); double *result_x = (double *)PyArray_DATA((PyArrayObject *)npx_obj); double *result_y = (double *)PyArray_DATA((PyArrayObject *)npy_obj); - Py_BEGIN_ALLOW_THREADS - - run_lttb(x, y, len_points, threshold, result_x, result_y); - - Py_END_ALLOW_THREADS - - Py_DECREF(x_array); - - Py_DECREF(y_array); + Py_BEGIN_ALLOW_THREADS; + run_lttb(x, y, len_points, threshold, result_x, result_y); + Py_END_ALLOW_THREADS; // Pack the results and return them - PyObject *result = PyTuple_Pack(2, npx_obj, npy_obj); - Py_DECREF(npx_obj); - Py_DECREF(npy_obj); - return result; + result = PyTuple_Pack(2, npx_obj, npy_obj); -fail: +done: Py_XDECREF(x_array); Py_XDECREF(y_array); - return NULL; + Py_XDECREF(npx_obj); + Py_XDECREF(npy_obj); + return result; } // ========================================== diff --git a/src/downsample/tests/test_layouts.py b/src/downsample/tests/test_layouts.py new file mode 100644 index 0000000..5e940c7 --- /dev/null +++ b/src/downsample/tests/test_layouts.py @@ -0,0 +1,74 @@ +import numpy as np +import pytest + +import downsample + +ALGORITHMS = [downsample.ltd, downsample.ltob, downsample.lttb] + + +def _data(n=5000, seed=0): + rng = np.random.default_rng(seed) + x = np.arange(n, dtype=np.float64) + y = np.cumsum(rng.normal(size=n)) + return x, y + + +@pytest.mark.parametrize("func", ALGORITHMS) +@pytest.mark.parametrize("threshold", [3, 10, 500, 4999]) +def test_strided_views_match_contiguous(func, threshold): + """Non-contiguous float64 views are converted to contiguous memory and + give identical results to their contiguous copies""" + x, y = _data() + expected_x, expected_y = func(x, y, threshold) + + interleaved = np.stack([x, y], axis=1) + layouts = { + "column views": (interleaved[:, 0], interleaved[:, 1]), + "step slices": (np.repeat(x, 3)[::3], np.repeat(y, 2)[::2]), + "reversed views": (x[::-1].copy()[::-1], y[::-1].copy()[::-1]), + "fortran columns": (np.asfortranarray(interleaved)[:, 0], + np.asfortranarray(interleaved)[:, 1]), + } + for name, (vx, vy) in layouts.items(): + nx, ny = func(vx, vy, threshold) + np.testing.assert_array_equal(nx, expected_x, err_msg=name) + np.testing.assert_array_equal(ny, expected_y, err_msg=name) + + +@pytest.mark.parametrize("func", ALGORITHMS) +def test_strided_input_not_modified(func): + """The input views must never be written to""" + x, y = _data() + interleaved = np.stack([x, y], axis=1) + interleaved.setflags(write=False) + snapshot = interleaved.copy() + func(interleaved[:, 0], interleaved[:, 1], 100) + np.testing.assert_array_equal(interleaved, snapshot) + + +@pytest.mark.parametrize("func", ALGORITHMS) +def test_broadcast_input(func): + """Zero-stride (broadcast) input is converted and handled""" + x, _ = _data() + y = np.broadcast_to(np.float64(2.5), x.shape) + nx, ny = func(x, y, 100) + assert nx.shape == ny.shape == (100,) + np.testing.assert_array_equal(ny, np.full(100, 2.5)) + + +@pytest.mark.parametrize("func", ALGORITHMS) +def test_unaligned_and_byteswapped_input(func): + """Unaligned and non-native byte order input is converted safely""" + x, y = _data() + expected_x, expected_y = func(x, y, 100) + + buf = np.zeros(x.size * 8 + 1, dtype=np.uint8) + unaligned = np.ndarray(x.shape, np.float64, buf, 1) + unaligned[:] = y + assert not unaligned.flags.aligned + nx, ny = func(x, unaligned, 100) + np.testing.assert_array_equal(ny, expected_y) + + nx, ny = func(x.astype(">f8"), y.astype(">f8"), 100) + np.testing.assert_array_equal(nx, expected_x) + np.testing.assert_array_equal(ny, expected_y) From 837c442c97a613d1e4586ab9453ebdce2bf9d1d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dennis=20G=C3=B6ries?= Date: Mon, 23 Nov 2026 23:14:52 +0100 Subject: [PATCH 2/2] more comments and tests --- src/downsample/__init__.py | 4 +- src/downsample/_ltd.c | 153 +++++++++++++++-------- src/downsample/_ltob.c | 62 +++++---- src/downsample/_lttb.c | 65 ++++++---- src/downsample/tests/test_ltd.py | 24 +++- src/downsample/tests/test_ltob.py | 24 +++- src/downsample/tests/test_memory_leak.py | 4 +- 7 files changed, 231 insertions(+), 105 deletions(-) diff --git a/src/downsample/__init__.py b/src/downsample/__init__.py index d7e0fdd..3232cec 100644 --- a/src/downsample/__init__.py +++ b/src/downsample/__init__.py @@ -11,10 +11,10 @@ def ltd(x: np.ndarray, y: np.ndarray, threshold: int): def ltob(x: np.ndarray, y: np.ndarray, threshold: int): - """Apply the largest triangle one buckets algorithm""" + """Apply the largest triangle one bucket algorithm""" return largest_triangle_one_bucket(x, y, threshold) def lttb(x: np.ndarray, y: np.ndarray, threshold: int): - """Apply the largest triangle one buckets algorithm""" + """Apply the largest triangle three buckets algorithm""" return largest_triangle_three_buckets(x, y, threshold) diff --git a/src/downsample/_ltd.c b/src/downsample/_ltd.c index 1f8b9f1..bc4c229 100644 --- a/src/downsample/_ltd.c +++ b/src/downsample/_ltd.c @@ -10,13 +10,15 @@ typedef struct { - npy_intp start; // inclusive index in the points array - npy_intp end; // exclusive index in the points array + npy_intp start; // inclusive index in the input arrays + npy_intp end; // exclusive index in the input arrays // Memoized SSE of this bucket together with the exact inputs it was - // computed from. The SSE only depends on the bucket range and on its two - // anchor points, so it is reused as long as none of those changed. The - // cache travels with the bucket when buckets are shifted. + // computed from. The SSE only depends on the bucket range [start, end) + // and on its two anchor points (prev and next), so it is reused across + // dynamic optimization iterations as long as none of those four indices + // changed. Because the cache is embedded in BucketRange, it automatically + // travels with the bucket when buckets are shifted via memmove(). npy_intp key_prev; // index of the previous anchor point npy_intp key_start; // bucket start at computation time (-1: invalid) npy_intp key_end; // bucket end at computation time @@ -25,21 +27,30 @@ typedef struct { } BucketRange; +/* + * Computes the area of the triangle formed by points A, B, and C using the + * shoelace formula: 0.5 * |Ax(By - Cy) + Bx(Cy - Ay) + Cx(Ay - By)|. + */ static inline double calc_triangle_area(double ax, double ay, double bx, double by, double cx, double cy) { return fabs((ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) * 0.5); } -/* The core algorithm only handles aligned, C-contiguous float64 vectors. */ +/* + * Debug predicate verifying that a PyArrayObject is a 1-D, aligned, + * C-contiguous array of double-precision floats (NPY_DOUBLE). + */ static inline int is_contiguous_double_1d(PyArrayObject *arr) { return PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_DOUBLE && PyArray_IS_C_CONTIGUOUS(arr) && PyArray_ISALIGNED(arr); } /* - * Calculates the Sum of Squared Errors (SSE) for a given bucket by fitting a - * linear regression line. It includes the previously selected point (prev) - * and the next anchor point (next) to ensure continuity. + * Calculates the Sum of Squared Errors (SSE) for a given bucket [start, end) + * by fitting an Ordinary Least Squares (OLS) linear regression line y = a*x + b. + * It includes the last point of the previous bucket (prev_x, prev_y) and the + * first point of the next bucket (next_x, next_y) so that adjacent buckets + * share boundary anchors for continuity. */ static inline double calculate_sse_bucket(const double *x, const double *y, npy_intp start, npy_intp end, @@ -50,10 +61,10 @@ static inline double calculate_sse_bucket(const double *x, const double *y, const npy_intp bucket_len = end - start; const npy_intp total_points = bucket_len + 2; // Bucket + prev + next + // Pass 1: Accumulate sums for X and Y to find the mean (centroid) double sum_x = prev_x + next_x; double sum_y = prev_y + next_y; - // Accumulate sums for X and Y to find the mean (centroid) for (npy_intp i = start; i < end; i++) { sum_x += x[i]; sum_y += y[i]; @@ -62,16 +73,17 @@ static inline double calculate_sse_bucket(const double *x, const double *y, const double avg_x = sum_x / (double)total_points; const double avg_y = sum_y / (double)total_points; + // Pass 2: Accumulate covariance (numerator) and variance of X (denominator) double numerator = 0.0; double denominator = 0.0; - // Calculate variance/covariance for the previous point + // Contribution from the previous anchor point double dx = prev_x - avg_x; double dy = prev_y - avg_y; numerator += dx * dy; denominator += dx * dx; - // Calculate variance/covariance for all points in the bucket + // Contributions from all points inside the bucket for (npy_intp i = start; i < end; i++) { dx = x[i] - avg_x; dy = y[i] - avg_y; @@ -79,16 +91,16 @@ static inline double calculate_sse_bucket(const double *x, const double *y, denominator += dx * dx; } - // Calculate variance/covariance for the next point + // Contribution from the next anchor point dx = next_x - avg_x; dy = next_y - avg_y; numerator += dx * dy; denominator += dx * dx; - // Calculate linear regression coefficients: y = ax + b + // Calculate linear regression coefficients: y = a * x + b double a, b; if (denominator == 0.0) { - // Handle vertical line edge-case + // Handle vertical line edge-case (zero variance in X) a = (numerator > 0) ? INFINITY : -INFINITY; b = avg_y; } else { @@ -96,19 +108,22 @@ static inline double calculate_sse_bucket(const double *x, const double *y, b = avg_y - a * avg_x; // y-intercept } - // Sum of Squared Errors (SSE) of the vertical residuals against the - // regression line, including both anchor points. + // Pass 3: Sum of Squared Errors (SSE) of the vertical residuals against + // the fitted regression line, including both anchor points. double sse = 0.0; + // Residual of previous anchor point double err = prev_y - (a * prev_x + b); sse += err * err; + // Residuals of all points in the bucket for (npy_intp i = start; i < end; i++) { // err = (Actual Y) - (Predicted Y on the trendline) err = y[i] - (a * x[i] + b); sse += err * err; } + // Residual of next anchor point err = next_y - (a * next_x + b); sse += err * err; @@ -120,10 +135,20 @@ static inline double calculate_sse_bucket(const double *x, const double *y, // ========================================== /* - * Requires `x` and `y` to be C-contiguous float64 arrays of `num_points` - * elements, `out_x` / `out_y` to hold `threshold` elements and `buckets` to - * provide room for `threshold + 1` entries (one scratch slot used while - * splitting). The function cannot fail. + * Executes the Largest Triangle Dynamic (LTD) downsampling algorithm: + * 1. Partitions the interior points into (threshold - 2) equal-sized buckets. + * 2. Iteratively refines bucket boundaries by splitting the bucket with the + * highest linear regression SSE and merging the adjacent pair with the + * lowest combined SSE. + * 3. Applies LTTB point selection across the dynamically sized buckets. + * + * Preconditions: + * - `x` and `y` are C-contiguous float64 arrays of `num_points` elements. + * - `out_x` and `out_y` are C-contiguous float64 arrays of `threshold` + * elements. + * - `buckets` has capacity for `threshold + 1` entries (the extra slot at + * index `threshold` is used as scratch space when splitting a bucket + * before merging). */ static void run_ltd(const double *x, const double *y, npy_intp num_points, int threshold, BucketRange *buckets, double *out_x, @@ -133,16 +158,17 @@ static void run_ltd(const double *x, const double *y, npy_intp num_points, assert(threshold > 2); assert(num_points > threshold); + // Mark all SSE cache entries as invalid before the first iteration for (int i = 0; i <= threshold; i++) { - buckets[i].key_start = -1; // no cached SSE yet + buckets[i].key_start = -1; } // The first and last buckets are explicitly fixed to the first and last - // points + // data points buckets[0].start = 0; buckets[0].end = 1; - // Distribute the remaining points evenly across the middle buckets + // Distribute the remaining interior points evenly across the middle buckets const double bucket_size = (double)(num_points - 2) / (threshold - 2); for (int i = 0; i < threshold - 2; i++) { buckets[i + 1].start = (npy_intp)floor(i * bucket_size) + 1; @@ -153,24 +179,28 @@ static void run_ltd(const double *x, const double *y, npy_intp num_points, buckets[threshold - 1].end = num_points; // Dynamic optimization iterations to adjust bucket boundaries + // (Empirically derived in Steinarsson's paper: threshold * 10 / threshold) const int num_iterations = 10; for (int iter = 0; iter < num_iterations; iter++) { - // Step 1. Calculate SSE for all middle buckets. A split / merge only - // touches a handful of buckets, so after the first iteration nearly - // all values are served from the per-bucket cache instead of - // re-scanning every point (identical results, O(n / threshold) work - // per iteration instead of O(n)). + // Step 1. Update SSE for all middle buckets. + // Because a split and a merge only alter a small neighborhood of + // buckets (the split halves, the merged bucket, and any adjacent + // bucket whose anchor point changed), almost all buckets in iterations + // 2..10 hit the per-bucket cache in O(1) instead of rescanning all N + // points. for (int i = 1; i < threshold - 1; i++) { BucketRange *bk = &buckets[i]; - // Anchor points are the last point of previous bucket and first - // of next bucket + // Anchor points are the last point of the previous bucket and the + // first point of the next bucket const npy_intp prev_idx = buckets[i - 1].end - 1; const npy_intp next_idx = buckets[i + 1].start; assert(prev_idx >= 0 && prev_idx < num_points); assert(next_idx >= 0 && next_idx < num_points); assert(bk->end <= num_points); + // Recompute SSE only if the bucket boundaries or anchor indices + // changed since this bucket's SSE was last evaluated if (bk->key_start != bk->start || bk->key_end != bk->end || bk->key_prev != prev_idx || bk->key_next != next_idx) { bk->sse = calculate_sse_bucket(x, y, bk->start, bk->end, @@ -183,8 +213,8 @@ static void run_ltd(const double *x, const double *y, npy_intp num_points, } } - // Step 2. Find the bucket with the highest SSE (must have >1 point to - // split) + // Step 2. Find the middle bucket with the highest SSE (must contain > 1 + // point so that it can be split into two non-empty halves) double max_sse = 0.0; int high_idx = -1; for (int i = 1; i < threshold - 1; i++) { @@ -195,12 +225,12 @@ static void run_ltd(const double *x, const double *y, npy_intp num_points, } } - // If we can't find a bucket to split, optimization is complete + // If no splittable bucket with positive finite SSE exists, stop early if (high_idx < 0) break; - // Step 3. Find the pair of adjacent buckets with the lowest combined - // SSE (We exclude the bucket we just marked for splitting) + // Step 3. Find the pair of adjacent middle buckets (i, i + 1) with the + // lowest combined SSE, excluding any pair involving high_idx double min_sum = INFINITY; int low_idx = -1; for (int i = 1; i < threshold - 2; i++) { @@ -214,37 +244,42 @@ static void run_ltd(const double *x, const double *y, npy_intp num_points, } } - // If we can't find buckets to merge, optimization is complete + // If no valid pair can be merged (e.g. threshold <= 4 or all sums are + // NaN/Inf), stop early if (low_idx < 0) break; assert(high_idx >= 1 && high_idx <= threshold - 2); assert(low_idx >= 1 && low_idx <= threshold - 3); - // Step 4. Split the highest SSE bucket perfectly in half. + // Step 4. Split the highest-SSE bucket in half. const npy_intp total_len = buckets[high_idx].end - buckets[high_idx].start; const npy_intp half = (npy_intp)ceil((double)total_len / 2.0); const npy_intp orig_end = buckets[high_idx].end; // Shift buckets [high_idx + 1, threshold) one slot to the right to - // make room for the newly split bucket (uses the scratch slot). + // make room for the second half (temporarily using slot `threshold`). memmove(&buckets[high_idx + 2], &buckets[high_idx + 1], sizeof(BucketRange) * (size_t)(threshold - high_idx - 1)); - // Assign boundaries for the two newly split halves. The cache keys - // no longer match, so both halves are recomputed. + // Update boundaries for the two newly split halves. Their start/end + // no longer match key_start/key_end, so both will be recomputed on the + // next iteration. buckets[high_idx].end = buckets[high_idx].start + half; buckets[high_idx + 1].start = buckets[high_idx].end; buckets[high_idx + 1].end = orig_end; buckets[high_idx + 1].key_start = -1; - // Step 5. Merge the pair selected before the split. A split to its - // left shifted the pair one position to the right. + // Step 5. Merge the lowest-SSE pair selected before the split. + // If the pair was to the right of high_idx, the split shifted its + // index by +1. if (low_idx > high_idx) { low_idx++; } + // Extend the first bucket of the pair to cover the second, then shift + // the trailing buckets one slot left to restore `threshold` buckets. buckets[low_idx].end = buckets[low_idx + 1].end; memmove(&buckets[low_idx + 1], &buckets[low_idx + 2], sizeof(BucketRange) * (size_t)(threshold - low_idx - 1)); @@ -253,8 +288,8 @@ static void run_ltd(const double *x, const double *y, npy_intp num_points, // ========================================== // LTTB Point Selection Phase // ========================================== - // Now that buckets are optimally sized, select the best point from each - // bucket. + // Now that the buckets are dynamically sized, select one representative + // point from each bucket using the Largest Triangle Three Buckets rule. // Always select the exact first point out_x[0] = x[0]; @@ -263,7 +298,8 @@ static void run_ltd(const double *x, const double *y, npy_intp num_points, double last_y = out_y[0]; // Iterate over the middle buckets to pick the point that forms the largest - // triangle + // triangle with the previously selected point and the next bucket's + // centroid for (int i = 1; i < threshold - 1; i++) { // 1. Calculate the average point (centroid) of the *next* bucket @@ -271,6 +307,7 @@ static void run_ltd(const double *x, const double *y, npy_intp num_points, const npy_intp next_end = buckets[i + 1].end; const npy_intp next_count = next_end - next_start; assert(next_start >= 0 && next_end <= num_points); + assert(next_count > 0); double avg_next_x = 0.0, avg_next_y = 0.0; for (npy_intp k = next_start; k < next_end; k++) { @@ -326,14 +363,20 @@ static PyObject *largest_triangle_dynamic(PyObject *self, PyObject *args) { return NULL; // Return NULL propagates the Python exception } - // Validation + // Validate threshold and input container types if (threshold <= 2) { PyErr_SetString(PyExc_ValueError, "Threshold must be larger than 2."); return NULL; } + if ((!PyArray_Check(x_obj) && !PyList_Check(x_obj)) || + (!PyArray_Check(y_obj) && !PyList_Check(y_obj))) { + PyErr_SetString(PyExc_TypeError, "x and y must be list or ndarray."); + return NULL; + } + // Convert input objects to aligned, C-contiguous float64 arrays. This is - // a no-op (no copy) for input that already has that layout. + // a no-op (zero copy) when an input array already has that layout. x = (PyArrayObject *)PyArray_FROM_OTF(x_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); y = x ? (PyArrayObject *)PyArray_FROM_OTF(y_obj, NPY_DOUBLE, @@ -354,9 +397,9 @@ static PyObject *largest_triangle_dynamic(PyObject *self, PyObject *args) { const npy_intp len_points = PyArray_DIM(x, 0); - // If the data is already smaller than the threshold, just return the data - // untouched - if (threshold >= len_points) { + // If the data is already smaller than or equal to the threshold, return + // the converted 1D float64 arrays untouched + if (threshold >= len_points || len_points <= 2) { result = PyTuple_Pack(2, x, y); goto done; } @@ -368,9 +411,8 @@ static PyObject *largest_triangle_dynamic(PyObject *self, PyObject *args) { if (!out_x_arr || !out_y_arr) goto done; - // Bucket work space (+1 scratch slot for splitting). Allocated while - // holding the GIL so a failure raises a proper MemoryError instead of - // silently returning garbage. + // Allocate bucket workspace (+1 scratch slot for splitting) while holding + // the GIL so that an allocation failure raises a Python MemoryError. buckets = (BucketRange *)PyMem_Malloc(sizeof(BucketRange) * ((size_t)threshold + 1)); if (!buckets) { @@ -378,7 +420,7 @@ static PyObject *largest_triangle_dynamic(PyObject *self, PyObject *args) { goto done; } - // The core only deals with contiguous memory + // Verify contiguity and alignment invariants before entering the C core assert(is_contiguous_double_1d(x)); assert(is_contiguous_double_1d(y)); assert(is_contiguous_double_1d((PyArrayObject *)out_x_arr)); @@ -389,6 +431,7 @@ static PyObject *largest_triangle_dynamic(PyObject *self, PyObject *args) { double *out_x = (double *)PyArray_DATA((PyArrayObject *)out_x_arr); double *out_y = (double *)PyArray_DATA((PyArrayObject *)out_y_arr); + // Release the GIL during the pure-C computation Py_BEGIN_ALLOW_THREADS; run_ltd(x_raw, y_raw, len_points, threshold, buckets, out_x, out_y); Py_END_ALLOW_THREADS; diff --git a/src/downsample/_ltob.c b/src/downsample/_ltob.c index 6e2e6d2..1c43ed6 100644 --- a/src/downsample/_ltob.c +++ b/src/downsample/_ltob.c @@ -6,12 +6,19 @@ #include +/* + * Computes the area of the triangle formed by points A, B, and C using the + * shoelace formula: 0.5 * |Ax(By - Cy) + Bx(Cy - Ay) + Cx(Ay - By)|. + */ static inline double calc_triangle_area(double ax, double ay, double bx, double by, double cx, double cy) { return fabs((ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) * 0.5); } -/* The core algorithm only handles aligned, C-contiguous float64 vectors. */ +/* + * Debug predicate verifying that a PyArrayObject is a 1-D, aligned, + * C-contiguous array of double-precision floats (NPY_DOUBLE). + */ static inline int is_contiguous_double_1d(PyArrayObject *arr) { return PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_DOUBLE && PyArray_IS_C_CONTIGUOUS(arr) && PyArray_ISALIGNED(arr); @@ -22,8 +29,16 @@ static inline int is_contiguous_double_1d(PyArrayObject *arr) { // ========================================== /* - * Requires `x` and `y` to be C-contiguous float64 arrays of `len_points` - * elements and `result_x` / `result_y` to hold `threshold` elements. + * Executes the Largest Triangle One Bucket (LTOB) downsampling algorithm: + * 1. Keeps the first and last data points (clamping non-finite values to 0). + * 2. Partitions the interior points into (threshold - 2) equal-sized buckets. + * 3. In each bucket, selects the point j that forms the largest triangle + * with its immediate neighbors (j - 1) and (j + 1). + * + * Preconditions: + * - `x` and `y` are C-contiguous float64 arrays of `len_points` elements. + * - `result_x` and `result_y` are C-contiguous float64 arrays of `threshold` + * elements. */ static void run_ltob(const double *x, const double *y, npy_intp len_points, int threshold, double *result_x, double *result_y) { @@ -32,7 +47,7 @@ static void run_ltob(const double *x, const double *y, npy_intp len_points, assert(threshold > 2); assert(len_points > threshold); - // Always add the first point (handling NaNs/Infs using standard C math) + // Always add the first point (replacing NaN/Inf with 0.0) result_x[0] = isfinite(x[0]) ? x[0] : 0.0; result_y[0] = isfinite(y[0]) ? y[0] : 0.0; @@ -52,14 +67,15 @@ static void run_ltob(const double *x, const double *y, npy_intp len_points, double max_area = -1.0; npy_intp max_area_index = start_index; - // bucket_size > 1 (len_points > threshold), so start_index >= 1, and - // end_index is capped at len_points - 1: both neighbours j - 1 and - // j + 1 are always in bounds and no per-point clamping is needed. + // Because len_points > threshold, bucket_size > 1.0, which guarantees + // start_index >= 1 for all i >= 1. Combined with end_index <= + // len_points - 1, both neighbors (j - 1) and (j + 1) are strictly + // within [0, len_points - 1] for every j in [start_index, end_index). assert(start_index >= 1 && start_index < len_points); assert(end_index <= len_points - 1); - // Slide a three-point window (prev, cur, next) over the bucket so - // only one new point is loaded per step. + // Slide a three-point register window (prev, cur, next) across the + // bucket so only one new point (j + 1) is loaded from memory per step. double px = x[start_index - 1]; double py = y[start_index - 1]; double cx = x[start_index]; @@ -70,7 +86,8 @@ static void run_ltob(const double *x, const double *y, npy_intp len_points, const double ny = y[j + 1]; double area = calc_triangle_area(px, py, cx, cy, nx, ny); - // Inf/NaN areas never overtake the bucket logic + // NaN comparisons evaluate to false, preventing NaN areas from + // overtaking the bucket selection if (area > max_area) { max_area = area; max_area_index = j; @@ -82,9 +99,9 @@ static void run_ltob(const double *x, const double *y, npy_intp len_points, } // Save the best point for this bucket. - // If the area was unresolvable or the point itself is not finite, - // fallback to 0.0 to satisfy test_inf(), test_nan(), and - // test_single_inf() expectations. + // If every triangle area was NaN (max_area == -1.0) or the winning + // point itself is non-finite (e.g. a neighbor of an Inf point produced + // an Inf area), fall back to (0.0, 0.0). result_x[i] = 0.0; result_y[i] = 0.0; if (max_area != -1.0) { @@ -98,7 +115,7 @@ static void run_ltob(const double *x, const double *y, npy_intp len_points, } } - // Always add the last point (handling potential NaNs/Infs) + // Always add the last point (replacing NaN/Inf with 0.0) const npy_intp last_idx = len_points - 1; result_x[threshold - 1] = isfinite(x[last_idx]) ? x[last_idx] : 0.0; result_y[threshold - 1] = isfinite(y[last_idx]) ? y[last_idx] : 0.0; @@ -111,11 +128,12 @@ static PyObject *largest_triangle_one_bucket(PyObject *self, PyObject *args) { PyObject *result = NULL; int threshold; - // Parse input arguments + // Parse input arguments: (Object, Object, Integer) if (!PyArg_ParseTuple(args, "OOi", &x_obj, &y_obj, &threshold)) { return NULL; } + // Validate threshold and input container types if (threshold <= 2) { PyErr_SetString(PyExc_ValueError, "Threshold must be larger than 2."); return NULL; @@ -128,7 +146,7 @@ static PyObject *largest_triangle_one_bucket(PyObject *self, PyObject *args) { } // Convert inputs to aligned, C-contiguous float64 arrays. This is a - // no-op (no copy) for input that already has that layout. + // no-op (zero copy) when an input array already has that layout. x_array = (PyArrayObject *)PyArray_FROM_OTF(x_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); y_array = x_array ? (PyArrayObject *)PyArray_FROM_OTF( @@ -137,7 +155,7 @@ static PyObject *largest_triangle_one_bucket(PyObject *self, PyObject *args) { if (!x_array || !y_array) goto done; - // Validation + // Validate array dimensions and matching shapes if (PyArray_NDIM(x_array) != 1 || PyArray_NDIM(y_array) != 1) { PyErr_SetString(PyExc_ValueError, "x and y must be 1-dimensional."); goto done; @@ -149,8 +167,8 @@ static PyObject *largest_triangle_one_bucket(PyObject *self, PyObject *args) { const npy_intp len_points = PyArray_DIM(x_array, 0); - // If threshold is greater than or equal to data size, return arrays - // unchanged + // If threshold is greater than or equal to data size, return the converted + // 1D float64 arrays unchanged if (threshold >= len_points || len_points <= 2) { result = PyTuple_Pack(2, x_array, y_array); goto done; @@ -164,7 +182,7 @@ static PyObject *largest_triangle_one_bucket(PyObject *self, PyObject *args) { goto done; } - // The core only deals with contiguous memory + // Verify contiguity and alignment invariants before entering the C core assert(is_contiguous_double_1d(x_array)); assert(is_contiguous_double_1d(y_array)); assert(is_contiguous_double_1d((PyArrayObject *)npx_obj)); @@ -175,9 +193,7 @@ static PyObject *largest_triangle_one_bucket(PyObject *self, PyObject *args) { double *result_x = (double *)PyArray_DATA((PyArrayObject *)npx_obj); double *result_y = (double *)PyArray_DATA((PyArrayObject *)npy_obj); - // ========================================== - // Release the GIL and do the heavy lifting - // ========================================== + // Release the GIL during the pure-C computation Py_BEGIN_ALLOW_THREADS; run_ltob(x, y, len_points, threshold, result_x, result_y); Py_END_ALLOW_THREADS; diff --git a/src/downsample/_lttb.c b/src/downsample/_lttb.c index e074bc5..a723624 100644 --- a/src/downsample/_lttb.c +++ b/src/downsample/_lttb.c @@ -7,12 +7,19 @@ #include +/* + * Computes the area of the triangle formed by points A, B, and C using the + * shoelace formula: 0.5 * |Ax(By - Cy) + Bx(Cy - Ay) + Cx(Ay - By)|. + */ static inline double calc_triangle_area(double ax, double ay, double bx, double by, double cx, double cy) { return fabs((ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) * 0.5); } -/* The core algorithm only handles aligned, C-contiguous float64 vectors. */ +/* + * Debug predicate verifying that a PyArrayObject is a 1-D, aligned, + * C-contiguous array of double-precision floats (NPY_DOUBLE). + */ static inline int is_contiguous_double_1d(PyArrayObject *arr) { return PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_DOUBLE && PyArray_IS_C_CONTIGUOUS(arr) && PyArray_ISALIGNED(arr); @@ -23,8 +30,18 @@ static inline int is_contiguous_double_1d(PyArrayObject *arr) { // ========================================== /* - * Requires `x` and `y` to be C-contiguous float64 arrays of `len_points` - * elements and `result_x` / `result_y` to hold `threshold` elements. + * Executes the Largest Triangle Three Buckets (LTTB) downsampling algorithm: + * 1. Keeps the first and last data points (clamping non-finite values to 0). + * 2. Partitions the interior points into (threshold - 2) equal-sized buckets. + * 3. For each bucket, computes the centroid (average X, Y) of the *next* + * bucket and selects the point in the *current* bucket that maximizes + * the triangle area formed with the previously selected point and that + * centroid. + * + * Preconditions: + * - `x` and `y` are C-contiguous float64 arrays of `len_points` elements. + * - `result_x` and `result_y` are C-contiguous float64 arrays of `threshold` + * elements. */ static void run_lttb(const double *x, const double *y, npy_intp len_points, int threshold, double *result_x, double *result_y) { @@ -33,19 +50,20 @@ static void run_lttb(const double *x, const double *y, npy_intp len_points, assert(threshold > 2); assert(len_points > threshold); - // Bucket size calculation. (Total points - 2 margins) / (Buckets - 2 - // margins) + // Bucket size calculation: (Total points - 2 endpoints) / (Buckets - 2 + // endpoints) const double every = (double)(len_points - 2) / (threshold - 2); - // Always add the first point (handling potential NaNs/Infs) + // Always add the first point (replacing NaN/Inf with 0.0) result_x[0] = npy_isfinite(x[0]) ? x[0] : 0.0; result_y[0] = npy_isfinite(y[0]) ? y[0] : 0.0; npy_intp a = 0; // Index of the selected point from the previous bucket - // Boundaries of the *current* bucket. The end of the current bucket is - // identical to the start of the next (averaging) bucket, so each - // boundary is computed only once and carried over to the next iteration. + // Boundaries [range_start, range_end) of the *current* bucket. + // Because the end of bucket `i` is identical to the start of bucket + // `i + 1` (the averaging bucket), each boundary is computed once and + // carried forward to the next iteration, cutting floor() calls in half. npy_intp range_start = (npy_intp)(floor((npy_intp)0 * every) + 1); npy_intp range_end = (npy_intp)(floor((npy_intp)1 * every) + 1); @@ -73,8 +91,9 @@ static void run_lttb(const double *x, const double *y, npy_intp len_points, avg_x *= inv_length; avg_y *= inv_length; - // 2. Find the point in the current bucket that forms the largest - // triangle with the previous anchor and the next bucket's centroid. + // 2. Find the point in the current bucket [range_start, range_end) + // that forms the largest triangle with the previous anchor `a` and + // the next bucket's centroid (avg_x, avg_y). assert(range_start >= 1 && range_end <= len_points); const double ax = x[a]; const double ay = y[a]; @@ -90,9 +109,11 @@ static void run_lttb(const double *x, const double *y, npy_intp len_points, } } - // 3. Store the selected point. If no area was comparable (NaN), the - // point is reported as 0.0 and the anchor stays unchanged. + // 3. Store the selected point. If no area was comparable (e.g. NaN), + // the point is reported as (0.0, 0.0) and the anchor `a` stays + // unchanged. if (best >= 0) { + assert(best < len_points); result_x[i + 1] = x[best]; result_y[i + 1] = y[best]; a = best; @@ -101,12 +122,12 @@ static void run_lttb(const double *x, const double *y, npy_intp len_points, result_y[i + 1] = 0.0; } - // Advance to the next bucket + // Advance bucket boundaries to the next bucket range_start = avg_start; range_end = next_range_end; } - // Always add the last point (handling potential NaNs/Infs) + // Always add the last point (replacing NaN/Inf with 0.0) const npy_intp last_idx = len_points - 1; result_x[threshold - 1] = npy_isfinite(x[last_idx]) ? x[last_idx] : 0.0; result_y[threshold - 1] = npy_isfinite(y[last_idx]) ? y[last_idx] : 0.0; @@ -120,17 +141,17 @@ static PyObject *largest_triangle_three_buckets(PyObject *self, PyObject *result = NULL; int threshold; - // Parse input arguments + // Parse input arguments: (Object, Object, Integer) if (!PyArg_ParseTuple(args, "OOi", &x_obj, &y_obj, &threshold)) { return NULL; } + // Validate threshold and input container types if (threshold <= 2) { PyErr_SetString(PyExc_ValueError, "Threshold must be larger than 2."); return NULL; } - // Ensure inputs are arrays or lists if ((!PyArray_Check(x_obj) && !PyList_Check(x_obj)) || (!PyArray_Check(y_obj) && !PyList_Check(y_obj))) { PyErr_SetString(PyExc_TypeError, "x and y must be list or ndarray."); @@ -138,7 +159,7 @@ static PyObject *largest_triangle_three_buckets(PyObject *self, } // Convert inputs to aligned, C-contiguous float64 arrays. This is a - // no-op (no copy) for input that already has that layout. + // no-op (zero copy) when an input array already has that layout. x_array = (PyArrayObject *)PyArray_FROM_OTF(x_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); y_array = x_array ? (PyArrayObject *)PyArray_FROM_OTF( @@ -150,7 +171,7 @@ static PyObject *largest_triangle_three_buckets(PyObject *self, goto done; } - // Validation + // Validate array dimensions and matching shapes if (PyArray_NDIM(x_array) != 1 || PyArray_NDIM(y_array) != 1) { PyErr_SetString(PyExc_ValueError, "x and y must be 1-dimensional."); goto done; @@ -162,7 +183,8 @@ static PyObject *largest_triangle_three_buckets(PyObject *self, const npy_intp len_points = PyArray_DIM(x_array, 0); - // If threshold exceeds the number of points, just return original data + // If threshold exceeds the number of points, return the converted 1D + // float64 arrays untouched if (threshold >= len_points || len_points <= 2) { result = PyTuple_Pack(2, x_array, y_array); goto done; @@ -176,7 +198,7 @@ static PyObject *largest_triangle_three_buckets(PyObject *self, goto done; } - // The core only deals with contiguous memory + // Verify contiguity and alignment invariants before entering the C core assert(is_contiguous_double_1d(x_array)); assert(is_contiguous_double_1d(y_array)); assert(is_contiguous_double_1d((PyArrayObject *)npx_obj)); @@ -187,6 +209,7 @@ static PyObject *largest_triangle_three_buckets(PyObject *self, double *result_x = (double *)PyArray_DATA((PyArrayObject *)npx_obj); double *result_y = (double *)PyArray_DATA((PyArrayObject *)npy_obj); + // Release the GIL during the pure-C computation Py_BEGIN_ALLOW_THREADS; run_lttb(x, y, len_points, threshold, result_x, result_y); Py_END_ALLOW_THREADS; diff --git a/src/downsample/tests/test_ltd.py b/src/downsample/tests/test_ltd.py index 6977d97..6e9a6e0 100644 --- a/src/downsample/tests/test_ltd.py +++ b/src/downsample/tests/test_ltd.py @@ -7,13 +7,35 @@ def test_input_wrong_threshold(): - """Test the down sampling with wrong input types for x or/and y""" + """Test the down sampling with wrong input types for threshold""" x = np.linspace(0.0, 10.0, 100000) y = np.linspace(0.0, 10.0, 100000) with pytest.raises(TypeError): downsample.ltd(x, y, "str") +def test_input_wrong_x_y(): + """Test the down sampling with wrong input types for x or/and y""" + y = np.array([True] * 1000, dtype=bool) + with pytest.raises(TypeError): + downsample.ltd(1, y, 100) + with pytest.raises(TypeError): + downsample.ltd(y, 4, 100) + with pytest.raises(TypeError): + downsample.ltd("wrong", y, 100) + with pytest.raises(TypeError): + downsample.ltd(y, "wrong", 100) + + +def test_single_dimension_validation(): + """Test that the ltd algorithm rejects arrays with multiple dims""" + x = np.zeros((10, 2), dtype=np.double) + y = np.ones(1000, dtype=bool) + with pytest.raises(ValueError): + downsample.ltd(x, y, 100) + + + def test_single_array(): """Test that the ltd algorithm rejects arrays with multiple dims""" x = np.linspace(0, 1, 100000) diff --git a/src/downsample/tests/test_ltob.py b/src/downsample/tests/test_ltob.py index dae318a..7f41488 100644 --- a/src/downsample/tests/test_ltob.py +++ b/src/downsample/tests/test_ltob.py @@ -7,13 +7,35 @@ def test_input_wrong_threshold(): - """Test the down sampling with wrong input types for x or/and y""" + """Test the down sampling with wrong input types for threshold""" x = np.linspace(0.0, 10.0, 100000) y = np.linspace(0.0, 10.0, 100000) with pytest.raises(TypeError): downsample.ltob(x, y, "str") +def test_input_wrong_x_y(): + """Test the down sampling with wrong input types for x or/and y""" + y = np.array([True] * 1000, dtype=bool) + with pytest.raises(TypeError): + downsample.ltob(1, y, 100) + with pytest.raises(TypeError): + downsample.ltob(y, 4, 100) + with pytest.raises(TypeError): + downsample.ltob("wrong", y, 100) + with pytest.raises(TypeError): + downsample.ltob(y, "wrong", 100) + + +def test_single_dimension_validation(): + """Test that the ltob algorithm rejects arrays with multiple dims""" + x = np.zeros((10, 2), dtype=np.double) + y = np.ones(1000, dtype=bool) + with pytest.raises(ValueError): + downsample.ltob(x, y, 100) + + + def test_single_array(): """Test that the ltob algorithm rejects arrays with multiple dims""" x = np.linspace(0, 1, 100000) diff --git a/src/downsample/tests/test_memory_leak.py b/src/downsample/tests/test_memory_leak.py index fce0b6d..9eb6e94 100644 --- a/src/downsample/tests/test_memory_leak.py +++ b/src/downsample/tests/test_memory_leak.py @@ -4,10 +4,10 @@ import numpy as np import pytest -from downsample import ltd, lttb +from downsample import ltd, ltob, lttb -@pytest.mark.parametrize("func", [lttb, ltd]) +@pytest.mark.parametrize("func", [lttb, ltob, ltd]) def test_memory_leak(func): """ Test memory leak for different LTTB functions.