From f2ae3707571bddce4f8259c2048a71c5b325b3c1 Mon Sep 17 00:00:00 2001 From: joobog Date: Thu, 26 Nov 2026 16:14:50 +0000 Subject: [PATCH 01/44] ECC-2393: Add a test Spectral complex packing of a field with a very steep spectrum (like the SPP random patterns 213131-213160) aborts with an assertion instead of returning an error, in GRIB1 and GRIB2. The test builds a T1279 field (sub-truncation 20, 16 bits) whose row norms follow the values of the issue, from 5.8e-2 at n=0 to 1.2e-52 at n=1279, and falls below 1e-15 just above the sub-truncation. It checks: 1. GRIB1: set the values, re-pack the decoded values, convert to GRIB2 2. GRIB2: set the values, re-pack the decoded values 3./4. GRIB1/GRIB2 with an operator set by the user that cannot be coded: an error must be returned instead of an abort Each case can be run alone: grib_ecc-2393 <1-4> --- tests/CMakeLists.txt | 2 + tests/grib_ecc-2393.cc | 215 +++++++++++++++++++++++++++++++++++++++++ tests/grib_ecc-2393.sh | 18 ++++ 3 files changed, 235 insertions(+) create mode 100644 tests/grib_ecc-2393.cc create mode 100755 tests/grib_ecc-2393.sh diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ed3dce43b..a898a57e5 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -69,6 +69,7 @@ list(APPEND test_c_bins grib_ecc-2045 grib_ecc-2188 grib_ecc-2191 + grib_ecc-2393 bufr_ecc-517 bufr_ecc-1288 bufr_ecc-2011 @@ -408,6 +409,7 @@ if( HAVE_BUILD_TOOLS ) grib_ecc-2230 grib_ecc-2268 grib_ecc-2366 + grib_ecc-2393 grib_modelName grib_sub_hourly grib_set_bytes diff --git a/tests/grib_ecc-2393.cc b/tests/grib_ecc-2393.cc new file mode 100644 index 000000000..2e88e24f4 --- /dev/null +++ b/tests/grib_ecc-2393.cc @@ -0,0 +1,215 @@ +/* + * (C) Copyright 2005- ECMWF. + * + * This software is licensed under the terms of the Apache Licence Version 2.0 + * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. + * + * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by + * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. + */ + +/* + * ECC-2393: Spectral complex packing aborts for fields with a very steep spectrum + * + * The test builds a T1279 field whose row norms follow the SPP random patterns + * 213131-213160 of the issue (5.8e-2 at n=0 down to 1.2e-52 at n=1279; the tail + * falls like (n(n+1))^-9.9). The spectrum is very steep just above the sub-truncation + * (TS=20) and falls below 1e-15 from n=30. Before the fix, the laplacian operator was + * fitted on these few steep rows only, the scaled coefficients of the tail overflowed + * and packing aborted: + * GRIB1: assertion `scale <= last' in grib_scaling.cc + * GRIB2: assertion in grib_ieee_to_long (reference value out of range) + */ + +#include "eccodes.h" + +#undef NDEBUG +#include +#include +#include +#include + +static const long T = 1279; +static const long TS = 20; + +/* Row norm of the test spectrum: log-log interpolation through the values of the issue */ +static double row_norm(long n) +{ + static const double ns[] = { 1, 10, 21, 30, 100, 500, 1279 }; + static const double amps[] = { 5.8e-2, 4.3e-5, 1e-8, 1e-15, 9.1e-31, 1.4e-44, 1.2e-52 }; + const int npts = sizeof(ns) / sizeof(ns[0]); + if (n < 1) + return amps[0]; + for (int i = 0; i < npts - 1; i++) { + if (n <= ns[i + 1]) { + const double t = (log((double)n) - log(ns[i])) / (log(ns[i + 1]) - log(ns[i])); + return exp(log(amps[i]) + t * (log(amps[i + 1]) - log(amps[i]))); + } + } + return amps[npts - 1]; +} + +/* Fill the coefficients in ecCodes order (m outer, n inner, real and imaginary parts). + Every coefficient is non-zero, as in the fields of the issue, except the imaginary + parts for m=0, which are zero for a real field (and decoded as zero). */ +static void fill_spectrum(double* values, size_t len) +{ + size_t i = 0; + unsigned long rnd = 12345; + for (long m = 0; m <= T; m++) { + for (long n = m; n <= T; n++) { + for (int k = 0; k < 2; k++) { + rnd = rnd * 1103515245UL + 12345UL; + const double frac = 0.5 + 0.5 * (double)((rnd >> 16) & 0x7fff) / 32767.0; /* 0.5 .. 1 */ + const double sign = ((rnd >> 8) & 1) ? 1.0 : -1.0; + assert(i < len); + values[i++] = (m == 0 && k == 1) ? 0.0 : sign * frac * row_norm(n); + } + } + } + assert(i == len); +} + +/* Setting J,K,M resizes the field only in GRIB1, so a GRIB2 field is converted from GRIB1 */ +static codes_handle* new_field(long edition, double** values, size_t* len) +{ + codes_handle* h = codes_grib_handle_new_from_samples(NULL, "sh_ml_grib1"); + assert(h); + CODES_CHECK(codes_set_long(h, "J", T), 0); + CODES_CHECK(codes_set_long(h, "K", T), 0); + CODES_CHECK(codes_set_long(h, "M", T), 0); + if (edition == 2) + CODES_CHECK(codes_set_long(h, "edition", 2), 0); + CODES_CHECK(codes_set_long(h, "bitsPerValue", 16), 0); + + size_t n = 0; + CODES_CHECK(codes_get_size(h, "values", &n), 0); + assert(n == (size_t)((T + 1) * (T + 2))); + *values = (double*)malloc(n * sizeof(double)); + assert(*values); + fill_spectrum(*values, n); + *len = n; + return h; +} + +/* Check the decoded coefficients: the unpacked sub-truncation must be exact (float), + and a packed coefficient of row n must be within one quantisation step of the + packing, 2^E / (10^D * (n(n+1))^P) */ +static void check_decoded(codes_handle* h, const double* expected, size_t len) +{ + double* decoded = (double*)malloc(len * sizeof(double)); + size_t dlen = len; + long E = 0, D = 0; + double P = 0; + assert(decoded); + CODES_CHECK(codes_get_double_array(h, "values", decoded, &dlen), 0); + assert(dlen == len); + CODES_CHECK(codes_get_long(h, "binaryScaleFactor", &E), 0); + CODES_CHECK(codes_get_long(h, "decimalScaleFactor", &D), 0); + CODES_CHECK(codes_get_double(h, "laplacianOperator", &P), 0); + const double step = ldexp(1.0, (int)E) / pow(10.0, (double)D); + + /* The unpacked sub-truncation (m,n <= TS) is stored as floats */ + size_t i = 0; + for (long m = 0; m <= T; m++) { + for (long n = m; n <= T; n++) { + for (int k = 0; k < 2; k++, i++) { + if (n <= TS) { + const double err = fabs(decoded[i] - expected[i]); + assert(err <= 1e-6 * fabs(expected[i])); + } + else { + const double scale = pow((double)(n * (n + 1)), P); + const double err = fabs(decoded[i] - expected[i]) * scale; + if (!(err <= step)) { + printf(" m=%ld n=%ld: decoded=%g expected=%g scaled error=%g > step=%g (E=%ld D=%ld P=%g)\n", + m, n, decoded[i], expected[i], err, step, E, D, P); + } + assert(err <= step); + } + } + } + } + free(decoded); +} + +static void test_repack(long edition) +{ + double* values = NULL; + size_t len = 0; + double op = 0; + printf("ECC-2393: GRIB%ld: set values of a steep spectrum\n", edition); + + codes_handle* h = new_field(edition, &values, &len); + int err = codes_set_double_array(h, "values", values, len); + printf(" codes_set_double_array: %s\n", codes_get_error_message(err)); + assert(err == CODES_SUCCESS); + CODES_CHECK(codes_get_double(h, "laplacianOperator", &op), 0); + printf(" laplacianOperator=%g\n", op); + assert(op > 0 && op < 9999); + check_decoded(h, values, len); + + /* Re-pack the decoded values (2nd case of the issue) */ + { + double* decoded = (double*)malloc(len * sizeof(double)); + size_t dlen = len; + assert(decoded); + CODES_CHECK(codes_get_double_array(h, "values", decoded, &dlen), 0); + err = codes_set_double_array(h, "values", decoded, dlen); + printf(" re-pack: %s\n", codes_get_error_message(err)); + assert(err == CODES_SUCCESS); + free(decoded); + } + + /* Convert the edition (1st case of the issue: grib_set -s edition=2) */ + { + if (edition == 1) { + /* The conversion re-packs the decoded GRIB1 values: compare with them */ + size_t dlen = len; + CODES_CHECK(codes_get_double_array(h, "values", values, &dlen), 0); + assert(dlen == len); + err = codes_set_long(h, "edition", 2); + printf(" edition=2: %s\n", codes_get_error_message(err)); + assert(err == CODES_SUCCESS); + CODES_CHECK(codes_get_double(h, "laplacianOperator", &op), 0); + printf(" laplacianOperator=%g\n", op); + assert(op > 0 && op < 9999); + check_decoded(h, values, len); + } + } + + codes_handle_delete(h); + free(values); +} + +/* With an operator given by the user that cannot be represented, packing must fail + with an error code instead of aborting */ +static void test_operator_out_of_range(long edition) +{ + double* values = NULL; + size_t len = 0; + printf("ECC-2393: GRIB%ld: user operator out of range\n", edition); + + codes_handle* h = new_field(edition, &values, &len); + CODES_CHECK(codes_set_long(h, "computeLaplacianOperator", 0), 0); + CODES_CHECK(codes_set_double(h, "laplacianOperator", 30.0), 0); + int err = codes_set_double_array(h, "values", values, len); + printf(" codes_set_double_array: %s\n", codes_get_error_message(err)); + assert(err != CODES_SUCCESS); + + codes_handle_delete(h); + free(values); +} + +int main(int argc, char** argv) +{ + /* Optional argument: run only one case (1..4) */ + const long only = argc > 1 ? strtol(argv[1], NULL, 10) : 0; + (void)setvbuf(stdout, NULL, _IONBF, 0); + if (!only || only == 1) test_repack(1); + if (!only || only == 2) test_repack(2); + if (!only || only == 3) test_operator_out_of_range(1); + if (!only || only == 4) test_operator_out_of_range(2); + printf("ECC-2393: all tests passed\n"); + return 0; +} diff --git a/tests/grib_ecc-2393.sh b/tests/grib_ecc-2393.sh new file mode 100755 index 000000000..6bfab6475 --- /dev/null +++ b/tests/grib_ecc-2393.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# (C) Copyright 2005- ECMWF. +# +# This software is licensed under the terms of the Apache Licence Version 2.0 +# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. +# +# In applying this licence, ECMWF does not waive the privileges and immunities granted to it by +# virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. +# + +. ./include.ctest.sh + +# --------------------------------------------------------- +# ECC-2393: Spectral complex packing aborts for fields with +# a very steep spectrum (SPP random patterns 213131-213160) +# --------------------------------------------------------- + +$EXEC ${test_dir}/grib_ecc-2393 From fbc1eab0d9c3447d088b12acd2503700d42da199 Mon Sep 17 00:00:00 2001 From: joobog Date: Thu, 26 Nov 2026 16:14:50 +0000 Subject: [PATCH 02/44] ECC-2393: Fix spectral complex packing of fields with a very steep spectrum calculate_pfactor sets the row norms below zeps=1e-15 to zeps and gives them a negligible weight. For a very steep spectrum, the laplacian operator is then fitted on a few steep rows just above the sub-truncation. Applied up to the full truncation, it makes the scaled coefficients overflow the reference value (IEEE/IBM float) and the binary scale factor, and packing aborted with an assertion. - calculate_pfactor: if the fitted operator would make the scaled coefficients overflow, fit again on the real row norms (only zero rows are ignored). This gives the slope of the spectrum tail, e.g. 9.9 for the SPP patterns, the value IFS writes. If the scaled coefficients would still be too large, use the largest operator that keeps them below 1e30. The fit of all other fields is unchanged (bit-identical output). - pack_double: check that the scaled values can be coded (reference value and binary scale factor) and return GRIB_OUT_OF_RANGE instead of failing an assertion, e.g. for an operator set by the user. --- src/eccodes/accessor/DataComplexPacking.cc | 192 ++++++++++++++++----- 1 file changed, 147 insertions(+), 45 deletions(-) diff --git a/src/eccodes/accessor/DataComplexPacking.cc b/src/eccodes/accessor/DataComplexPacking.cc index 2d179aa57..49ed76754 100644 --- a/src/eccodes/accessor/DataComplexPacking.cc +++ b/src/eccodes/accessor/DataComplexPacking.cc @@ -9,6 +9,10 @@ */ #include "DataComplexPacking.h" +#include "grib_ibmfloat.h" + +#include +#include namespace eccodes::accessor { @@ -60,28 +64,119 @@ int DataComplexPacking::value_count(long* count) return ret; } +/* + * Weighted least square fit of log(norm) over log(n(n+1)) for the rows ismin..ismax. + * Returns the laplacian operator (minus the slope). + * rowNorms: the largest absolute coefficient of each row + * zeps: norms below zeps are set to zeps (no log(0)) and get a negligible weight + * norms, weights: work arrays of size ismax+1 + */ +static double fit_laplacian_operator(const double* rowNorms, long ismin, long ismax, double zeps, + double* norms, double* weights) +{ + long loop; + double weightedSumOverX = 0.0, weightedSumOverY = 0.0, sumOfWeights = 0.0, x, y; + double numerator = 0.0, denominator = 0.0, slope; + + /* + * Setup the weights + */ + const double range = (double)(ismax - ismin + 1); + for (loop = ismin; loop <= ismax; loop++) + weights[loop] = range / (double)(loop - ismin + 1); + + /* + * Ensure the norms have a value which is not too small in case of + * problems with math functions (e.g. LOG). + */ + for (loop = ismin; loop <= ismax; loop++) { + norms[loop] = std::max(rowNorms[loop], zeps); + if (norms[loop] == zeps) + weights[loop] = 100.0 * zeps; + } + + /* + * Do linear fit to find the slope + */ + for (loop = ismin; loop <= ismax; loop++) { + x = log((double)(loop * (loop + 1))); + ECCODES_ASSERT(norms[loop] > 0); + y = log(norms[loop]); + weightedSumOverX = weightedSumOverX + x * weights[loop]; + weightedSumOverY = weightedSumOverY + y * weights[loop]; + sumOfWeights = sumOfWeights + weights[loop]; + } + weightedSumOverX = weightedSumOverX / sumOfWeights; + weightedSumOverY = weightedSumOverY / sumOfWeights; + + /* + * Perform a least square fit for the equation + */ + for (loop = ismin; loop <= ismax; loop++) { + x = log((double)(loop * (loop + 1))); + y = log(norms[loop]); + numerator = + numerator + weights[loop] * (y - weightedSumOverY) * (x - weightedSumOverX); + denominator = + denominator + weights[loop] * ((x - weightedSumOverX) * (x - weightedSumOverX)); + } + slope = numerator / denominator; + + return -slope; +} + +/* + * ECC-2393: Natural logarithm of the largest scaled coefficient, max(norm(n) * (n(n+1))^p), + * over the rows ismin..ismax with a non-zero norm. Returns -HUGE_VAL if all norms are zero. + */ +static double log_max_scaled_norm(const double* rowNorms, long ismin, long ismax, double p) +{ + double result = -HUGE_VAL; + for (long loop = ismin; loop <= ismax; loop++) { + if (rowNorms[loop] > 0) + result = std::max(result, log(rowNorms[loop]) + p * log((double)(loop * (loop + 1)))); + } + return result; +} + +/* + * ECC-2393: Largest laplacian operator for which no scaled coefficient of the rows + * ismin..ismax exceeds exp(logLimit): norm(n) * (n(n+1))^p <= exp(logLimit) for all n + */ +static double max_laplacian_operator(const double* rowNorms, long ismin, long ismax, double logLimit) +{ + double result = HUGE_VAL; + for (long loop = ismin; loop <= ismax; loop++) { + if (rowNorms[loop] > 0) + result = std::min(result, (logLimit - log(rowNorms[loop])) / log((double)(loop * (loop + 1)))); + } + return result; +} + double calculate_pfactor(const grib_context* ctx, const double* spectralField, long fieldTruncation, long subsetTruncation) { /*long n_vals = ((fieldTruncation+1)*(fieldTruncation+2));*/ long loop, index, m, n = 0; double pFactor, zeps = 1.0e-15; long ismin = (subsetTruncation + 1), ismax = (fieldTruncation + 1); - double *weights, range, *norms; - double weightedSumOverX = 0.0, weightedSumOverY = 0.0, sumOfWeights = 0.0, x, y; - double numerator = 0.0, denominator = 0.0, slope; + double *weights, *norms, *workNorms; + + /* + * ECC-2393: Scaled coefficients above kOverflowLimit cannot be coded: the reference value + * is a 32-bit float (IEEE in GRIB2, |x| <= FLT_MAX) and the binary scale factor is at most 127. + * An operator limited because of an overflow keeps the scaled coefficients below + * kMaxScaledNorm, which leaves a margin for the rounding of the coded operator. + */ + constexpr double kOverflowLimit = FLT_MAX / 2; + constexpr double kMaxScaledNorm = 1.0e30; /* Catch corner case. See GRIB-172 */ if (ismax - ismin <= 1) { return 1; /* any value will do! we cannot do linear fit on a single point! */ } - /* - * Setup the weights - */ - range = (double)(ismax - ismin + 1); weights = (double*)grib_context_malloc(ctx, (ismax + 1) * sizeof(double)); - for (loop = ismin; loop <= ismax; loop++) - weights[loop] = range / (double)(loop - ismin + 1); + workNorms = (double*)grib_context_malloc(ctx, (ismax + 1) * sizeof(double)); /* * Compute norms @@ -116,62 +211,47 @@ double calculate_pfactor(const grib_context* ctx, const double* spectralField, l } } - /* - * Ensure the norms have a value which is not too small in case of - * problems with math functions (e.g. LOG). - */ - long numValidNorms = 0; - for (loop = ismin; loop <= ismax; loop++) { - norms[loop] = std::max(norms[loop], zeps); - if (norms[loop] == zeps) - weights[loop] = 100.0 * zeps; - else - numValidNorms++; - } - /* * Catch corner case: fewer than two rows with non-negligible coefficients, * e.g. a field zero-padded to a higher truncation. The fit would then be driven * solely by the artificial zeps norms, giving a huge, meaningless operator * and an IEEE float overflow when scaling. Same fallback as GRIB-172. */ + long numValidNorms = 0; + for (loop = ismin; loop <= ismax; loop++) { + if (norms[loop] > zeps) + numValidNorms++; + } if (numValidNorms < 2) { grib_context_free(ctx, weights); + grib_context_free(ctx, workNorms); grib_context_free(ctx, norms); return 1; } - /* - * Do linear fit to find the slope - */ - for (loop = ismin; loop <= ismax; loop++) { - x = log((double)(loop * (loop + 1))); - ECCODES_ASSERT(norms[loop] > 0); - y = log(norms[loop]); - weightedSumOverX = weightedSumOverX + x * weights[loop]; - weightedSumOverY = weightedSumOverY + y * weights[loop]; - sumOfWeights = sumOfWeights + weights[loop]; - } - weightedSumOverX = weightedSumOverX / sumOfWeights; - weightedSumOverY = weightedSumOverY / sumOfWeights; + pFactor = fit_laplacian_operator(norms, ismin, ismax, zeps, workNorms, weights); /* - * Perform a least square fit for the equation + * ECC-2393: For a very steep spectrum, most rows are below zeps and get a negligible + * weight: the slope is then fitted on a few steep rows just above the sub-truncation. + * Applied up to the full truncation, such an operator makes the scaled coefficients + * overflow. Fit again on the real norms (only zero rows are ignored); if the scaled + * coefficients would still be too large, use the largest operator that keeps them in range. */ - for (loop = ismin; loop <= ismax; loop++) { - x = log((double)(loop * (loop + 1))); - y = log(norms[loop]); - numerator = - numerator + weights[loop] * (y - weightedSumOverY) * (x - weightedSumOverX); - denominator = - denominator + weights[loop] * ((x - weightedSumOverX) * (x - weightedSumOverX)); + if (pFactor > 0 && log_max_scaled_norm(norms, ismin, ismax, pFactor) > log(kOverflowLimit)) { + const double fitted = pFactor; + pFactor = fit_laplacian_operator(norms, ismin, ismax, DBL_MIN, workNorms, weights); + if (log_max_scaled_norm(norms, ismin, ismax, pFactor) > log(kMaxScaledNorm)) + pFactor = std::max(0.0, max_laplacian_operator(norms, ismin, ismax, log(kMaxScaledNorm))); + grib_context_log(ctx, GRIB_LOG_DEBUG, + "calculate_pfactor: laplacian operator %g would make the scaled values overflow, using %g", + fitted, pFactor); } - slope = numerator / denominator; grib_context_free(ctx, weights); + grib_context_free(ctx, workNorms); grib_context_free(ctx, norms); - pFactor = -slope; if (pFactor < -9999.9) pFactor = -9999.9; if (pFactor > 9999.9) @@ -432,6 +512,28 @@ int DataComplexPacking::pack_double(const double* val, size_t* len) mmax++; } + /* + * ECC-2393: The scaled values must be codable: the reference value is a 32-bit float + * (IBM in GRIB1, IEEE in GRIB2) and the range must fit with a binary scale factor <= 127. + * Return an error instead of failing an assertion in the float or scaling functions. + */ + { + const double dd = optimize_scaling_factor ? 1.0 : codes_power(+decimal_scale_factor, 10); + // Half the largest float: the nearest smaller value of a negative minimum is further from zero + const double refLimit = 0.5 * ((ieee_floats == 0) ? IbmTable::vmax : IeeeTable::vmax); + const double rangeLimit = std::ldexp(codes_power(bits_per_value, 2) - 1, 127); + if (!std::isfinite(min) || !std::isfinite(max) || + fabs(dd * min) > refLimit || fabs(dd * max) > refLimit || + (bits_per_value >= 1 && dd * (max - min) > rangeLimit)) { + grib_context_log(context_, GRIB_LOG_ERROR, + "%s: Scaled values out of range (min=%g, max=%g, laplacianOperator=%g)", + accessor_type().c_str(), dd * min, dd * max, laplacianOperator); + grib_context_free(context_, scals); + grib_context_free(context_, buf); + return GRIB_OUT_OF_RANGE; + } + } + if (optimize_scaling_factor) { ret = grib_optimize_decimal_factor(this, reference_value_, max, min, bits_per_value, 0, 1, From 24cc46eb21788783232cfd836154eefd4bd448cf Mon Sep 17 00:00:00 2001 From: joobog Date: Thu, 26 Nov 2026 17:12:14 +0000 Subject: [PATCH 03/44] spectral_complex: new library for GRIB spectral complex packing --- projects/spectral_complex/.clang-format | 108 ++++ projects/spectral_complex/.clang-tidy | 74 +++ projects/spectral_complex/.gitignore | 6 + projects/spectral_complex/CHANGELOG.md | 29 + projects/spectral_complex/CMakeLists.txt | 180 ++++++ projects/spectral_complex/LICENSE | 201 ++++++ projects/spectral_complex/README.md | 122 ++++ .../cmake/spectral_complexConfig.cmake.in | 11 + .../cmake/spectral_complexFloatingPoint.cmake | 221 +++++++ .../include/spectral_complex/detail/Float.h | 78 +++ .../spectral_complex/detail/Operator.h | 26 + .../spectral_complex/spectral_complex.h | 500 +++++++++++++++ .../include/spectral_complex/version.h | 23 + projects/spectral_complex/src/Float.cc | 242 +++++++ projects/spectral_complex/src/Operator.cc | 139 ++++ .../spectral_complex/tests/CMakeLists.txt | 48 ++ .../tests/install/consumer/CMakeLists.txt | 11 + .../tests/install/consumer/main.cc | 33 + .../tests/install/install_test.cmake | 62 ++ .../spectral_complex/tests/legacy_reference.h | 600 ++++++++++++++++++ .../tests/regression/CMakeLists.txt | 31 + .../regression/ecc_2393_steep_spectrum.cc | 52 ++ .../tests/regression/full_sub_truncation.cc | 55 ++ .../tests/regression/grib_172_single_row.cc | 30 + .../regression/real_field_and_gribex_bug.cc | 51 ++ .../tests/regression/underflow_zero_codes.cc | 42 ++ .../tests/regression/zero_packed_part.cc | 46 ++ projects/spectral_complex/tests/test_fields.h | 133 ++++ .../tests/unit/CMakeLists.txt | 25 + projects/spectral_complex/tests/unit/api.cc | 94 +++ .../tests/unit/float_codes.cc | 117 ++++ .../tests/unit/operator_reference.cc | 46 ++ .../tests/unit/pack_reference.cc | 165 +++++ .../spectral_complex/tests/unit/version.cc | 22 + 34 files changed, 3623 insertions(+) create mode 100644 projects/spectral_complex/.clang-format create mode 100644 projects/spectral_complex/.clang-tidy create mode 100644 projects/spectral_complex/.gitignore create mode 100644 projects/spectral_complex/CHANGELOG.md create mode 100644 projects/spectral_complex/CMakeLists.txt create mode 100755 projects/spectral_complex/LICENSE create mode 100644 projects/spectral_complex/README.md create mode 100644 projects/spectral_complex/cmake/spectral_complexConfig.cmake.in create mode 100644 projects/spectral_complex/cmake/spectral_complexFloatingPoint.cmake create mode 100644 projects/spectral_complex/include/spectral_complex/detail/Float.h create mode 100644 projects/spectral_complex/include/spectral_complex/detail/Operator.h create mode 100644 projects/spectral_complex/include/spectral_complex/spectral_complex.h create mode 100644 projects/spectral_complex/include/spectral_complex/version.h create mode 100644 projects/spectral_complex/src/Float.cc create mode 100644 projects/spectral_complex/src/Operator.cc create mode 100644 projects/spectral_complex/tests/CMakeLists.txt create mode 100644 projects/spectral_complex/tests/install/consumer/CMakeLists.txt create mode 100644 projects/spectral_complex/tests/install/consumer/main.cc create mode 100644 projects/spectral_complex/tests/install/install_test.cmake create mode 100644 projects/spectral_complex/tests/legacy_reference.h create mode 100644 projects/spectral_complex/tests/regression/CMakeLists.txt create mode 100644 projects/spectral_complex/tests/regression/ecc_2393_steep_spectrum.cc create mode 100644 projects/spectral_complex/tests/regression/full_sub_truncation.cc create mode 100644 projects/spectral_complex/tests/regression/grib_172_single_row.cc create mode 100644 projects/spectral_complex/tests/regression/real_field_and_gribex_bug.cc create mode 100644 projects/spectral_complex/tests/regression/underflow_zero_codes.cc create mode 100644 projects/spectral_complex/tests/regression/zero_packed_part.cc create mode 100644 projects/spectral_complex/tests/test_fields.h create mode 100644 projects/spectral_complex/tests/unit/CMakeLists.txt create mode 100644 projects/spectral_complex/tests/unit/api.cc create mode 100644 projects/spectral_complex/tests/unit/float_codes.cc create mode 100644 projects/spectral_complex/tests/unit/operator_reference.cc create mode 100644 projects/spectral_complex/tests/unit/pack_reference.cc create mode 100644 projects/spectral_complex/tests/unit/version.cc diff --git a/projects/spectral_complex/.clang-format b/projects/spectral_complex/.clang-format new file mode 100644 index 000000000..f7f2be2cf --- /dev/null +++ b/projects/spectral_complex/.clang-format @@ -0,0 +1,108 @@ +--- +Language: Cpp +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignConsecutiveMacros: true +AlignEscapedNewlines: Left +AlignOperands: AlignAfterOperator +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: true +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: true + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: AfterColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 0 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeCategories: + - Regex: '^<.*\.h>' + Priority: 1 + - Regex: '^<.*' + Priority: 2 + - Regex: '.*' + Priority: 3 +IncludeIsMainRegex: '([-_](test|unittest))?$' +IndentCaseLabels: true +IndentPPDirectives: BeforeHash +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 2 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: false +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +ReflowComments: true +SortIncludes: false +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 2 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Auto +TabWidth: 4 +UseTab: Never +... diff --git a/projects/spectral_complex/.clang-tidy b/projects/spectral_complex/.clang-tidy new file mode 100644 index 000000000..fed9f97c8 --- /dev/null +++ b/projects/spectral_complex/.clang-tidy @@ -0,0 +1,74 @@ +--- +# bugprone-assignment-in-if-condition stays off: -Wparentheses already catches +# `if (a = b)`, and `if ((err = f()))` is the idiom here. +# The trailing - entries are findings not yet fixed; each fix drops its entry. +Checks: > + -*, + bugprone-*, + clang-analyzer-*, + performance-*, + cert-err33-c, + concurrency-mt-unsafe, + misc-redundant-expression, + readability-misleading-indentation, + -bugprone-assignment-in-if-condition, + -bugprone-argument-comment, + -bugprone-branch-clone, + -bugprone-easily-swappable-parameters, + -bugprone-empty-catch, + -bugprone-forward-declaration-namespace, + -bugprone-implicit-widening-of-multiplication-result, + -bugprone-inc-dec-in-conditions, + -bugprone-incorrect-roundings, + -bugprone-integer-division, + -bugprone-macro-parentheses, + -bugprone-misplaced-widening-cast, + -bugprone-multi-level-implicit-pointer-conversion, + -bugprone-narrowing-conversions, + -bugprone-not-null-terminated-result, + -bugprone-reserved-identifier, + -bugprone-signed-char-misuse, + -bugprone-suspicious-include, + -bugprone-suspicious-string-compare, + -bugprone-switch-missing-default-case, + -bugprone-unsafe-functions, + -clang-analyzer-core.BitwiseShift, + -clang-analyzer-core.NonNullParamChecker, + -clang-analyzer-core.NullDereference, + -clang-analyzer-core.UndefinedBinaryOperatorResult, + -clang-analyzer-deadcode.DeadStores, + -clang-analyzer-optin.performance.Padding, + -clang-analyzer-security.insecureAPI.strcpy, + -clang-analyzer-unix.Malloc, + -concurrency-mt-unsafe, + -performance-enum-size, + -performance-inefficient-vector-operation, + -performance-unnecessary-value-param +# The code is not yet clean under these checks (mostly bugprone-signed-bitwise): they are reported as +# warnings, not errors. Set WarningsAsErrors: '*' once it is. +WarningsAsErrors: '' +CheckOptions: + # The default list without the printf family and fclose: a failed write to a + # stream or buffer is rarely something the caller can handle, and most files + # here are read-only. Files that are written check their fclose by hand. + cert-err33-c.CheckedFunctions: >- + ::asctime_s; ::at_quick_exit; ::atexit; ::bsearch; ::bsearch_s; ::btowc; ::c16rtomb; ::c32rtomb; + ::calloc; ::clock; ::cnd_broadcast; ::cnd_init; ::cnd_signal; ::cnd_timedwait; ::cnd_wait; + ::ctime_s; ::fflush; ::fgetc; ::fgetpos; ::fgets; ::fgetwc; ::fopen; ::fopen_s; + ::fread; ::freopen; ::freopen_s; ::fscanf; ::fscanf_s; ::fseek; ::fsetpos; ::ftell; ::fwrite; + ::fwscanf; ::fwscanf_s; ::getc; ::getchar; ::getenv; ::getenv_s; ::gets_s; ::getwc; ::getwchar; + ::gmtime; ::gmtime_s; ::localtime; ::localtime_s; ::malloc; ::mbrtoc16; ::mbrtoc32; ::mbsrtowcs; + ::mbsrtowcs_s; ::mbstowcs; ::mbstowcs_s; ::memchr; ::mktime; ::mtx_init; ::mtx_lock; + ::mtx_timedlock; ::mtx_trylock; ::mtx_unlock; ::raise; ::realloc; ::remove; ::rename; ::scanf; + ::scanf_s; ::setlocale; ::setvbuf; ::signal; ::sscanf; ::sscanf_s; ::strchr; ::strerror_s; + ::strftime; ::strpbrk; ::strrchr; ::strstr; ::strtod; ::strtof; ::strtoimax; ::strtok; + ::strtok_s; ::strtol; ::strtold; ::strtoll; ::strtoul; ::strtoull; ::strtoumax; ::strxfrm; + ::swscanf; ::swscanf_s; ::thrd_create; ::thrd_detach; ::thrd_join; ::thrd_sleep; ::time; + ::timespec_get; ::tmpfile; ::tmpfile_s; ::tmpnam; ::tmpnam_s; ::tss_create; ::tss_get; + ::tss_set; ::ungetc; ::ungetwc; ::vfscanf; ::vfscanf_s; ::vfwscanf; ::vfwscanf_s; ::vscanf; + ::vscanf_s; ::vsscanf; ::vsscanf_s; ::vswscanf; ::vswscanf_s; ::vwscanf; ::vwscanf_s; ::wcrtomb; + ::wcschr; ::wcsftime; ::wcspbrk; ::wcsrchr; ::wcsrtombs; ::wcsrtombs_s; ::wcsstr; ::wcstod; + ::wcstof; ::wcstoimax; ::wcstok; ::wcstok_s; ::wcstol; ::wcstold; ::wcstoll; ::wcstombs; + ::wcstombs_s; ::wcstoul; ::wcstoull; ::wcstoumax; ::wcsxfrm; ::wctob; ::wctrans; ::wctype; + ::wmemchr; ::wscanf; ::wscanf_s +... diff --git a/projects/spectral_complex/.gitignore b/projects/spectral_complex/.gitignore new file mode 100644 index 000000000..053da9b0b --- /dev/null +++ b/projects/spectral_complex/.gitignore @@ -0,0 +1,6 @@ +# Build directories and files generated by tools +build/ +build-*/ +compile_commands.json +.cache/ +.clangd diff --git a/projects/spectral_complex/CHANGELOG.md b/projects/spectral_complex/CHANGELOG.md new file mode 100644 index 000000000..04810c28e --- /dev/null +++ b/projects/spectral_complex/CHANGELOG.md @@ -0,0 +1,29 @@ + + +# Changelog + +All notable changes to spectral_complex. The version is defined in +`include/spectral_complex/version.h`. Before version 1.0.0 the interface may still change. + +## 0.0.1 (unreleased) + +First version. + +- GRIB spectral complex packing: `sc::laplacianOperator`, `sc::parameters`, `sc::pack`, + `sc::unpack`, `sc::Layout`, `sc::Parameters`, `sc::Method`. +- Unpacked sub-truncation as IEEE32, IEEE64 or IBM32 floats; packed coefficients with 1 to 63 bits + per value (simple_packing), IEEE (GRIB2) or IBM (GRIB1) reference values; unpacking to `float` + and `double`. +- The laplacian operator of legacy ecCodes, including GRIB-172 (one packed row) and ECC-2393 (fields + with a very steep spectrum). +- Packed data byte-identical to legacy ecCodes, including the GRIBEX sh bug, the underflow of the + binary scale factor and JS = J; decoded values bit-identical in `double` (floats: the doubles converted, as ecCodes). +- Errors are exceptions where legacy ecCodes failed an assertion or coded garbage (values that cannot + be coded, NaN). +- Floating-point compiler options `ON` by default (`SPECTRAL_COMPLEX_FP_CONTRACT_OFF`, + `SPECTRAL_COMPLEX_NO_FAST_MATH`, `SPECTRAL_COMPLEX_NO_TRAPPING_MATH`). +- Benchmark `benchmarks/sc_bench` (`SPECTRAL_COMPLEX_BUILD_BENCHMARKS`), libFuzzer fuzzers + (`SPECTRAL_COMPLEX_BUILD_FUZZERS`), install test. diff --git a/projects/spectral_complex/CMakeLists.txt b/projects/spectral_complex/CMakeLists.txt new file mode 100644 index 000000000..09080ac25 --- /dev/null +++ b/projects/spectral_complex/CMakeLists.txt @@ -0,0 +1,180 @@ +# SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +# SPDX-License-Identifier: Apache-2.0 + +# spectral_complex: GRIB spectral complex packing (spherical harmonics coefficients: an unpacked +# sub-truncation and simple packing of the other coefficients, scaled with a laplacian operator). +# It uses simple_packing (projects/simple_packing) for the simple packing of the scaled coefficients. +# +# Can be built and installed standalone: +# cmake -S projects/spectral_complex -B build && cmake --build build && ctest --test-dir build +# cmake --install build --prefix +# and consumed with find_package(spectral_complex) -> target spectral_complex::spectral_complex. +# +# ecCodes includes it with add_subdirectory() (see the top-level CMakeLists.txt). + +cmake_minimum_required(VERSION 3.19) + +# The version is defined in include/spectral_complex/version.h +file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/include/spectral_complex/version.h" spectral_complex_version_line + REGEX "^#define SPECTRAL_COMPLEX_VERSION[ \t]+\"[0-9]+\\.[0-9]+\\.[0-9]+\"") # any spaces: clang-format aligns the defines +string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" spectral_complex_version "${spectral_complex_version_line}") +if(NOT spectral_complex_version) + message(FATAL_ERROR "spectral_complex: no version in include/spectral_complex/version.h") +endif() +project(spectral_complex VERSION ${spectral_complex_version} LANGUAGES CXX) + +if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) + set(SPECTRAL_COMPLEX_TOP_LEVEL ON) +else() + set(SPECTRAL_COMPLEX_TOP_LEVEL OFF) +endif() + +option(SPECTRAL_COMPLEX_BUILD_TESTS "Build the spectral_complex tests" ${SPECTRAL_COMPLEX_TOP_LEVEL}) +option(SPECTRAL_COMPLEX_BUILD_BENCHMARKS "Build the spectral_complex benchmarks (benchmarks/)" OFF) +option(SPECTRAL_COMPLEX_BUILD_FUZZERS "Build the spectral_complex libFuzzer fuzzers (requires Clang)" OFF) +option(SPECTRAL_COMPLEX_INSTALL "Install the spectral_complex library, headers and CMake package" ${SPECTRAL_COMPLEX_TOP_LEVEL}) +option(SPECTRAL_COMPLEX_NATIVE_ARCH "Optimise for the host CPU (-march=native): faster, but not portable" ON) + +# libFuzzer + ASan + UBSan instrumentation for the fuzzers and the library code they exercise +if(SPECTRAL_COMPLEX_BUILD_FUZZERS) + if(NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang") + message(FATAL_ERROR "SPECTRAL_COMPLEX_BUILD_FUZZERS requires Clang (found ${CMAKE_CXX_COMPILER_ID})") + endif() + set(SPECTRAL_COMPLEX_FUZZER_COMPILE_OPTIONS -fsanitize=fuzzer,address,undefined -fno-sanitize-recover=undefined -g -O1) + set(SPECTRAL_COMPLEX_FUZZER_LINK_OPTIONS -fsanitize=fuzzer,address,undefined) +endif() + +if(SPECTRAL_COMPLEX_TOP_LEVEL) + set(CMAKE_CXX_STANDARD 17) + set(CMAKE_CXX_STANDARD_REQUIRED ON) + set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +endif() + +include(GNUInstallDirs) + +# --- simple_packing: the simple packing of the scaled coefficients --- +# In ecCodes the target already exists (projects/simple_packing is added first). Standalone: an +# installed simple_packing, else the copy next to this project (installed with this project if +# SPECTRAL_COMPLEX_INSTALL is on). +set(SPECTRAL_COMPLEX_BUNDLED_SIMPLE_PACKING OFF) +if(NOT TARGET simple_packing::simple_packing) + find_package(simple_packing 0.0 QUIET) + if(NOT simple_packing_FOUND) + if(NOT EXISTS ${PROJECT_SOURCE_DIR}/../simple_packing/CMakeLists.txt) + message(FATAL_ERROR "spectral_complex needs simple_packing: install it or build next to projects/simple_packing") + endif() + set(SIMPLE_PACKING_BUILD_TESTS OFF) + set(SIMPLE_PACKING_INSTALL ${SPECTRAL_COMPLEX_INSTALL}) + set(SIMPLE_PACKING_NATIVE_ARCH ${SPECTRAL_COMPLEX_NATIVE_ARCH}) + add_subdirectory(${PROJECT_SOURCE_DIR}/../simple_packing ${PROJECT_BINARY_DIR}/simple_packing) + set(SPECTRAL_COMPLEX_BUNDLED_SIMPLE_PACKING ON) + endif() +endif() + +# Optimisation flags for the packing loops (also used for the tests): -O3, the floating-point +# options that this compiler needs (cmake/spectral_complexFloatingPoint.cmake: AUTO, ON or OFF per +# option) and -march=native (SPECTRAL_COMPLEX_NATIVE_ARCH) +include(CheckCXXCompilerFlag) +set(SPECTRAL_COMPLEX_ARCH_FLAGS "") +if(SPECTRAL_COMPLEX_NATIVE_ARCH AND NOT CMAKE_CROSSCOMPILING) + check_cxx_compiler_flag("-march=native" SPECTRAL_COMPLEX_HAVE_MARCH_NATIVE) + if(SPECTRAL_COMPLEX_HAVE_MARCH_NATIVE) + set(SPECTRAL_COMPLEX_ARCH_FLAGS -march=native -mtune=native) + endif() +endif() +include(${PROJECT_SOURCE_DIR}/cmake/spectral_complexFloatingPoint.cmake) +spectral_complex_floating_point_flags(${SPECTRAL_COMPLEX_ARCH_FLAGS}) +# MSVC has no -O3: /O2 (its highest optimisation level) +if(MSVC) + set(SPECTRAL_COMPLEX_OPT_LEVEL /O2) +else() + set(SPECTRAL_COMPLEX_OPT_LEVEL -O3) +endif() +set(SPECTRAL_COMPLEX_OPT_FLAGS ${SPECTRAL_COMPLEX_OPT_LEVEL} ${SPECTRAL_COMPLEX_FP_FLAGS} ${SPECTRAL_COMPLEX_ARCH_FLAGS}) +if(NOT SPECTRAL_COMPLEX_TOP_LEVEL) + set(SPECTRAL_COMPLEX_OPT_FLAGS ${SPECTRAL_COMPLEX_OPT_FLAGS} PARENT_SCOPE) + set(SPECTRAL_COMPLEX_FP_SAFETY_FLAGS ${SPECTRAL_COMPLEX_FP_SAFETY_FLAGS} PARENT_SCOPE) + set(SPECTRAL_COMPLEX_FP_LINK_FLAGS ${SPECTRAL_COMPLEX_FP_LINK_FLAGS} PARENT_SCOPE) +endif() + +# --- spectral_complex::headers: the public headers --- + +add_library(spectral_complex_headers INTERFACE) +add_library(spectral_complex::headers ALIAS spectral_complex_headers) +set_target_properties(spectral_complex_headers PROPERTIES EXPORT_NAME headers) +target_include_directories(spectral_complex_headers INTERFACE + $ + $) +target_compile_features(spectral_complex_headers INTERFACE cxx_std_17) +target_link_libraries(spectral_complex_headers INTERFACE simple_packing::headers) +# Users get the results of the project's own builds: the floating-point options that this compiler +# needs for correct results (SPECTRAL_COMPLEX_FP_SAFETY_FLAGS; the header code is compiled with the +# user's flags). Not -fno-trapping-math, which only affects the speed. +foreach(sc_flag IN LISTS SPECTRAL_COMPLEX_FP_SAFETY_FLAGS) + target_compile_options(spectral_complex_headers INTERFACE $<$:${sc_flag}>) +endforeach() +target_link_options(spectral_complex_headers INTERFACE ${SPECTRAL_COMPLEX_FP_LINK_FLAGS}) + +# --- Compiled sources: an object library, so that ecCodes can embed them --- + +add_library(spectral_complex_objects OBJECT + src/Float.cc + src/Operator.cc) +target_link_libraries(spectral_complex_objects PUBLIC spectral_complex_headers) +set_target_properties(spectral_complex_objects PROPERTIES POSITION_INDEPENDENT_CODE ON) +target_compile_options(spectral_complex_objects PRIVATE ${SPECTRAL_COMPLEX_OPT_FLAGS}) +target_compile_definitions(spectral_complex_objects PRIVATE NDEBUG) + +if(SPECTRAL_COMPLEX_BUILD_FUZZERS) + # The fuzzers need the library itself instrumented (they are built standalone, with the + # tests switched off, since the instrumented objects cannot be linked uninstrumented) + target_compile_options(spectral_complex_objects PRIVATE ${SPECTRAL_COMPLEX_FUZZER_COMPILE_OPTIONS}) +endif() + +# --- spectral_complex::spectral_complex: the library --- + +add_library(spectral_complex STATIC $) +add_library(spectral_complex::spectral_complex ALIAS spectral_complex) +target_link_libraries(spectral_complex PUBLIC spectral_complex_headers simple_packing::simple_packing) + +if(SPECTRAL_COMPLEX_BUILD_TESTS) + if(SPECTRAL_COMPLEX_TOP_LEVEL) + enable_testing() + endif() + add_subdirectory(tests) +endif() + +# --- libFuzzer fuzzers (Clang only; see SPECTRAL_COMPLEX_FUZZER_* options above) --- + +if(SPECTRAL_COMPLEX_BUILD_FUZZERS) + add_subdirectory(tests/fuzz) +endif() + +# --- Benchmarks (an overview of the speed; see benchmarks/) --- + +if(SPECTRAL_COMPLEX_BUILD_BENCHMARKS) + add_subdirectory(benchmarks) +endif() + +# --- Installation --- + +if(SPECTRAL_COMPLEX_INSTALL) + include(CMakePackageConfigHelpers) + set(SPECTRAL_COMPLEX_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake/spectral_complex) + + install(DIRECTORY include/spectral_complex DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + install(TARGETS spectral_complex_headers spectral_complex EXPORT spectral_complexTargets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) + install(EXPORT spectral_complexTargets NAMESPACE spectral_complex:: DESTINATION ${SPECTRAL_COMPLEX_CMAKE_DIR}) + + configure_package_config_file(cmake/spectral_complexConfig.cmake.in + ${PROJECT_BINARY_DIR}/spectral_complexConfig.cmake + INSTALL_DESTINATION ${SPECTRAL_COMPLEX_CMAKE_DIR}) + write_basic_package_version_file(${PROJECT_BINARY_DIR}/spectral_complexConfigVersion.cmake + COMPATIBILITY SameMinorVersion) # before 1.0.0 a new minor version may change the interface + install(FILES + ${PROJECT_BINARY_DIR}/spectral_complexConfig.cmake + ${PROJECT_BINARY_DIR}/spectral_complexConfigVersion.cmake + DESTINATION ${SPECTRAL_COMPLEX_CMAKE_DIR}) + install(FILES LICENSE CHANGELOG.md README.md DESTINATION ${CMAKE_INSTALL_DOCDIR}) +endif() diff --git a/projects/spectral_complex/LICENSE b/projects/spectral_complex/LICENSE new file mode 100755 index 000000000..b55ed3557 --- /dev/null +++ b/projects/spectral_complex/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2005- ECMWF + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/projects/spectral_complex/README.md b/projects/spectral_complex/README.md new file mode 100644 index 000000000..8c2b3e767 --- /dev/null +++ b/projects/spectral_complex/README.md @@ -0,0 +1,122 @@ + + +# spectral_complex + +spectral_complex is a C++17 library for GRIB spectral complex packing [1] of spherical harmonics +coefficients. The coefficients of the sub-truncation JS are stored unpacked; all other coefficients +are multiplied by `(n(n+1))^P`, P being the laplacian operator, and packed with simple packing +(`projects/simple_packing`): `Y * 10^D = R + X * 2^E`. + +Version 0.0.1 (`sc::version()`, `SPECTRAL_COMPLEX_VERSION` in `spectral_complex/version.h`). Before +version 1.0.0 the interface may still change. + +## Features + +- One header, `spectral_complex/spectral_complex.h`, with `sc::laplacianOperator`, + `sc::parameters`, `sc::pack`, `sc::unpack`, `sc::Layout` (truncation J and sub-truncation JS), + `sc::Parameters` and `sc::Method`. +- Triangular truncations (J = K = M), coefficients in ecCodes order: m = 0..J, n = m..J, a real and + an imaginary part each, `(J + 1) * (J + 2)` values. +- The laplacian operator of legacy ecCodes: a weighted least squares fit of the row norms, with + GRIB-172 (one packed row: P = 1) and ECC-2393 (a very steep spectrum: refit on the real norms, + else the largest operator that keeps the scaled coefficients codable). +- Unpacked coefficients as IEEE32 or IEEE64 (GRIB2) or IBM32 (GRIB1) floats; packed coefficients + with 1 to 63 bits per value, IEEE (GRIB2) or IBM (GRIB1) reference values. +- Two ways to choose the scaling, as in ecCodes: + - `sc::Method::bits(n, D)`: the bits per value and the decimal scale factor are given + (`optimizeScaleFactor=0`). + - `sc::Method::bestPrecision(n)`: the best use of n bits (`optimizeScaleFactor=1`). +- Unpacking to `double` and `float` (floats: the doubles converted, as `codes_get_float_array`). +- The packed data are byte-identical to legacy ecCodes and the decoded values bit-identical, with + all its details: the ECMWF GRIBEX sh bug, the underflow of the binary scale factor (all codes 0), + JS = J (all coefficients unpacked), the zero imaginary part of m = 0. +- Errors are exceptions: `std::invalid_argument`, `std::range_error`, `std::length_error`. Where + legacy ecCodes failed an assertion (a value that cannot be coded) or coded garbage (NaN), the + library throws. + +## Usage + +```cpp +#include "spectral_complex/spectral_complex.h" + +const sc::Layout layout{ 1279, 20 }; // T1279, sub-truncation 20 +std::vector values(sc::valueCount(layout)); // the coefficients, in ecCodes order +double P = sc::laplacianOperator(values, layout); +sc::Parameters p = sc::parameters(values, layout, P, sc::Method::bits(16)); +std::vector packed = sc::pack(values, p); +std::vector back = sc::unpack(packed, p); +``` + +The packed data contain no parameters. To unpack a message, fill in `sc::Parameters` from its keys: +the layout, the laplacian operator as the message stores it, the scaling (`referenceValue`, +`binaryScaleFactor`, `decimalScaleFactor`, `bitsPerValue`), the format of the unpacked coefficients +and the GRIBEX bug. + +- Messages store the operator rounded (GRIB1 in thousandths, GRIB2 in millionths): pass the stored + value to `sc::parameters`, so that packing and unpacking use the same. +- A packed coefficient of row n is restored to within one step `2^E * 10^-D / (n(n+1))^P`; the + unpacked ones to the precision of their format. + +For GRIB edition 1, use IBM floats: +`sc::parameters(values, layout, P, sc::Method::bits(16).referenceFormat(sc::ReferenceFormat::IBM32), sc::UnpackedFormat::IBM32)`. + +Everything in `spectral_complex/detail` (namespace `sc::detail`) is internal. + +## Build and test + +```sh +cmake -S projects/spectral_complex -B build -G Ninja +cmake --build build +ctest --test-dir build +``` + +spectral_complex needs simple_packing: an installed one (`find_package(simple_packing)`), else +`projects/simple_packing` next to it, which is then built (and installed) with it. + +CMake targets: `spectral_complex::spectral_complex` and `spectral_complex::headers`. Options: +`SPECTRAL_COMPLEX_BUILD_TESTS`, `SPECTRAL_COMPLEX_BUILD_FUZZERS` (Clang), +`SPECTRAL_COMPLEX_INSTALL`, `SPECTRAL_COMPLEX_NATIVE_ARCH` (`-march=native`, default on), and the +floating-point options below. + +The tests compare the library with a frozen copy of the legacy ecCodes code +(`tests/legacy_reference.h`): the laplacian operator, the float codes, and packing and unpacking +over a matrix of truncations, sub-truncations, bits per value, formats, decimal scale factors and +spectra. The regression tests cover ECC-2393, GRIB-172, zero-padded fields, JS = J, the underflow +and the GRIBEX bug. + +`-DSPECTRAL_COMPLEX_BUILD_BENCHMARKS=ON` builds `benchmarks/sc_bench`, an overview of the speed of +packing and unpacking. + +## Floating-point compiler options + +spectral_complex must round floating-point values in exactly the same way on every compiler and CPU, +and as legacy ecCodes. It compiles with the options of simple_packing, with the same meaning: + +| Option | CMake variable | Why | +|---|---|---| +| `-ffp-contract=off` | `SPECTRAL_COMPLEX_FP_CONTRACT_OFF` | Correct results: no fused multiply-add, which rounds differently | +| `-fno-fast-math` | `SPECTRAL_COMPLEX_NO_FAST_MATH` | Correct results: keeps the checks for NaN and infinity (icx/icpx use fast math by default) | +| `-fno-trapping-math` | `SPECTRAL_COMPLEX_NO_TRAPPING_MATH` | Speed | + +Each variable can be `ON` (default), `AUTO` (only with the compilers that need it) or `OFF`. Your own +code that includes the headers gets `-ffp-contract=off` and `-fno-fast-math` through the CMake +targets. + +## Performance + +See `benchmarks/` (filled in with the measurements of `sc_bench` and the ecCodes API). + +## In ecCodes + +- `ECCODES_USE_SC=1` selects spectral_complex for GRIB spectral complex packing + (`data_g1complex_packing`, `data_g2complex_packing`); the legacy code is the default. + +## References + +1. WMO. *Manual on Codes, Volume I.2: International Codes, Part B – Binary Codes* (WMO-No. 306). + Geneva: World Meteorological Organization. GRIB edition 2: data representation template 5.51 + (spherical harmonics, complex packing); GRIB edition 1: binary data section, complex packing of + spherical harmonics. diff --git a/projects/spectral_complex/cmake/spectral_complexConfig.cmake.in b/projects/spectral_complex/cmake/spectral_complexConfig.cmake.in new file mode 100644 index 000000000..67f197dee --- /dev/null +++ b/projects/spectral_complex/cmake/spectral_complexConfig.cmake.in @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +# SPDX-License-Identifier: Apache-2.0 + +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) +find_dependency(simple_packing 0.0) + +include("${CMAKE_CURRENT_LIST_DIR}/spectral_complexTargets.cmake") + +check_required_components(spectral_complex) diff --git a/projects/spectral_complex/cmake/spectral_complexFloatingPoint.cmake b/projects/spectral_complex/cmake/spectral_complexFloatingPoint.cmake new file mode 100644 index 000000000..a1229ebac --- /dev/null +++ b/projects/spectral_complex/cmake/spectral_complexFloatingPoint.cmake @@ -0,0 +1,221 @@ +# SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +# SPDX-License-Identifier: Apache-2.0 +# +# Floating-point compiler options of spectral_complex (see README.md, "Floating-point compiler options"). +# +# Spectral complex packing scales floating-point values to integers and computes the packing parameters: the +# results must be rounded exactly as written (bit-identical on every compiler and CPU, and to the +# legacy ecCodes code), and the checks for NaN and infinite values must not be optimised away. +# Each option is a cache variable with the values ON (the default), AUTO and OFF. +# ON adds the option for every compiler that accepts it: where it is not needed it restates the +# default and changes nothing (measured: no cost), and the results do not depend on the probes and +# compiler lists of AUTO. AUTO enables an option only for the compilers that need it; OFF never. +# +# Measured performance impact of each option alone (AMD Zen 3; GCC 16, Clang 22, icx 2026.2; +# -O3, -march=native and -march=x86-64; 7 GRIB fields, 47.8 MiB, cold caches; differences within +# about +-3 % are measurement noise): +# +# -fno-fast-math packing and unpacking: none. +# Correctness: keeps the checks for NaN and infinity and exact rounding. +# AUTO: on for icx/icpx (IntelLLVM) and icc (Intel): their default floating- +# point model (-fp-model=fast) allows unsafe optimisations (in the attack +# tests, 1736 of 7103 cases changed). A -ffast-math in CMAKE_CXX_FLAGS is not +# undone: configure warns, the tests fail; set SPECTRAL_COMPLEX_NO_FAST_MATH=ON. +# -ffp-contract=off packing and unpacking: none (+-3 %). +# Correctness: without it, compilers fuse (x * 10^D - R) * 2^-E into +# multiply-adds where the CPU has them, which round differently: the coded +# values would depend on the compiler and the CPU. +# AUTO: on if a probe compiled with the project flags fuses a * b - c. That is +# GCC (default -ffp-contract=fast), Clang >= 14 (default "on") and icx/icpx +# (fast and precise models) on CPUs with fused multiply-add: -march=native or +# -march=haswell and later on x86-64; always on AArch64, POWER and s390x. When +# cross-compiling (the probe cannot run): on for GCC, Clang and IntelLLVM. +# -fno-trapping-math packing: GCC +2 to +5 %, unpacking unchanged; Clang and icx/icpx none +# (their default already). Performance only: GCC's default -ftrapping-math +# keeps it from vectorising the range checks of the values. Spectral complex packing does +# not use floating-point exception flags. AUTO: on for GCC. +# +# -fno-fast-math is also a link option (SPECTRAL_COMPLEX_FP_LINK_FLAGS): linking with -ffast-math (GCC, Clang: +# crtfastmath.o) or with icx/icpx sets the CPU to flush subnormal numbers to zero, which +# -fno-fast-math at compile time does not undo. +# +# Defines SPECTRAL_COMPLEX_FP_FLAGS (all enabled options, in this order: -fno-fast-math, -fno-trapping-math, +# -ffp-contract=off; Clang and icx reset the contraction with -fno-fast-math) and +# SPECTRAL_COMPLEX_FP_SAFETY_FLAGS (the options needed for correct results, for the usage requirements of +# spectral_complex::headers and for code that does the same arithmetic). + +include(CheckCXXCompilerFlag) +include(CheckCXXSourceCompiles) +include(CheckCXXSourceRuns) +include(CheckLinkerFlag) + +set(SPECTRAL_COMPLEX_NO_FAST_MATH ON CACHE STRING "Compile with -fno-fast-math: ON (default), AUTO (icx/icpx, icc) or OFF") +set(SPECTRAL_COMPLEX_FP_CONTRACT_OFF ON CACHE STRING "Compile with -ffp-contract=off: ON (default), AUTO (compilers that fuse multiply-adds) or OFF") +set(SPECTRAL_COMPLEX_NO_TRAPPING_MATH ON CACHE STRING "Compile with -fno-trapping-math: ON (default), AUTO (GCC: faster) or OFF") +foreach(sc_option SPECTRAL_COMPLEX_NO_FAST_MATH SPECTRAL_COMPLEX_FP_CONTRACT_OFF SPECTRAL_COMPLEX_NO_TRAPPING_MATH) + set_property(CACHE ${sc_option} PROPERTY STRINGS ON AUTO OFF) + if(NOT ${sc_option} MATCHES "^(AUTO|ON|OFF)$") + message(FATAL_ERROR "${sc_option} must be ON, AUTO or OFF (it is ${${sc_option}})") + endif() +endforeach() + +# The compiler flags of each configuration (CMAKE_CXX_FLAGS_: all configurations of a +# multi-configuration generator, else CMAKE_BUILD_TYPE), followed by the flags the project adds: the +# probes below compile with what the build compiles with (CMAKE_CXX_FLAGS are added by the checks) +function(spectral_complex_configuration_flags out) + if(CMAKE_CONFIGURATION_TYPES) + set(configs ${CMAKE_CONFIGURATION_TYPES}) + else() + set(configs "${CMAKE_BUILD_TYPE}") + endif() + set(result "") + foreach(config IN LISTS configs) + string(TOUPPER "${config}" upper) + list(APPEND result "${CMAKE_CXX_FLAGS_${upper}}") + endforeach() + set(${out} "${result}" PARENT_SCOPE) +endfunction() + +# spectral_complex_floating_point_flags(): sets SPECTRAL_COMPLEX_FP_FLAGS and SPECTRAL_COMPLEX_FP_SAFETY_FLAGS in the +# caller's scope; (e.g. -march=native) are used by the contraction probe +function(spectral_complex_floating_point_flags) + set(arch_flags ${ARGN}) + set(flags "") + set(safety "") + set(link_flags "") + set(reasons "") + + # -fno-fast-math + unset(reason) + set(enable OFF) + if(SPECTRAL_COMPLEX_NO_FAST_MATH STREQUAL "ON") + set(enable ON) + elseif(SPECTRAL_COMPLEX_NO_FAST_MATH STREQUAL "AUTO" AND CMAKE_CXX_COMPILER_ID MATCHES "^(IntelLLVM|Intel)$") + set(enable ON) + set(reason "-fno-fast-math (the default floating-point model of ${CMAKE_CXX_COMPILER_ID} is fast)") + elseif(CMAKE_CXX_COMPILER_ID MATCHES "^(IntelLLVM|Intel)$" AND NOT CMAKE_CXX_FLAGS MATCHES "-fp-model|-fno-fast-math") + message(WARNING "spectral_complex: SPECTRAL_COMPLEX_NO_FAST_MATH=OFF with ${CMAKE_CXX_COMPILER_ID}, whose default floating-point " + "model is fast (it defines no macro to check): the results may differ and the tests fail. " + "Configure with -DSPECTRAL_COMPLEX_NO_FAST_MATH=ON (the default) or AUTO.") + endif() + if(enable) + check_cxx_compiler_flag(-fno-fast-math SPECTRAL_COMPLEX_HAVE_NO_FAST_MATH) + if(SPECTRAL_COMPLEX_HAVE_NO_FAST_MATH) + list(APPEND flags -fno-fast-math) + list(APPEND safety -fno-fast-math) + if(DEFINED reason) + list(APPEND reasons "${reason}") + endif() + else() + message(STATUS "spectral_complex: the compiler does not accept -fno-fast-math: not added") + endif() + check_linker_flag(CXX -fno-fast-math SPECTRAL_COMPLEX_LINKER_HAS_NO_FAST_MATH) + if(SPECTRAL_COMPLEX_LINKER_HAS_NO_FAST_MATH) + set(link_flags -fno-fast-math) + endif() + endif() + + # -fno-trapping-math + unset(reason) + set(enable OFF) + if(SPECTRAL_COMPLEX_NO_TRAPPING_MATH STREQUAL "ON") + set(enable ON) + elseif(SPECTRAL_COMPLEX_NO_TRAPPING_MATH STREQUAL "AUTO" AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(enable ON) + set(reason "-fno-trapping-math (GCC vectorises the range checks only with it)") + endif() + if(enable) + check_cxx_compiler_flag(-fno-trapping-math SPECTRAL_COMPLEX_HAVE_NO_TRAPPING_MATH) + if(SPECTRAL_COMPLEX_HAVE_NO_TRAPPING_MATH) + list(APPEND flags -fno-trapping-math) + if(DEFINED reason) + list(APPEND reasons "${reason}") + endif() + else() + message(STATUS "spectral_complex: the compiler does not accept -fno-trapping-math: not added") + endif() + endif() + + # -ffp-contract=off: AUTO probes whether the compiler fuses a * b - c with the flags of the build + unset(reason) + set(enable OFF) + spectral_complex_configuration_flags(config_flags) + if(SPECTRAL_COMPLEX_FP_CONTRACT_OFF STREQUAL "ON") + set(enable ON) + elseif(SPECTRAL_COMPLEX_FP_CONTRACT_OFF STREQUAL "AUTO") + if(CMAKE_CROSSCOMPILING AND NOT CMAKE_CROSSCOMPILING_EMULATOR) + if(CMAKE_CXX_COMPILER_ID MATCHES "^(GNU|Clang|AppleClang|IntelLLVM)$") + set(enable ON) + set(reason "-ffp-contract=off (cross-compiling: ${CMAKE_CXX_COMPILER_ID} contracts by default where the target has fused multiply-add)") + endif() + else() + # a * b rounds to 1 (2^-54 is lost); fused, a * b - c is -2^-54. The result is compared as a + # bit pattern: with -ffast-math a floating-point comparison could be folded away. + foreach(config_flag_set IN LISTS config_flags) + string(MD5 key "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_FLAGS} ${config_flag_set} ${arch_flags} ${flags}") + set(CMAKE_REQUIRED_FLAGS "${config_flag_set} -O3 ${flags} ${arch_flags}") + string(REPLACE ";" " " CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") + set(CMAKE_REQUIRED_QUIET ON) + check_cxx_source_runs(" + #include + #include + volatile double a = 1.0 + 0x1p-27, b = 1.0 - 0x1p-27, c = 1.0; + int main() + { + const double x = a, y = b, z = c; + const double r = x * y - z; + std::uint64_t bits = 0; + std::memcpy(&bits, &r, sizeof(bits)); + return bits == 0 ? 0 : 1; + }" + SPECTRAL_COMPLEX_NOT_CONTRACTING_${key}) + if(NOT SPECTRAL_COMPLEX_NOT_CONTRACTING_${key}) + set(enable ON) + set(reason "-ffp-contract=off (the compiler fuses multiply-adds with these flags)") + endif() + endforeach() + endif() + endif() + if(enable) + check_cxx_compiler_flag(-ffp-contract=off SPECTRAL_COMPLEX_HAVE_FP_CONTRACT_OFF) + if(SPECTRAL_COMPLEX_HAVE_FP_CONTRACT_OFF) + list(APPEND flags -ffp-contract=off) + list(APPEND safety -ffp-contract=off) + if(DEFINED reason) + list(APPEND reasons "${reason}") + endif() + else() + message(STATUS "spectral_complex: the compiler does not accept -ffp-contract=off: not added") + endif() + endif() + + # A -ffast-math (or -ffinite-math-only) of the user that the flags above do not undo, with the flags + # of the build (a later -O level undoes -Ofast, but not -ffast-math) + foreach(config_flag_set IN LISTS config_flags) + string(MD5 key "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_FLAGS} ${config_flag_set} ${flags}") + set(CMAKE_REQUIRED_FLAGS "${config_flag_set} -O3 ${flags}") + string(REPLACE ";" " " CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") + set(CMAKE_REQUIRED_QUIET ON) + check_cxx_source_compiles(" + #if defined(__FAST_MATH__) || (defined(__FINITE_MATH_ONLY__) && __FINITE_MATH_ONLY__) + #error fast math + #endif + int main() { return 0; }" SPECTRAL_COMPLEX_NO_FAST_MATH_IN_EFFECT_${key}) + if(NOT SPECTRAL_COMPLEX_NO_FAST_MATH_IN_EFFECT_${key}) + message(WARNING "spectral_complex: the compiler flags (CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}; of the configuration: " + "${config_flag_set}) enable -ffast-math or -ffinite-math-only. Spectral complex packing then cannot detect NaN " + "and infinite values and may round differently: the tests fail. Configure with " + "-DSPECTRAL_COMPLEX_NO_FAST_MATH=ON (the default; adds -fno-fast-math) or remove the option.") + break() + endif() + endforeach() + + if(reasons) + string(REPLACE ";" ", " text "${reasons}") + message(STATUS "spectral_complex: floating-point options enabled automatically: ${text}") + endif() + message(STATUS "spectral_complex: floating-point options: ${flags}") + set(SPECTRAL_COMPLEX_FP_FLAGS ${flags} PARENT_SCOPE) + set(SPECTRAL_COMPLEX_FP_SAFETY_FLAGS ${safety} PARENT_SCOPE) + set(SPECTRAL_COMPLEX_FP_LINK_FLAGS ${link_flags} PARENT_SCOPE) +endfunction() diff --git a/projects/spectral_complex/include/spectral_complex/detail/Float.h b/projects/spectral_complex/include/spectral_complex/detail/Float.h new file mode 100644 index 000000000..6e17235e2 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/detail/Float.h @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// The 32-bit IEEE and IBM floats of the unpacked coefficients, coded exactly as legacy ecCodes +// (grib_ieee_to_long, grib_long_to_ieee, grib_ibm_to_long, grib_long_to_ibm). These differ from a +// conversion by the compiler: the mantissa is rounded half up, numbers below the smallest normal +// number are coded as (signed) zero, and an IEEE number with exponent 0 (denormal) decodes as if its +// exponent were 1 with the implicit bit set. + +#pragma once + +#include +#include +#include + +namespace sc::detail +{ + +// IEEE 754 single precision bits of x, as legacy ecCodes codes them. Throws std::range_error if +// |x| is larger than the largest float or x is NaN. +uint32_t ieee32Code(double x); + +// The value of the IEEE 754 single precision bits, as legacy ecCodes decodes them +double ieee32Value(uint32_t code); + +// IBM single precision bits of x, as legacy ecCodes codes them. Throws std::range_error if |x| is +// larger than the largest IBM float or x is NaN. +uint32_t ibm32Code(double x); + +// The value of the IBM single precision bits, as legacy ecCodes decodes them +double ibm32Value(uint32_t code); + +// The largest IEEE and IBM single precision numbers +double ieee32Max(); +double ibm32Max(); + +// IEEE 754 double precision bits of x (its memory representation) +inline uint64_t ieee64Code(double x) +{ + uint64_t code = 0; + std::memcpy(&code, &x, sizeof code); + return code; +} + +inline double ieee64Value(uint64_t code) +{ + double x = 0; + std::memcpy(&x, &code, sizeof x); + return x; +} + +// Big-endian stores and loads of 4 and 8 bytes (the byte order of GRIB) +inline void storeBigEndian32(uint8_t* p, uint32_t v) +{ + p[0] = static_cast(v >> 24); + p[1] = static_cast(v >> 16); + p[2] = static_cast(v >> 8); + p[3] = static_cast(v); +} + +inline void storeBigEndian64(uint8_t* p, uint64_t v) +{ + storeBigEndian32(p, static_cast(v >> 32)); + storeBigEndian32(p + 4, static_cast(v)); +} + +inline uint32_t loadBigEndian32(const uint8_t* p) +{ + return (static_cast(p[0]) << 24) | (static_cast(p[1]) << 16) | (static_cast(p[2]) << 8) | + static_cast(p[3]); +} + +inline uint64_t loadBigEndian64(const uint8_t* p) +{ + return (static_cast(loadBigEndian32(p)) << 32) | loadBigEndian32(p + 4); +} + +} // namespace sc::detail diff --git a/projects/spectral_complex/include/spectral_complex/detail/Operator.h b/projects/spectral_complex/include/spectral_complex/detail/Operator.h new file mode 100644 index 000000000..6b1f7e325 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/detail/Operator.h @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// The laplacian operator P of a spectral field, as legacy ecCodes computes it (calculate_pfactor +// in src/eccodes/accessor/DataComplexPacking.cc) + +#pragma once + +#include +#include + +namespace sc::detail +{ + +// The laplacian operator for the coefficients of truncation J with the unpacked sub-truncation JS +// (values in ecCodes order, (J + 1) * (J + 2) of them): +// - a weighted least squares fit of log(norm(n)) over log(n(n + 1)) for the rows n = JS + 1 .. J + 1, +// where norm(n) is the largest absolute coefficient of row n; rows below 1e-15 get a negligible weight +// - GRIB-172: 1 if fewer than two rows can be fitted (J - JS <= 1) +// - ECC-2393: if the fitted operator would make the scaled coefficients overflow, a fit on the real +// norms (only zero rows ignored), and if that is still too large the largest operator that keeps +// the scaled coefficients below 1e30 +// - limited to [-9999.9, 9999.9] +double laplacianOperator(const double* values, int32_t truncation, int32_t subTruncation); + +} // namespace sc::detail diff --git a/projects/spectral_complex/include/spectral_complex/spectral_complex.h b/projects/spectral_complex/include/spectral_complex/spectral_complex.h new file mode 100644 index 000000000..d6bfc7a72 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/spectral_complex.h @@ -0,0 +1,500 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// spectral_complex: GRIB spectral complex packing of spherical harmonics coefficients. +// +// The coefficients of a triangular truncation J are ordered as in ecCodes: m = 0..J, then +// n = m..J, a real and an imaginary part each: (J + 1) * (J + 2) values. The coefficients of the +// sub-truncation JS (n <= JS) are stored unpacked, as 32-bit IEEE or IBM floats or 64-bit IEEE +// floats. All other coefficients are multiplied by (n(n + 1))^P, P being the laplacian operator, +// and packed with simple packing (projects/simple_packing): Y * 10^D = R + X * 2^E. +// The packed data are byte-identical to legacy ecCodes. +// +// Everything in spectral_complex/detail (namespace sc::detail) is internal. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "simple_packing/simple_packing.h" +// sc::version() for the users of this header +#include "spectral_complex/version.h" // IWYU pragma: export +#include "spectral_complex/detail/Float.h" +#include "spectral_complex/detail/Operator.h" + +namespace sc +{ + +// The format of the reference value of the packed coefficients: IEEE32 (GRIB2) or IBM32 (GRIB1) +using ReferenceFormat = sp::ReferenceFormat; + +// The truncation J and the sub-truncation JS (0 <= JS <= J) of a field. Only triangular +// truncations (J = K = M) are supported, as in ecCodes. +struct Layout +{ + int32_t truncation = 0; + int32_t subTruncation = 0; +}; + +// The format of the unpacked coefficients (ecCodes key ieee_floats: 0 = IBM32, 1 = IEEE32, 2 = IEEE64) +enum class UnpackedFormat +{ + IEEE32, + IEEE64, + IBM32 +}; + +// How the scaling of the packed coefficients is chosen +class Method +{ +public: + // The bits per value and the decimal scale factor are given; the reference value and the binary + // scale factor follow (ecCodes: optimizeScaleFactor=0) + static Method bits(int32_t bitsPerValue, int32_t decimalScaleFactor = 0) { return Method(false, bitsPerValue, decimalScaleFactor); } + // The best use of the given bits per value: decimal and binary scale factor (optimizeScaleFactor=1) + static Method bestPrecision(int32_t bitsPerValue) { return Method(true, bitsPerValue, 0); } + + // Returns a copy with the given format of the reference value (default IEEE32) + Method referenceFormat(ReferenceFormat format) const + { + Method m = *this; + m.referenceFormat_ = format; + return m; + } + +private: + Method(bool bestPrecision, int32_t bitsPerValue, int32_t decimalScaleFactor) : + bestPrecision_(bestPrecision), bitsPerValue_(bitsPerValue), decimalScaleFactor_(decimalScaleFactor) + { + } + + bool bestPrecision_; + int32_t bitsPerValue_; + int32_t decimalScaleFactor_; + ReferenceFormat referenceFormat_ = ReferenceFormat::IEEE32; + + friend struct Parameters parameters(const double* values, size_t count, const Layout& layout, double laplacianOperator, + const Method& method, UnpackedFormat unpackedFormat, bool gribexShBug); +}; + +// Everything needed to pack and unpack a field. sc::parameters fills it in for packing; to unpack +// a message, fill it in from the keys of the message. +struct Parameters +{ + Layout layout; + // The laplacian operator P as the message stores it (GRIB1 and GRIB2 round it) + double laplacianOperator = 0; + // The simple packing of the scaled coefficients (reference value, binary and decimal scale + // factor, bits per value) + sp::Scaling scaling; + // The format of the unpacked coefficients (value-initialised: IEEE32) + UnpackedFormat unpackedFormat{}; + // ECMWF GRIBEX bug: the last unpacked coefficient of each m is stored scaled (ecCodes key + // GRIBEXShBugPresent) + bool gribexShBug = false; + // The scaled coefficients are too close to each other for any binary scale factor >= -127 (an + // underflow): legacy ecCodes then codes them all as 0 with R = 0 and E = 0 (only for packing) + bool zeroCodes = false; +}; + +namespace detail +{ + +[[noreturn]] inline void invalid(const std::string& what) +{ + throw std::invalid_argument("Spectral complex packing: " + what); +} + +inline void checkLayout(const Layout& layout) +{ + if (layout.truncation < 0 || layout.truncation > 65535 * 64) { + invalid("the truncation " + std::to_string(layout.truncation) + " is out of range"); + } + if (layout.subTruncation < 0 || layout.subTruncation > layout.truncation) { + invalid("the sub-truncation " + std::to_string(layout.subTruncation) + " must be between 0 and the truncation " + + std::to_string(layout.truncation)); + } +} + +inline size_t bytesOf(UnpackedFormat format) +{ + return format == UnpackedFormat::IEEE64 ? 8 : 4; +} + +inline void checkCount(const char* what, size_t count, size_t expected) +{ + if (count != expected) { + invalid(std::string(what) + ": " + std::to_string(count) + " values, the truncation needs " + std::to_string(expected)); + } +} + +// (n(n + 1))^P for n = 0..J (0 for n = 0), as legacy ecCodes packs +inline std::vector packingFactors(int32_t truncation, double laplacianOperator) +{ + std::vector scals(static_cast(truncation) + 1); + scals[0] = 0; + for (size_t n = 1; n < scals.size(); n++) { + scals[n] = std::pow(static_cast(n * (n + 1)), laplacianOperator); + } + return scals; +} + +// 1 / (n(n + 1))^P in the precision T, as legacy ecCodes unpacks +template +std::vector unpackingFactors(int32_t truncation, T laplacianOperator) +{ + std::vector scals(static_cast(truncation) + 1); + scals[0] = 0; + for (size_t n = 1; n < scals.size(); n++) { + const T operat = static_cast(std::pow(static_cast(n * (n + 1)), static_cast(laplacianOperator))); + scals[n] = operat != 0 ? static_cast(1.0 / operat) : T(0); + } + return scals; +} + +inline sp::Scaling codeScaling(int32_t bitsPerValue) +{ + sp::Scaling s; + s.referenceValue = 0; + s.binaryScaleFactor = 0; + s.decimalScaleFactor = 0; + s.bitsPerValue = bitsPerValue; + return s; +} + +} // namespace detail + +// The number of coefficients of a layout: (J + 1) * (J + 2) +inline size_t valueCount(const Layout& layout) +{ + detail::checkLayout(layout); + const size_t j = static_cast(layout.truncation); + return (j + 1) * (j + 2); +} + +// The number of unpacked coefficients: (JS + 1) * (JS + 2), or all if JS = J +inline size_t unpackedCount(const Layout& layout) +{ + detail::checkLayout(layout); + if (layout.subTruncation == layout.truncation) { + return valueCount(layout); + } + const size_t js = static_cast(layout.subTruncation); + return (js + 1) * (js + 2); +} + +// The number of packed coefficients +inline size_t packedCount(const Layout& layout) +{ + return valueCount(layout) - unpackedCount(layout); +} + +// The size in bytes of the packed data: the unpacked coefficients, then the packed ones +inline size_t packedSize(const Parameters& p) +{ + const size_t unpacked = unpackedCount(p.layout) * detail::bytesOf(p.unpackedFormat); + if (p.layout.subTruncation == p.layout.truncation) { + return unpacked; + } + return unpacked + sp::packedSize(packedCount(p.layout), detail::codeScaling(p.scaling.bitsPerValue)); +} + +// The laplacian operator that legacy ecCodes computes for a field (see detail/Operator.h) +inline double laplacianOperator(const double* values, size_t count, const Layout& layout) +{ + detail::checkCount("laplacianOperator", count, valueCount(layout)); + return detail::laplacianOperator(values, layout.truncation, layout.subTruncation); +} + +inline double laplacianOperator(const std::vector& values, const Layout& layout) +{ + return laplacianOperator(values.data(), values.size(), layout); +} + +// The parameters to pack a field with the given laplacian operator (as the message will store it). +// Throws std::range_error if the scaled coefficients cannot be coded (their reference value or +// their range is too large), std::invalid_argument for invalid arguments. +inline Parameters parameters(const double* values, size_t count, const Layout& layout, double laplacianOperator, const Method& method, + UnpackedFormat unpackedFormat = UnpackedFormat::IEEE32, bool gribexShBug = false) +{ + detail::checkCount("parameters", count, valueCount(layout)); + sp::detail::checkRange("bits per value", method.bitsPerValue_, 1, sp::detail::maxEncodingBitsPerValue); + + Parameters p; + p.layout = layout; + p.laplacianOperator = laplacianOperator; + p.unpackedFormat = unpackedFormat; + p.gribexShBug = gribexShBug; + p.scaling.bitsPerValue = method.bitsPerValue_; + p.scaling.decimalScaleFactor = method.bestPrecision_ ? 0 : method.decimalScaleFactor_; + p.scaling.binaryScaleFactor = 0; + p.scaling.referenceValue = 0; + + const int32_t J = layout.truncation; + const int32_t JS = layout.subTruncation; + if (JS == J) { + return p; // no packed coefficients + } + + // The range of the scaled packed coefficients (without the decimal scaling, as legacy ecCodes) + const std::vector scals = detail::packingFactors(J, laplacianOperator); + double min = 0; + double max = 0; + bool first = true; + bool nan = false; // legacy ecCodes ignores NaN in the range and codes garbage: an error here + size_t i = 0; + for (int32_t m = 0; m <= J; m++) { + int32_t n = m; + if (m <= JS) { + i += 2 * static_cast(JS - m + 1); + n = JS + 1; + } + for (; n <= J; n++) { + for (int k = 0; k < 2; k++) { + const double v = values[i++] * scals[n]; + nan |= std::isnan(v); + if (first) { + min = max = v; + first = false; + } + if (v > max) + max = v; + if (v < min) + min = v; + } + } + } + + // ECC-2393: the scaled coefficients must be codable (reference value and binary scale factor) + const bool ibm = method.referenceFormat_ == ReferenceFormat::IBM32; + const int32_t bpv = method.bitsPerValue_; + { + const double dd = method.bestPrecision_ ? 1.0 : sp::detail::sp_power(method.decimalScaleFactor_, 10); + const double refLimit = 0.5 * (ibm ? detail::ibm32Max() : detail::ieee32Max()); + const double rangeLimit = std::ldexp(sp::detail::sp_power(bpv, 2) - 1, 127); + if (nan || !std::isfinite(min) || !std::isfinite(max) || std::fabs(dd * min) > refLimit || std::fabs(dd * max) > refLimit || + dd * (max - min) > rangeLimit) { + throw std::range_error("Spectral complex packing: the scaled values are out of range (min " + std::to_string(dd * min) + ", max " + + std::to_string(dd * max) + ", laplacian operator " + std::to_string(laplacianOperator) + ")"); + } + } + + if (method.bestPrecision_) { + const sp::Scaling s = sp::scaling(min, max, sp::Method::bestPrecision(bpv).referenceFormat(method.referenceFormat_)); + p.scaling.referenceValue = s.referenceValue; + p.scaling.binaryScaleFactor = s.binaryScaleFactor; + p.scaling.decimalScaleFactor = s.decimalScaleFactor; + return p; + } + + const double d = sp::detail::sp_power(method.decimalScaleFactor_, 10); + const std::optional ref = sp::detail::nearest_smaller_value(d * min, ibm ? sp::detail::FloatType::IBM32 : sp::detail::FloatType::IEEE32); + if (!ref) { + throw std::range_error("Spectral complex packing: no reference value for " + std::to_string(d * min)); + } + const std::optional e = sp::detail::get_binary_scale_factor(d * max, *ref, bpv); + if (!e) { + p.zeroCodes = true; // underflow: R = 0, E = 0, all codes 0 + return p; + } + p.scaling.referenceValue = *ref; + p.scaling.binaryScaleFactor = static_cast(*e); + return p; +} + +inline Parameters parameters(const std::vector& values, const Layout& layout, double laplacianOperator, const Method& method, + UnpackedFormat unpackedFormat = UnpackedFormat::IEEE32, bool gribexShBug = false) +{ + return parameters(values.data(), values.size(), layout, laplacianOperator, method, unpackedFormat, gribexShBug); +} + +// Packs the count = valueCount(layout) coefficients into packedSize(p) bytes of output +inline void pack(const double* values, size_t count, const Parameters& p, uint8_t* output, size_t capacity) +{ + detail::checkCount("pack", count, valueCount(p.layout)); + const size_t size = packedSize(p); + if (capacity < size) { + throw std::length_error("Spectral complex packing: the output buffer is too small (" + std::to_string(capacity) + " bytes, " + + std::to_string(size) + " bytes are needed)"); + } + const int32_t J = p.layout.truncation; + const int32_t JS = p.layout.subTruncation; + const size_t bytes = detail::bytesOf(p.unpackedFormat); + const double d = sp::detail::sp_power(p.scaling.decimalScaleFactor, 10); + + if (JS == J) { + // Everything unpacked: IEEE floats converted by the compiler (as legacy ecCodes, also for GRIB1) + for (size_t i = 0; i < count; i++) { + const double v = values[i] * d; + if (bytes == 4) { + if (std::fabs(v) > static_cast(std::numeric_limits::max())) { + throw std::range_error("Spectral complex packing: the number " + std::to_string(v) + " cannot be coded as an IEEE float"); + } + const float f = static_cast(v); + uint32_t bits = 0; + std::memcpy(&bits, &f, sizeof bits); + detail::storeBigEndian32(output + 4 * i, bits); + } + else { + detail::storeBigEndian64(output + 8 * i, detail::ieee64Code(v)); + } + } + return; + } + + const std::vector scals = detail::packingFactors(J, p.laplacianOperator); + // After an underflow legacy ecCodes scales with d = 0: also the coefficients of the GRIBEX bug + const double dScaled = p.zeroCodes ? 0.0 : d; + auto storeUnpacked = [&](uint8_t* out, double v) { + if (p.unpackedFormat == UnpackedFormat::IEEE32) + detail::storeBigEndian32(out, detail::ieee32Code(v)); + else if (p.unpackedFormat == UnpackedFormat::IBM32) + detail::storeBigEndian32(out, detail::ibm32Code(v)); + else + detail::storeBigEndian64(out, detail::ieee64Code(v)); + }; + + std::vector scaled; + scaled.reserve(packedCount(p.layout)); + uint8_t* h = output; + size_t i = 0; + for (int32_t m = 0; m <= J; m++) { + int32_t n = m; + if (m <= JS) { + for (; n <= JS; n++) { + for (int k = 0; k < 2; k++) { + double v = values[i++]; + if (p.gribexShBug && n == JS) + v = (v * dScaled) * scals[n]; + storeUnpacked(h, v); + h += bytes; + } + } + } + for (; n <= J; n++) { + scaled.push_back((values[i++] * d) * scals[n]); + scaled.push_back((values[i++] * d) * scals[n]); + } + } + + const size_t unpacked = static_cast(h - output); + if (p.zeroCodes) { + std::memset(output + unpacked, 0, size - unpacked); + return; + } + sp::Scaling s = p.scaling; + s.decimalScaleFactor = 0; // the decimal scaling is in the scaled values (as legacy ecCodes scales them) + sp::pack(scaled.data(), scaled.size(), s, output + unpacked, capacity - unpacked); +} + +inline std::vector pack(const std::vector& values, const Parameters& p) +{ + std::vector output(packedSize(p)); + pack(values.data(), values.size(), p, output.data(), output.size()); + return output; +} + +// Unpacks the count = valueCount(layout) coefficients from data (at least packedSize(p) bytes). +// Floats are the unpacked doubles converted to float, as ecCodes returns them (codes_get_float_array). +template +void unpack(const uint8_t* data, size_t size, const Parameters& p, Value* values, size_t count) +{ + static_assert(std::is_floating_point::value, "spectral complex packing unpacks floating-point values"); + detail::checkCount("unpack", count, valueCount(p.layout)); + if constexpr (!std::is_same::value) { + std::vector d(count); + unpack(data, size, p, d.data(), count); + for (size_t i = 0; i < count; i++) + values[i] = static_cast(d[i]); + return; + } + const size_t needed = packedSize(p); + if (size < needed) { + throw std::length_error("Spectral complex packing: the packed data are too small (" + std::to_string(size) + " bytes, " + + std::to_string(needed) + " bytes are needed)"); + } + const int32_t J = p.layout.truncation; + const int32_t JS = p.layout.subTruncation; + const size_t bytes = detail::bytesOf(p.unpackedFormat); + + if (JS == J) { + const Value d = sp::detail::sp_power(-p.scaling.decimalScaleFactor, 10); + for (size_t i = 0; i < count; i++) { + if (bytes == 4) { + const uint32_t bits = detail::loadBigEndian32(data + 4 * i); + float f = 0; + std::memcpy(&f, &bits, sizeof f); + values[i] = static_cast(f); + } + else { + values[i] = static_cast(detail::ieee64Value(detail::loadBigEndian64(data + 8 * i))); + } + if (d != 0) + values[i] *= d; + } + return; + } + + auto loadUnpacked = [&](const uint8_t* in) -> double { + if (p.unpackedFormat == UnpackedFormat::IEEE32) + return detail::ieee32Value(detail::loadBigEndian32(in)); + if (p.unpackedFormat == UnpackedFormat::IBM32) + return detail::ibm32Value(detail::loadBigEndian32(in)); + return detail::ieee64Value(detail::loadBigEndian64(in)); + }; + + const std::vector scals = detail::unpackingFactors(J, static_cast(p.laplacianOperator)); + const Value d = sp::detail::sp_power(-p.scaling.decimalScaleFactor, 10); + const Value s = sp::detail::sp_power(p.scaling.binaryScaleFactor, 2); + const Value ref = static_cast(p.scaling.referenceValue); + + // The codes of the packed coefficients go to the end of the output; the coefficients are then + // written from the front. A coefficient is never written after the code it overwrites is read: + // the k-th packed coefficient is written at most at unpacked + k, where its code is. + const size_t unpacked = unpackedCount(p.layout); + sp::unpack(data + unpacked * bytes, size - unpacked * bytes, detail::codeScaling(p.scaling.bitsPerValue), values + unpacked, + count - unpacked); + + const uint8_t* h = data; + size_t i = 0; + size_t j = unpacked; + for (int32_t m = 0; m <= J; m++) { + int32_t n = m; + if (m <= JS) { + for (; n <= JS; n++) { + for (int k = 0; k < 2; k++) { + Value v = static_cast(loadUnpacked(h)); + h += bytes; + if (p.gribexShBug && n == JS) + v *= scals[n]; // stored scaled (GRIBEX bug) + values[i++] = v; + } + } + } + for (; n <= J; n++) { + const Value c1 = values[j++]; + values[i++] = d * static_cast((c1 * s) + ref) * scals[n]; + const Value c2 = values[j++]; + values[i++] = d * static_cast((c2 * s) + ref) * scals[n]; + if (m == 0) + values[i - 1] = 0; // the imaginary part of m = 0 is 0 (a real field) + } + } +} + +template +std::vector unpack(const std::vector& data, const Parameters& p) +{ + std::vector values(valueCount(p.layout)); + unpack(data.data(), data.size(), p, values.data(), values.size()); + return values; +} + +} // namespace sc diff --git a/projects/spectral_complex/include/spectral_complex/version.h b/projects/spectral_complex/include/spectral_complex/version.h new file mode 100644 index 000000000..1e4cef059 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/version.h @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// The version of spectral_complex (major.minor.patch). Before 1.0.0 the interface may still change. +// CMakeLists.txt reads the version from this file: change it only here. + +#pragma once + +#define SPECTRAL_COMPLEX_VERSION_MAJOR 0 +#define SPECTRAL_COMPLEX_VERSION_MINOR 0 +#define SPECTRAL_COMPLEX_VERSION_PATCH 1 +#define SPECTRAL_COMPLEX_VERSION "0.0.1" + +namespace sc +{ + +// The version of the library, e.g. "0.0.1" +constexpr const char* version() +{ + return SPECTRAL_COMPLEX_VERSION; +} + +} // namespace sc diff --git a/projects/spectral_complex/src/Float.cc b/projects/spectral_complex/src/Float.cc new file mode 100644 index 000000000..78bc0b7d3 --- /dev/null +++ b/projects/spectral_complex/src/Float.cc @@ -0,0 +1,242 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// IEEE and IBM single precision floats as legacy ecCodes codes them (src/eccodes/grib_ieeefloat.cc, +// src/eccodes/grib_ibmfloat.cc). The arithmetic is the same, step by step, so that the coded bits +// are identical. + +#include "spectral_complex/detail/Float.h" + +#include +#include +#include +#include + +namespace sc::detail +{ +namespace +{ + +// n to the power of s, by repeated multiplication or division (like codes_power of ecCodes) +constexpr double power(int64_t s, int64_t n) +{ + double divisor = 1.0; + if (s == 0) + return 1.0; + if (s == 1) + return static_cast(n); + while (s < 0) { + divisor /= static_cast(n); + s++; + } + while (s > 0) { + divisor *= static_cast(n); + s--; + } + return divisor; +} + +// IEEE table: e[i] = 2^(i - 150) for i = 1..254 (e[0] = 0), v[i] = e[i] * 0x800000 +struct IeeeTable +{ + static constexpr int size = 255; + static constexpr uint32_t mantissaMin = 0x800000; + static constexpr uint32_t mantissaMax = 0xffffff; + std::array e{}; + std::array v{}; + double vmin = 0; + double vmax = 0; +}; + +constexpr IeeeTable makeIeeeTable() +{ + IeeeTable t{}; + for (int i = 1; i < IeeeTable::size; ++i) { + t.e[i] = power(i - 150, 2); + t.v[i] = t.e[i] * IeeeTable::mantissaMin; + } + t.vmin = t.e[1] * IeeeTable::mantissaMin; + t.vmax = t.e[254] * IeeeTable::mantissaMax; + return t; +} + +constexpr IeeeTable ieeeTable = makeIeeeTable(); + +// IBM table: e[i] = 16^(i - 70) for i = 0..127, v[i] = e[i] * 0x100000 +struct IbmTable +{ + static constexpr int size = 128; + static constexpr uint32_t mantissaMin = 0x100000; + static constexpr uint32_t mantissaMax = 0xffffff; + std::array e{}; + std::array v{}; + double vmin = 0; + double vmax = 0; +}; + +constexpr IbmTable makeIbmTable() +{ + IbmTable t{}; + for (int i = 0; i < IbmTable::size; ++i) { + t.e[i] = power(i - 70, 16); + t.v[i] = t.e[i] * IbmTable::mantissaMin; + } + t.vmin = t.e[0] * IbmTable::mantissaMin; + t.vmax = t.e[127] * IbmTable::mantissaMax; + return t; +} + +constexpr IbmTable ibmTable = makeIbmTable(); + +// The index jl with xx[jl] <= x < xx[jl + 1] of an ascending array of n + 1 values (legacy binary_search) +uint64_t binarySearch(const double* xx, uint64_t n, double x) +{ + uint64_t jl = 0; + uint64_t ju = n; + while (ju - jl > 1) { + const uint64_t jm = (ju + jl) >> 1; + if (x >= xx[jm]) + jl = jm; + else + ju = jm; + } + return jl; +} + +[[noreturn]] void tooLarge(const char* format, double x, double xmax) +{ + throw std::range_error(std::string("Spectral complex packing: the number ") + std::to_string(x) + " cannot be coded as an " + format + + " float (largest " + std::to_string(xmax) + ")"); +} + +} // namespace + +uint32_t ieee32Code(double x) +{ + uint64_t s = 0; + const uint64_t mmax = 0xffffff; + const uint64_t mmin = 0x800000; + const double rmmax = static_cast(mmax) + 0.5; + + if (std::isnan(x)) + tooLarge("IEEE", x, ieeeTable.vmax); + if (x < 0) { + s = 1; + x = -x; + } + // Underflow: a signed zero + if (x < ieeeTable.vmin) + return static_cast(s << 31); + // Overflow + if (x > ieeeTable.vmax) + tooLarge("IEEE", s ? -x : x, ieeeTable.vmax); + + uint64_t e = binarySearch(ieeeTable.v.data(), 254, x); + x /= ieeeTable.e[e]; + while (x < static_cast(mmin)) { + x *= 2; + e--; + } + while (x > rmmax) { + x /= 2; + e++; + } + uint64_t m = static_cast(x + 0.5); + if (m > mmax) { + e++; + m = 0x800000; + } + return static_cast((s << 31) | (e << 23) | (m & 0x7fffff)); +} + +double ieee32Value(uint32_t code) +{ + const uint32_t s = code & 0x80000000u; + uint32_t c = (code & 0x7f800000u) >> 23; + uint32_t m = code & 0x007fffffu; + + if (c == 0 && m == 0) + return 0; + // Exponent 255: infinity or NaN + if (c == 255) { + if (m != 0) + return std::nan(""); + return s ? -HUGE_VAL : HUGE_VAL; + } + if (c == 0) { + m |= 0x800000; + c = 1; + } + else { + m |= 0x800000; + } + double val = m * ieeeTable.e[c]; + if (s) + val = -val; + return val; +} + +uint32_t ibm32Code(double x) +{ + uint64_t s = 0; + const uint64_t mmax = 0xffffff; + const uint64_t mmin = 0x800000; // as legacy ecCodes (not the IBM normalisation 0x100000) + const double rmmax = static_cast(mmax) + 0.5; + + if (std::isnan(x)) + tooLarge("IBM", x, ibmTable.vmax); + if (x < 0) { + s = 1; + x = -x; + } + // Underflow: a signed zero + if (x < ibmTable.vmin) + return static_cast(s << 31); + // Overflow + if (x > ibmTable.vmax) + tooLarge("IBM", s ? -x : x, ibmTable.vmax); + + uint64_t e = binarySearch(ibmTable.v.data(), 127, x); + x /= ibmTable.e[e]; + while (x < static_cast(mmin)) { + x *= 16; + e--; + } + while (x > rmmax) { + x /= 16; + e++; + } + uint64_t m = static_cast(x + 0.5); + if (m > mmax) { + e++; + m = 0x800000; + } + return static_cast((s << 31) | (e << 24) | m); +} + +double ibm32Value(uint32_t code) +{ + const uint32_t s = code & 0x80000000u; + const uint32_t c = (code & 0x7f000000u) >> 24; + const uint32_t m = code & 0x00ffffffu; + + double val = m; + if (c == 0 && m <= 1) + return 0; + val *= ibmTable.e[c]; + if (s) + val = -val; + return val; +} + +double ieee32Max() +{ + return ieeeTable.vmax; +} + +double ibm32Max() +{ + return ibmTable.vmax; +} + +} // namespace sc::detail diff --git a/projects/spectral_complex/src/Operator.cc b/projects/spectral_complex/src/Operator.cc new file mode 100644 index 000000000..7d7a8943f --- /dev/null +++ b/projects/spectral_complex/src/Operator.cc @@ -0,0 +1,139 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// The laplacian operator, as legacy ecCodes computes it (calculate_pfactor in +// src/eccodes/accessor/DataComplexPacking.cc, including GRIB-172 and ECC-2393). The arithmetic is +// the same, in the same order, so that the operator is bit-identical. + +#include "spectral_complex/detail/Operator.h" + +#include +#include +#include +#include + +namespace sc::detail +{ +namespace +{ + +// Weighted least squares fit of log(norm) over log(n(n+1)) for the rows ismin..ismax: the operator +// (minus the slope). Norms below zeps are set to zeps and get a negligible weight. +double fit(const std::vector& rowNorms, int64_t ismin, int64_t ismax, double zeps, std::vector& norms, + std::vector& weights) +{ + double weightedSumOverX = 0.0, weightedSumOverY = 0.0, sumOfWeights = 0.0, x, y; + double numerator = 0.0, denominator = 0.0; + + const double range = static_cast(ismax - ismin + 1); + for (int64_t loop = ismin; loop <= ismax; loop++) + weights[loop] = range / static_cast(loop - ismin + 1); + + // Norms that are not too small for log() + for (int64_t loop = ismin; loop <= ismax; loop++) { + norms[loop] = std::max(rowNorms[loop], zeps); + if (norms[loop] == zeps) + weights[loop] = 100.0 * zeps; + } + + for (int64_t loop = ismin; loop <= ismax; loop++) { + x = std::log(static_cast(loop * (loop + 1))); + y = std::log(norms[loop]); + weightedSumOverX = weightedSumOverX + x * weights[loop]; + weightedSumOverY = weightedSumOverY + y * weights[loop]; + sumOfWeights = sumOfWeights + weights[loop]; + } + weightedSumOverX = weightedSumOverX / sumOfWeights; + weightedSumOverY = weightedSumOverY / sumOfWeights; + + for (int64_t loop = ismin; loop <= ismax; loop++) { + x = std::log(static_cast(loop * (loop + 1))); + y = std::log(norms[loop]); + numerator = numerator + weights[loop] * (y - weightedSumOverY) * (x - weightedSumOverX); + denominator = denominator + weights[loop] * ((x - weightedSumOverX) * (x - weightedSumOverX)); + } + const double slope = numerator / denominator; + return -slope; +} + +// ECC-2393: log of the largest scaled coefficient, max(norm(n) * (n(n+1))^p), over the rows with a +// non-zero norm (-HUGE_VAL if all norms are zero) +double logMaxScaledNorm(const std::vector& rowNorms, int64_t ismin, int64_t ismax, double p) +{ + double result = -HUGE_VAL; + for (int64_t loop = ismin; loop <= ismax; loop++) { + if (rowNorms[loop] > 0) + result = std::max(result, std::log(rowNorms[loop]) + p * std::log(static_cast(loop * (loop + 1)))); + } + return result; +} + +// ECC-2393: the largest operator for which no scaled coefficient exceeds exp(logLimit) +double maxOperator(const std::vector& rowNorms, int64_t ismin, int64_t ismax, double logLimit) +{ + double result = HUGE_VAL; + for (int64_t loop = ismin; loop <= ismax; loop++) { + if (rowNorms[loop] > 0) + result = std::min(result, (logLimit - std::log(rowNorms[loop])) / std::log(static_cast(loop * (loop + 1)))); + } + return result; +} + +} // namespace + +double laplacianOperator(const double* values, int32_t truncation, int32_t subTruncation) +{ + const double zeps = 1.0e-15; + const int64_t ismin = static_cast(subTruncation) + 1; + const int64_t ismax = static_cast(truncation) + 1; + + // ECC-2393: scaled coefficients above overflowLimit cannot be coded (32-bit float reference + // value, binary scale factor at most 127); a limited operator keeps them below maxScaledNorm + constexpr double overflowLimit = FLT_MAX / 2; + constexpr double maxScaledNorm = 1.0e30; + + // GRIB-172: a linear fit needs at least two points + if (ismax - ismin <= 1) + return 1; + + std::vector weights(static_cast(ismax + 1)); + std::vector workNorms(static_cast(ismax + 1)); + std::vector norms(static_cast(ismax + 1), 0.0); + + // Norms of the rows which contain part of the unpacked sub-truncation (only n >= JS counts) + int64_t index = -2; + for (int64_t m = 0; m < subTruncation; m++) { + for (int64_t n = m; n <= truncation; n++) { + index += 2; + if (n >= subTruncation) { + norms[n] = std::max(norms[n], std::fabs(values[index])); + norms[n] = std::max(norms[n], std::fabs(values[index + 1])); + } + } + } + // Norms of the other rows + for (int64_t m = subTruncation; m <= truncation; m++) { + for (int64_t n = m; n <= truncation; n++) { + index += 2; + norms[n] = std::max(norms[n], std::fabs(values[index])); + norms[n] = std::max(norms[n], std::fabs(values[index + 1])); + } + } + + double p = fit(norms, ismin, ismax, zeps, workNorms, weights); + + // ECC-2393: refit on the real norms, else limit the operator + if (p > 0 && logMaxScaledNorm(norms, ismin, ismax, p) > std::log(overflowLimit)) { + p = fit(norms, ismin, ismax, DBL_MIN, workNorms, weights); + if (logMaxScaledNorm(norms, ismin, ismax, p) > std::log(maxScaledNorm)) + p = std::max(0.0, maxOperator(norms, ismin, ismax, std::log(maxScaledNorm))); + } + + if (p < -9999.9) + p = -9999.9; + if (p > 9999.9) + p = 9999.9; + return p; +} + +} // namespace sc::detail diff --git a/projects/spectral_complex/tests/CMakeLists.txt b/projects/spectral_complex/tests/CMakeLists.txt new file mode 100644 index 000000000..c66366942 --- /dev/null +++ b/projects/spectral_complex/tests/CMakeLists.txt @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +# SPDX-License-Identifier: Apache-2.0 + +# Test names are prefixed to avoid collisions when built as part of ecCodes +set(SC_TEST_PREFIX "spectral_complex_") + +# sc_add_test( [SOURCES ]) +# Builds .cc into the executable sc_, compiled like the library (optimised). +function(sc_add_test name) + cmake_parse_arguments(ARG "" "" "SOURCES" ${ARGN}) + add_executable(sc_${name} ${CMAKE_CURRENT_SOURCE_DIR}/${name}.cc ${ARG_SOURCES}) + target_link_libraries(sc_${name} PRIVATE spectral_complex::spectral_complex) + target_include_directories(sc_${name} PRIVATE ${PROJECT_SOURCE_DIR}/tests) + target_compile_options(sc_${name} PRIVATE ${SPECTRAL_COMPLEX_OPT_FLAGS}) + target_link_options(sc_${name} PRIVATE ${SPECTRAL_COMPLEX_FP_LINK_FLAGS}) + # The tests check with assert(): never compile them with NDEBUG (the Release flags contain -DNDEBUG) + target_compile_options(sc_${name} PRIVATE -UNDEBUG) +endfunction() + +# sc_label_tests(