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)