diff --git a/CMakeLists.txt b/CMakeLists.txt index 6c20d26b0b..47035840de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -184,6 +184,10 @@ ecbuild_add_option( FEATURE AEC # with AEC libaec is the default and ECCODES_USE_SPAEC=1 selects SpAec at runtime. # Simple packing: the legacy code and the simple_packing library (projects/simple_packing) are # both built. The legacy code is the default; ECCODES_USE_SP=1 selects the library. +# Spectral complex packing: the legacy code and the spectral_complex library +# (projects/spectral_complex) are both built. The legacy code is the default; ECCODES_USE_SC=1 +# selects the library. ECCODES_SC_OPERATOR=optimal selects the library with the laplacian operator +# of the smallest expected error (ECC-2393) instead of the fit of legacy ecCodes. ecbuild_find_python( VERSION 3.6 NO_LIBS ) # find_package( NumPy ) @@ -490,6 +494,9 @@ add_subdirectory( projects/spaec ) set( SIMPLE_PACKING_BUILD_TESTS ${ENABLE_TESTS} ) set( SIMPLE_PACKING_INSTALL OFF ) add_subdirectory( projects/simple_packing ) +set( SPECTRAL_COMPLEX_BUILD_TESTS ${ENABLE_TESTS} ) +set( SPECTRAL_COMPLEX_INSTALL OFF ) +add_subdirectory( projects/spectral_complex ) add_subdirectory( src ) if( HAVE_BUILD_TOOLS ) add_subdirectory( tools ) diff --git a/projects/spectral_complex/.clang-format b/projects/spectral_complex/.clang-format new file mode 100644 index 0000000000..f7f2be2cf6 --- /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 0000000000..fed9f97c80 --- /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 0000000000..053da9b0b7 --- /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 0000000000..470031308d --- /dev/null +++ b/projects/spectral_complex/CHANGELOG.md @@ -0,0 +1,60 @@ + + +# Changelog + +All notable changes to spectral_complex. The version is defined in +[`include/spectral_complex/version.h`](include/spectral_complex/version.h). The interface may still change before version 1.0.0. + +## 0.0.1 (unreleased) + +First version. + +### Packing and unpacking + +- GRIB spectral complex packing: `sc::parameters`, `sc::pack`, `sc::unpack`, `sc::Layout`, + `sc::Parameters`, `sc::Method`. +- Unpacked coefficients as IEEE32, IEEE64 or IBM32 floats; packed coefficients with 1 to 63 bits per + value and an IEEE (GRIB2) or IBM (GRIB1) reference value; unpacking to `float` and `double`. +- 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. +- Errors are exceptions where legacy ecCodes fails an assertion or codes garbage. `sc::parameters` + rejects: + - NaN and infinite coefficients (detected from their bit pattern, also with `-ffast-math` in the + including code); + - scaled values beyond the range of the reference value or of the binary scale factor (ECC-2393); + - a decimal scale factor beyond 16 bits, or with a 10^D that is not a normal number; + - an operator whose factors `(n(n+1))^P` or their inverses are not normal numbers; + - an operator with which packing or unpacking would overflow or lose precision. + +### The laplacian operator + +- `sc::laplacianOperator`: the fit of legacy ecCodes, bit-identical, including GRIB-172 (one packed + row), ECC-2381 (fewer than two rows above 1e-15, e.g. zero-padded fields) and ECC-2393 (very steep + spectra). +- `sc::optimalLaplacianOperator` (ECC-2393, header + [`spectral_complex/optimal_operator.h`](include/spectral_complex/optimal_operator.h)): the + operator with the smallest expected error of the packed coefficients, among the operators that the + message can store (`sc::OperatorCoding`) and with which the field can be packed and unpacked. It + is separate from the rest of the library. Described in + [docs/laplacian_operator.md](docs/laplacian_operator.md). + +### Build and tests + +- Floating-point compiler options `ON` by default (`SPECTRAL_COMPLEX_FP_CONTRACT_OFF`, + `SPECTRAL_COMPLEX_NO_FAST_MATH`, `SPECTRAL_COMPLEX_NO_TRAPPING_MATH`). Configure checks the + floating-point behaviour of the build flags and warns if it is not exact. +- Tests against a frozen copy of the legacy code, compiled with fixed floating-point options; the + optimal operator against brute force over all GRIB1 operators; regression tests. +- Benchmark `benchmarks/sc_bench` (`SPECTRAL_COMPLEX_BUILD_BENCHMARKS`), libFuzzer fuzzers + (`SPECTRAL_COMPLEX_BUILD_FUZZERS`), install test. +- Packing and unpacking tested on Linux (GCC, Clang, Intel icx; x86-64, AArch64, s390x) and on + Windows with MinGW-w64; the optimal operator on Linux x86-64 with GCC and Clang. + +### ecCodes + +- `ECCODES_USE_SC=1` selects the library (`DataComplexPackingNew.cc`); the messages are + byte-identical to the legacy code, which stays the default. +- `ECCODES_SC_OPERATOR=optimal` selects the library with the optimal laplacian operator. diff --git a/projects/spectral_complex/CMakeLists.txt b/projects/spectral_complex/CMakeLists.txt new file mode 100644 index 0000000000..152186e884 --- /dev/null +++ b/projects/spectral_complex/CMakeLists.txt @@ -0,0 +1,203 @@ +# 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 + src/OptimalOperator.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) + +# --- The frozen copy of legacy ecCodes (tests/legacy_reference.cc), the reference of the tests, fuzzers +# and benchmarks: compiled with fixed floating-point options, independent of the SPECTRAL_COMPLEX_* options +# and after the user's flags, so that the tests detect when the library loses its protection --- + +if(SPECTRAL_COMPLEX_BUILD_TESTS OR SPECTRAL_COMPLEX_BUILD_FUZZERS OR SPECTRAL_COMPLEX_BUILD_BENCHMARKS) + set(SPECTRAL_COMPLEX_REFERENCE_FLAGS "") + foreach(sc_flag -fno-fast-math -ffp-contract=off) + string(MAKE_C_IDENTIFIER "SPECTRAL_COMPLEX_REFERENCE_HAVE${sc_flag}" sc_var) + check_cxx_compiler_flag(${sc_flag} ${sc_var}) + if(${sc_var}) + list(APPEND SPECTRAL_COMPLEX_REFERENCE_FLAGS ${sc_flag}) + endif() + endforeach() + add_library(spectral_complex_legacy_reference OBJECT tests/legacy_reference.cc) + target_link_libraries(spectral_complex_legacy_reference PUBLIC simple_packing::headers) + target_include_directories(spectral_complex_legacy_reference PUBLIC ${PROJECT_SOURCE_DIR}/tests) + target_compile_options(spectral_complex_legacy_reference PRIVATE -O2 ${SPECTRAL_COMPLEX_REFERENCE_FLAGS}) + if(SPECTRAL_COMPLEX_BUILD_FUZZERS) + target_compile_options(spectral_complex_legacy_reference PRIVATE ${SPECTRAL_COMPLEX_FUZZER_COMPILE_OPTIONS}) + endif() +endif() + +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 docs/laplacian_operator.md DESTINATION ${CMAKE_INSTALL_DOCDIR}) +endif() diff --git a/projects/spectral_complex/LICENSE b/projects/spectral_complex/LICENSE new file mode 100755 index 0000000000..b55ed35574 --- /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 0000000000..78e6268f97 --- /dev/null +++ b/projects/spectral_complex/README.md @@ -0,0 +1,229 @@ + + +# spectral_complex + +spectral_complex is a C++17 library for GRIB spectral complex packing [[1]](#references) of +spherical harmonics coefficients. The coefficients of the sub-truncation JS are stored unpacked. +All others are multiplied by `(n(n+1))^P`, where P is the laplacian operator, and packed with +[simple packing](../simple_packing): `Y * 10^D = R + X * 2^E`. + +> [!NOTE] +> Version 0.0.1 (`sc::version()`, [`spectral_complex/version.h`](include/spectral_complex/version.h)). +> The interface may still change before version 1.0.0. + +[Features](#features) · +[Usage](#usage) · +[Build and test](#build-and-test) · +[Floating-point options](#floating-point-compiler-options) · +[Performance](#performance) · +[In ecCodes](#in-eccodes) · +[Known limits](#known-limits) + +## Features + +- Packing and unpacking with the same result as legacy ecCodes: the packed data are byte-identical + and the decoded values bit-identical, including the GRIBEX sh bug, the underflow of the binary + scale factor (all codes 0), JS = J (everything unpacked) and the zero imaginary part of m = 0. +- Two laplacian operators ([docs/laplacian_operator.md](docs/laplacian_operator.md) explains both, + with examples): + - `sc::laplacianOperator`: the fit of legacy ecCodes. + - `sc::optimalLaplacianOperator`: the operator with the smallest expected error (ECC-2393). It is + in its own header; the rest of the library does not depend on it. +- 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. +- Unpacked coefficients as IEEE32, IEEE64 or IBM32 floats; packed ones with 1 to 63 bits per value + and an IEEE (GRIB2) or IBM (GRIB1) reference value. +- Two ways to choose the scaling, as in ecCodes: `sc::Method::bits(n, D)` (bits per value and + decimal scale factor given, `optimizeScaleFactor=0`) and `sc::Method::bestPrecision(n)` + (`optimizeScaleFactor=1`). +- Unpacking to `double` or `float` (floats are the doubles converted, as `codes_get_float_array`). +- Errors are exceptions (`std::invalid_argument`, `std::range_error`, `std::length_error`), also + where legacy ecCodes fails an assertion or codes garbage: NaN, values or operators that cannot be + coded, a decimal scale factor out of range. + +## Usage + +The legacy algorithm, [`spectral_complex/spectral_complex.h`](include/spectral_complex/spectral_complex.h): + +```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 +const sc::Method method = sc::Method::bits(16); + +double P = sc::laplacianOperator(values, layout); // the fit of legacy ecCodes +sc::Parameters p = sc::parameters(values, layout, P, method); +std::vector packed = sc::pack(values, p); +std::vector back = sc::unpack(packed, p); +``` + +With the optimal operator, [`spectral_complex/optimal_operator.h`](include/spectral_complex/optimal_operator.h): + +```cpp +#include "spectral_complex/optimal_operator.h" + +sc::CodedOperator op = sc::optimalLaplacianOperator(values, layout, method, sc::OperatorCoding::GRIB2); +sc::Parameters p = sc::parameters(values, layout, op.value, method); +// Store op.units in the message (GRIB1: thousandths, GRIB2: millionths) +``` + +- The packed data contain no parameters. To unpack a message, fill in `sc::Parameters` from its + keys: the layout, the laplacian operator, the scaling (`referenceValue`, `binaryScaleFactor`, + `decimalScaleFactor`, `bitsPerValue`), the format of the unpacked coefficients and the GRIBEX bug. +- A message stores the operator rounded (GRIB1 in thousandths, GRIB2 in millionths). Pass the stored + value to `sc::parameters`, so that packing and unpacking use the same one. +- A packed coefficient of degree n is restored to within one step `2^E * 10^-D / (n(n+1))^P`, an + unpacked one to the precision of its format. +- For GRIB edition 1 use IBM floats: `sc::Method::bits(16).referenceFormat(sc::ReferenceFormat::IBM32)` + and `sc::UnpackedFormat::IBM32` as the format argument of `sc::parameters`. +- 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 +``` + +- **Dependency:** [simple_packing](../simple_packing), either installed + (`find_package(simple_packing)`) or from `projects/simple_packing` next to this project, which is + then built with it. +- **CMake targets:** `spectral_complex::spectral_complex` and `spectral_complex::headers`. +- **Options:** `SPECTRAL_COMPLEX_BUILD_TESTS`, `SPECTRAL_COMPLEX_BUILD_BENCHMARKS`, + `SPECTRAL_COMPLEX_BUILD_FUZZERS` (Clang), `SPECTRAL_COMPLEX_INSTALL`, + `SPECTRAL_COMPLEX_NATIVE_ARCH` (`-march=native`, default on) and the floating-point options below. +- **Tests:** + - Against a frozen copy of the legacy ecCodes code + ([`tests/legacy_reference.h`](tests/legacy_reference.h)): the fitted + operator, the float codes, packing and unpacking over many truncations, bits per value, formats + and spectra. + - The optimal operator against brute force: for small fields, no operator that GRIB1 can store + (all 65533 are tried) has a smaller expected error. + - Regression tests for the corner cases (ECC-2393, ECC-2381, GRIB-172, JS = J, underflow, GRIBEX + bug) and for the bugs found by the attack tests. +- **Fuzzers** (`-DSPECTRAL_COMPLEX_BUILD_FUZZERS=ON`, Clang, tests off): `fuzz_spectral_unpack` + (fuzzed parameters and data must not crash) and `fuzz_spectral_pack` (the result must equal the + frozen legacy copy). +- **Platforms:** packing and unpacking were tested on Linux (GCC, Clang, Intel icx; x86-64, AArch64 + and big-endian s390x) and on Windows (MinGW-w64 GCC, under wine). The optimal operator has so far + only been tested on Linux x86-64 with GCC and Clang. + +## Floating-point compiler options + +The library must round exactly like legacy ecCodes, on every compiler and CPU. It is therefore +compiled with these options (the same as simple_packing): + +| Option | CMake variable | Why | +|:---|:---|:---| +| `-ffp-contract=off` | `SPECTRAL_COMPLEX_FP_CONTRACT_OFF` | No fused multiply-add, which rounds differently | +| `-fno-fast-math` | `SPECTRAL_COMPLEX_NO_FAST_MATH` | Keeps the checks for NaN and infinity (icx uses fast math by default) | +| `-fno-trapping-math` | `SPECTRAL_COMPLEX_NO_TRAPPING_MATH` | Speed | + +- Each variable is `ON` (default), `AUTO` (only for the compilers that need it) or `OFF`. Code that + includes the headers gets the first two options through the CMake targets. +- Configure checks the arithmetic of the build flags and warns if it is not exact IEEE arithmetic + (`-ffast-math`, `-ffp-model=fast`, `-fno-honor-nans`, `-freciprocal-math`, `-fassociative-math`). +- x87 arithmetic (`-mfpmath=387`) is not supported: extended precision can change a packed value by + one code. Configure warns. +- NaN and infinite coefficients are detected from their bit pattern, so they are rejected even if + the including code is compiled with `-ffast-math`. +- The rounding mode must be the default (to nearest). + +## Performance + +The numbers give an overview; they are not exact. + +**Through the ecCodes API**, the legacy code against the library. Both write byte-identical +messages. + +| Call | Legacy MiB/s | Library MiB/s | Speed-up | +|:---|---:|---:|---:| +| `codes_get_double_array` | 1,705 | 8,724 | 5.1× | +| `codes_get_float_array` | 737 | 2,500 | 3.4× | +| `codes_set_double_array` | 242 | 2,491 | 10.3× | +| `codes_set_float_array` | 119 | 1,032 | 8.7× | + +The legacy code packs the coefficients bit by bit; the library uses the loops of simple_packing. + +
+How it was measured + +- AMD Ryzen Threadripper PRO 5995WX, one thread, GCC 16.2.1; ecCodes as a RelWithDebInfo build. +- Legacy code: `ECCODES_USE_SC=0`. Library: `ECCODES_USE_SC=1`. +- 16 synthetic fields T213 to T2047, GRIB1 and GRIB2, 12 and 16 bits per value, sub-truncation 20, + 27 million values in total. Each call runs over all messages three times; the fastest run counts. +- MiB/s counts the array passed to ecCodes: 8 bytes per double, 4 per float. +- Program: [`tests/benchmarks/packing_api.py`](../../tests/benchmarks/packing_api.py) of ecCodes + (`--program /tests/packing_api --spectral `). + +
+ +**The optimal operator** costs more than the fit, about as much as packing the field. One T1279 +field with 16 bits per value (1.6 million values): + +| Step | Time | +|:---|---:| +| `sc::laplacianOperator` (fit) | 0.2 ms | +| `sc::optimalLaplacianOperator`, GRIB1 / GRIB2 | 2.2 ms / 3.6 ms | +| `sc::parameters` + `sc::pack` | 3.0 ms | +| `codes_set_double_array` with the legacy code | 10.1 ms | +| `codes_set_double_array` with the library (`ECCODES_USE_SC=1`) | 3.7 ms | +| `codes_set_double_array` with the optimal operator (`ECCODES_SC_OPERATOR=optimal`) | 6.4 ms | + +(16 bits is the fastest case of the legacy code; bit widths that are not whole bytes are slower.) + +The library alone: [`benchmarks/sc_bench`](benchmarks/sc_bench.cc) +(`-DSPECTRAL_COMPLEX_BUILD_BENCHMARKS=ON`), results in +[benchmarks/sc_results.md](benchmarks/sc_results.md). + +## In ecCodes + +ecCodes contains both the legacy code and this library +([`accessor/DataComplexPackingNew.cc`](../../src/eccodes/accessor/DataComplexPackingNew.cc)). Two +environment variables select what is used; they are read once per process. + +| Environment | Packing and unpacking | Laplacian operator | Messages | +|:---|:---|:---|:---| +| none (default) | legacy code | fit | | +| `ECCODES_USE_SC=1` | library | fit | byte-identical to the default | +| `ECCODES_SC_OPERATOR=optimal` | library | optimal | same format, another operator | + +- `ECCODES_SC_OPERATOR=legacy`, unset or empty means the fit. Any other value makes encoding fail + with `GRIB_INVALID_ARGUMENT`; decoding is not affected. +- The optimal operator is only used where ecCodes computes the operator. An operator that the + message keeps (GRIBEX mode) and the fixed operator of ECC-2366 are not changed. +- Where the legacy code fails an assertion or reads past the message, the library returns an error + (`GRIB_OUT_OF_RANGE` for values that cannot be coded and for NaN). If the keys describe more data + than the message contains, the missing bytes are decoded as zeros. +- ctests: [`eccodes_t_grib_spectral_complex_legacy`](../../tests/grib_spectral_complex_legacy.sh) + (byte-identical messages), + [`eccodes_t_grib_spectral_complex_optimal`](../../tests/grib_spectral_complex_optimal.sh), + [`eccodes_t_grib_ecc-2393`](../../tests/grib_ecc-2393.cc). + +> [!IMPORTANT] +> When decoded values are packed again unchanged, keep the operator of the message (key +> `computeLaplacianOperator=0`, or GRIBEX mode): with the same bits per value they are then +> reproduced exactly or nearly so. Any recomputed operator, fitted or optimal, adds a new rounding +> error. + +## Known limits + +- With `sc::Method::bestPrecision` and subnormal coefficients (below 2.2e-308), `sc::parameters` can + return a scaling with which `sc::pack` throws `std::runtime_error`. Legacy ecCodes has the same + mismatch and codes garbage. +- A message with an extreme operator (for example -1074) decodes to infinite values, as with legacy + ecCodes. `sc::parameters` rejects such an operator when packing. +- The limits of the optimal operator are listed in + [docs/laplacian_operator.md](docs/laplacian_operator.md#limits-of-the-optimal-operator). + +## 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/benchmarks/CMakeLists.txt b/projects/spectral_complex/benchmarks/CMakeLists.txt new file mode 100644 index 0000000000..6ac8370930 --- /dev/null +++ b/projects/spectral_complex/benchmarks/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +# SPDX-License-Identifier: Apache-2.0 +# +# sc_bench: an overview of the speed of spectral_complex (see sc_bench.cc) +add_executable(sc_bench sc_bench.cc) +target_link_libraries(sc_bench PRIVATE spectral_complex::spectral_complex spectral_complex_legacy_reference) +target_include_directories(sc_bench PRIVATE ${PROJECT_SOURCE_DIR}/tests) # test_fields.h, legacy_reference.h +target_compile_options(sc_bench PRIVATE ${SPECTRAL_COMPLEX_OPT_FLAGS}) +target_compile_definitions(sc_bench PRIVATE NDEBUG) diff --git a/projects/spectral_complex/benchmarks/sc_bench.cc b/projects/spectral_complex/benchmarks/sc_bench.cc new file mode 100644 index 0000000000..bbf67a3b80 --- /dev/null +++ b/projects/spectral_complex/benchmarks/sc_bench.cc @@ -0,0 +1,100 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// usage: sc_bench [--runs N] +// +// An overview of the speed of spectral_complex: the laplacian operators (sc::laplacianOperator, the +// fit of legacy ecCodes, and sc::optimalLaplacianOperator for GRIB2), packing (sc::parameters with +// Method::bits and sc::pack) and unpacking to doubles and floats, for +// synthetic fields T639, T1279 and T2047 (sub-truncation 20, power-law spectrum) with 12, 16 and 24 +// bits per value. For comparison, the frozen copy of the legacy code (tests/legacy_reference.h, which +// codes bit by bit like legacy ecCodes for widths that are not 8, 16, ... bits). Times: the fastest of +// N runs (default 5), warm caches. MiB/s counts the doubles or floats (8 or 4 bytes per value). +// Exit status 1 if the library and the legacy copy disagree. + +#include +#include +#include +#include +#include +#include +#include + +#include "legacy_reference.h" +#include "spectral_complex/optimal_operator.h" +#include "spectral_complex/spectral_complex.h" +#include "test_fields.h" + +namespace +{ + +using Clock = std::chrono::steady_clock; + +double best(int runs, const std::function& f) +{ + double t = 1e30; + for (int r = 0; r < runs; r++) { + const auto t0 = Clock::now(); + f(); + t = std::min(t, std::chrono::duration(Clock::now() - t0).count()); + } + return t; +} + +void row(const char* what, int32_t J, int32_t bpv, size_t values, size_t bytesPerValue, double seconds) +{ + std::printf("| %s | T%d | %d | %.0f | %.0f |\n", what, J, bpv, static_cast(values * bytesPerValue) / seconds / 1048576.0, + static_cast(values) / seconds / 1e6); +} + +} // namespace + +int main(int argc, char** argv) +{ + int runs = 5; + for (int i = 1; i < argc; i++) { + if (std::strcmp(argv[i], "--runs") == 0 && i + 1 < argc) + runs = std::atoi(argv[++i]); + } + std::printf("spectral_complex %s, fastest of %d runs\n\n", sc::version(), runs); + std::printf("| Operation | Truncation | Bits per value | MiB/s | Mvalues/s |\n|:---|:---|---:|---:|---:|\n"); + int failures = 0; + for (int32_t J : { 639, 1279, 2047 }) { + const sc::Layout layout{ J, 20 }; + const std::vector v = test::field(J, test::powerLaw(1e3, 3.0), static_cast(J)); + const size_t n = v.size(); + double P = 0; + row("laplacianOperator", J, 0, n, 8, best(runs, [&] { P = sc::laplacianOperator(v, layout); })); + P = std::trunc(P * 1e6) / 1e6; // as GRIB2 stores it + for (int32_t bpv : { 12, 16, 24 }) { + row("optimalLaplacianOperator", J, bpv, n, 8, best(runs, [&] { sc::optimalLaplacianOperator(v, layout, sc::Method::bits(bpv)); })); + sc::Parameters p; + std::vector packed(sc::packedSize(sc::parameters(v, layout, P, sc::Method::bits(bpv)))); + row("pack (parameters + pack)", J, bpv, n, 8, best(runs, [&] { + p = sc::parameters(v, layout, P, sc::Method::bits(bpv)); + sc::pack(v.data(), n, p, packed.data(), packed.size()); + })); + std::vector d(n); + std::vector f(n); + row("unpack double", J, bpv, n, 8, best(runs, [&] { sc::unpack(packed.data(), packed.size(), p, d.data(), n); })); + row("unpack float", J, bpv, n, 4, best(runs, [&] { sc::unpack(packed.data(), packed.size(), p, f.data(), n); })); + + // The frozen legacy copy, once (it is slow): the same data, its speed for comparison + legacy::Packed expected; + const double tl = best(1, [&] { expected = legacy::pack_double(v.data(), J, 20, P, bpv, 0, 1, false); }); + row("legacy copy: pack", J, bpv, n, 8, tl); + std::vector ld(n); + std::vector padded(packed); + padded.resize(packed.size() + 16, 0); + const double tu = best(1, [&] { + legacy::unpack_real(padded.data(), J, 20, P, bpv, p.scaling.referenceValue, p.scaling.binaryScaleFactor, 0, 1, false, ld.data()); + }); + row("legacy copy: unpack double", J, bpv, n, 8, tu); + if (expected.buf != packed || std::memcmp(ld.data(), d.data(), n * sizeof(double)) != 0) { + std::fprintf(stderr, "FAIL: T%d %d bits: the library and the legacy copy disagree\n", J, bpv); + failures++; + } + } + } + return failures ? 1 : 0; +} diff --git a/projects/spectral_complex/benchmarks/sc_results.md b/projects/spectral_complex/benchmarks/sc_results.md new file mode 100644 index 0000000000..54b705f04f --- /dev/null +++ b/projects/spectral_complex/benchmarks/sc_results.md @@ -0,0 +1,75 @@ + + +# sc_bench results + +`sc_bench --runs 7` (see [`sc_bench.cc`](sc_bench.cc)): synthetic fields T639, T1279 and T2047 with sub-truncation 20 +and a power-law spectrum; the fastest of 7 runs, warm caches, one thread. `optimalLaplacianOperator` +is for GRIB2 (millionths). MiB/s counts the doubles or +floats (8 or 4 bytes per value). "legacy copy" is the frozen copy of the legacy ecCodes code in +[`tests/legacy_reference.h`](../tests/legacy_reference.h) (one run; it codes bit by bit like legacy ecCodes). + +- Hardware: AMD Ryzen Threadripper PRO 5995WX (Zen 3, AVX2), pinned to one core. +- Compiler: GCC 16.2.1, Release build with the project flags (`-O3 -march=native`, `-ffp-contract=off`). + +| Operation | Truncation | Bits per value | MiB/s | Mvalues/s | +|:---|:---|---:|---:|---:| +| laplacianOperator | T639 | 0 | 45176 | 5921 | +| optimalLaplacianOperator | T639 | 12 | 2045 | 268 | +| pack (parameters + pack) | T639 | 12 | 3917 | 513 | +| unpack double | T639 | 12 | 7974 | 1045 | +| unpack float | T639 | 12 | 3303 | 866 | +| legacy copy: pack | T639 | 12 | 399 | 52 | +| legacy copy: unpack double | T639 | 12 | 527 | 69 | +| optimalLaplacianOperator | T639 | 16 | 2051 | 269 | +| pack (parameters + pack) | T639 | 16 | 4128 | 541 | +| unpack double | T639 | 16 | 11713 | 1535 | +| unpack float | T639 | 16 | 4494 | 1178 | +| legacy copy: pack | T639 | 16 | 203 | 27 | +| legacy copy: unpack double | T639 | 16 | 387 | 51 | +| optimalLaplacianOperator | T639 | 24 | 1751 | 229 | +| pack (parameters + pack) | T639 | 24 | 3463 | 454 | +| unpack double | T639 | 24 | 9160 | 1201 | +| unpack float | T639 | 24 | 3723 | 976 | +| legacy copy: pack | T639 | 24 | 122 | 16 | +| legacy copy: unpack double | T639 | 24 | 281 | 37 | +| laplacianOperator | T1279 | 0 | 52109 | 6830 | +| optimalLaplacianOperator | T1279 | 12 | 3063 | 402 | +| pack (parameters + pack) | T1279 | 12 | 3935 | 516 | +| unpack double | T1279 | 12 | 7943 | 1041 | +| unpack float | T1279 | 12 | 3289 | 862 | +| legacy copy: pack | T1279 | 12 | 408 | 54 | +| legacy copy: unpack double | T1279 | 12 | 528 | 69 | +| optimalLaplacianOperator | T1279 | 16 | 3064 | 402 | +| pack (parameters + pack) | T1279 | 16 | 4119 | 540 | +| unpack double | T1279 | 16 | 11776 | 1544 | +| unpack float | T1279 | 16 | 4494 | 1178 | +| legacy copy: pack | T1279 | 16 | 212 | 28 | +| legacy copy: unpack double | T1279 | 16 | 389 | 51 | +| optimalLaplacianOperator | T1279 | 24 | 3520 | 461 | +| pack (parameters + pack) | T1279 | 24 | 3467 | 454 | +| unpack double | T1279 | 24 | 9158 | 1200 | +| unpack float | T1279 | 24 | 3702 | 970 | +| legacy copy: pack | T1279 | 24 | 125 | 16 | +| legacy copy: unpack double | T1279 | 24 | 281 | 37 | +| laplacianOperator | T2047 | 0 | 33252 | 4358 | +| optimalLaplacianOperator | T2047 | 12 | 4819 | 632 | +| pack (parameters + pack) | T2047 | 12 | 2989 | 392 | +| unpack double | T2047 | 12 | 7445 | 976 | +| unpack float | T2047 | 12 | 1806 | 473 | +| legacy copy: pack | T2047 | 12 | 406 | 53 | +| legacy copy: unpack double | T2047 | 12 | 528 | 69 | +| optimalLaplacianOperator | T2047 | 16 | 4265 | 559 | +| pack (parameters + pack) | T2047 | 16 | 3112 | 408 | +| unpack double | T2047 | 16 | 10945 | 1435 | +| unpack float | T2047 | 16 | 2174 | 570 | +| legacy copy: pack | T2047 | 16 | 215 | 28 | +| legacy copy: unpack double | T2047 | 16 | 389 | 51 | +| optimalLaplacianOperator | T2047 | 24 | 4814 | 631 | +| pack (parameters + pack) | T2047 | 24 | 2709 | 355 | +| unpack double | T2047 | 24 | 8381 | 1099 | +| unpack float | T2047 | 24 | 1919 | 503 | +| legacy copy: pack | T2047 | 24 | 127 | 17 | +| legacy copy: unpack double | T2047 | 24 | 281 | 37 | 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 0000000000..67f197dee5 --- /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 0000000000..1df4f664c5 --- /dev/null +++ b/projects/spectral_complex/cmake/spectral_complexFloatingPoint.cmake @@ -0,0 +1,288 @@ +# 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 +# undone: the project's flags come after it on the command line. Without +# -fno-fast-math (OFF) configure warns and the tests fail. Flags that a +# consumer adds after the usage requirements cannot be seen at configure time. +# -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. +# +# After the flags are chosen, configure checks the floating-point behaviour with the flags of the build: +# the macros of -ffast-math / -ffinite-math-only, x87 arithmetic (FLT_EVAL_METHOD != 0: intermediate +# results in extended precision, e.g. -mfpmath=387; the results then may differ from legacy ecCodes by one +# code, no option fixes that, use SSE2) and, where the probe can run, the behaviour itself (NaN and +# infinity detected, no contraction, no reciprocal or reassociated arithmetic; this also catches +# -ffp-model=fast and -fno-honor-nans, which define no macro). It warns if one of them is not as required. +# +# 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() + # No build type (or empty flags): one set of flags, so that the checks run once (an empty list would + # skip them) + if(NOT result) + set(result " ") + endif() + 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() + + # x87 arithmetic: intermediate results in extended precision (no option makes them identical) + set(CMAKE_REQUIRED_FLAGS "${config_flag_set} -O3 ${flags} ${arch_flags}") + string(REPLACE ";" " " CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") + string(MD5 key "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_FLAGS} ${config_flag_set} ${flags} ${arch_flags}") + check_cxx_source_compiles(" + #if defined(__FLT_EVAL_METHOD__) && __FLT_EVAL_METHOD__ > 0 + #error excess precision + #endif + int main() { return 0; }" SPECTRAL_COMPLEX_NO_EXCESS_PRECISION_${key}) + if(NOT SPECTRAL_COMPLEX_NO_EXCESS_PRECISION_${key}) + message(WARNING "spectral_complex: with the compiler flags (CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}; of the configuration: " + "${config_flag_set}) the arithmetic uses extended precision (FLT_EVAL_METHOD > 0, x87, e.g. -mfpmath=387): " + "the packed data may differ from legacy ecCodes by one code and the tests fail. Use SSE2 arithmetic " + "(-mfpmath=sse; the default on x86-64).") + break() + endif() + + # The behaviour itself (catches -ffp-model=fast, -fno-honor-nans, -freciprocal-math, ... which define no + # macro), where the probe can run. Results are compared as bit patterns: comparisons of floating-point + # values could be folded away. + if(NOT CMAKE_CROSSCOMPILING OR CMAKE_CROSSCOMPILING_EMULATOR) + set(CMAKE_REQUIRED_FLAGS "${config_flag_set} -O3 ${flags} ${arch_flags}") + string(REPLACE ";" " " CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") + string(MD5 key "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_FLAGS} ${config_flag_set} ${flags} ${arch_flags}") + check_cxx_source_runs(" + #include + #include + #include + static std::uint64_t bits(double x) { std::uint64_t b = 0; std::memcpy(&b, &x, sizeof b); return b; } + volatile double zero = 0.0, one = 1.0, seven = 7.0, a = 1.0 + 0x1p-27, b = 1.0 - 0x1p-27; + int main() + { + int bad = 0; + const double nan = zero / zero, inf = one / zero; + if (!std::isnan(nan) || std::isfinite(nan)) bad |= 1; // NaN detected + if (!std::isinf(inf) || std::isfinite(inf)) bad |= 2; // infinity detected + const double x = a, y = b, c = one; + if (bits(x * y - c) != 0) bad |= 4; // no contraction + if (bits(seven / 3.0) != bits(7.0 / 3.0)) bad |= 8; // no reciprocal arithmetic + const double o = one; + if (bits((o + 0x1p53) - 0x1p53) != 0) bad |= 16; // no reassociation + return bad; + }" SPECTRAL_COMPLEX_FP_BEHAVIOUR_${key}) + if(NOT SPECTRAL_COMPLEX_FP_BEHAVIOUR_${key}) + message(WARNING "spectral_complex: with the compiler flags (CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}; of the configuration: " + "${config_flag_set}; project: ${flags}) the floating-point arithmetic is not exact IEEE (NaN or infinity " + "not detected, contraction, reciprocal or reassociated arithmetic, e.g. -ffp-model=fast or " + "-fno-honor-nans): the packed data may differ from legacy ecCodes and the tests fail. Remove the option " + "or keep the SPECTRAL_COMPLEX_* floating-point options ON.") + break() + endif() + 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/docs/laplacian_operator.md b/projects/spectral_complex/docs/laplacian_operator.md new file mode 100644 index 0000000000..2928e53561 --- /dev/null +++ b/projects/spectral_complex/docs/laplacian_operator.md @@ -0,0 +1,241 @@ + + +# The laplacian operator + +[Summary](#summary) · +[Background](#background) · +[The default](#the-default-the-fit-of-legacy-eccodes) · +[The optimal operator](#the-optimal-operator) · +[The difference](#the-difference-with-numbers) · +[Cost](#cost) · +[Limits](#limits-of-the-optimal-operator) + +## Summary + +When ecCodes compresses spectral fields (spherical harmonics, e.g. IFS model fields), a setting +called the laplacian operator decides how the precision is shared between the large and the small +scales. Today it is estimated from the shape of the data, without regard to the resulting accuracy. +The new method chooses it so that the error of the compressed field is as small as possible. + +- **More accurate data in the same space:** about 10 % smaller errors for ordinary fields, with the + same file size and the same format. Existing software reads the files unchanged. +- **Much better for unusual fields:** for very steep spectra, such as the stochastic perturbation + patterns of the ensemble (ECC-2393), the errors are 13 times smaller. For these fields today's + estimate even made the encoding fail before it was corrected. +- **Easy to introduce and to undo:** today's method stays the default. One environment variable, + `ECCODES_SC_OPERATOR=optimal`, switches the new one on. It has passed all ecCodes tests and + extensive automated stress tests. +- **The price:** computing the setting takes about as long as compressing the field (2 to 4 ms for + a T1279 field; see [Cost](#cost)). + +## Background + +The coefficients $c$ of the degrees $n \le J_S$ (the sub-truncation) are stored as floats. Every +other coefficient is multiplied by the factor $(n(n+1))^P$ and coded with $b$ bits: + +```math +c \cdot (n(n+1))^P \cdot 10^D = R + X \cdot 2^E, \qquad X \in \{0, \dots, 2^b - 1\} +``` + +| Symbol | Meaning | +|---|---| +| $P$ | The laplacian operator. The message stores it as an integer: thousandths in GRIB1, millionths in GRIB2 | +| $R$ | The reference value: the smallest scaled coefficient, rounded down to a 32-bit float | +| $E$ | The binary scale factor: the smallest one with which the range of the scaled coefficients fits $b$ bits | +| $D$ | The decimal scale factor | +| $\Delta = 2^E / 10^D$ | The quantisation step | + +A decoded coefficient of degree $n$ is wrong by at most + +```math +|\delta c| \le \frac{\Delta}{2} \, (n(n+1))^{-P} +``` + +A larger $P$ shrinks the error of the high degrees. But it also makes the scaled coefficients +larger and their range wider, so the step $\Delta$ gets coarser. The two operators settle this +trade-off differently. + +## The default: the fit of legacy ecCodes + +[`sc::laplacianOperator`](../include/spectral_complex/spectral_complex.h), in ecCodes with +`ECCODES_SC_OPERATOR` unset or `legacy`. + +The operator is the slope of the spectrum: a straight line fitted through the logarithms of the +row norms. + +**Step 1: the row norms.** The row norm of degree $n$ is its largest absolute packed coefficient: + +```math +N_n = \max_m |c_{mn}| +``` + +**Step 2: one point per degree.** For each packed degree $n = J_S+1, \dots, J$: + +```math +x_n = \ln\bigl(n(n+1)\bigr), \qquad y_n = \ln N_n, \qquad w_n = \frac{J - J_S + 1}{n - J_S} +``` + +The weights $w_n$ favour the low degrees. A norm of at most $10^{-15}$ gets a negligible weight +($10^{-13}$), which removes it from the fit. + +**Step 3: the slope.** $P$ is minus the slope of the weighted least squares line. With the weighted +means $\bar x = \sum w_n x_n / \sum w_n$ and $\bar y = \sum w_n y_n / \sum w_n$: + +```math +P = -\frac{\sum_n w_n (x_n - \bar x)(y_n - \bar y)}{\sum_n w_n (x_n - \bar x)^2} +``` + +For a spectrum $N_n \propto (n(n+1))^{-a}$ this gives $P = a$: all scaled norms are then equal. + +**Special cases.** + +- $P = 1$ if fewer than two degrees can be fitted (GRIB-172: $J - J_S \le 1$; ECC-2381: fewer than + two norms above $10^{-15}$). +- ECC-2393: if $P \gt 0$ and the largest scaled norm $\max_n N_n (n(n+1))^P$ would exceed half the + largest 32-bit float, the fit is repeated with all non-zero norms. If that is still too large, + $P$ is the largest operator that keeps it below $10^{30}$ (at least 0). +- $P$ is limited to $\pm 9999.9$. + +The fit looks only at the shape of the spectrum. It does not know the number of bits or the step +$\Delta$ that its operator leads to. + +## The optimal operator + +[`sc::optimalLaplacianOperator`](../include/spectral_complex/optimal_operator.h), in ecCodes with +`ECCODES_SC_OPERATOR=optimal`. + +The operator is the one with the smallest expected error of the decoded coefficients. + +**Step 1: the error.** A coded value is rounded to the nearest code, so its error is spread evenly +over $\pm\Delta/2$ (variance $\Delta^2/12$). Decoding divides it by $(n(n+1))^P$. Degree $n$ has +$2n+1$ packed values with an error (the imaginary part of $m = 0$ is always zero). The expected +squared error of the field is + +```math +G(P) = \frac{\Delta(P)^2}{12} \sum_{n=J_S+1}^{J} (2n+1)\,(n(n+1))^{-2P} +``` + +$\Delta(P)$ is the step that the packing really chooses for $P$, for this field, this number of +bits and this reference format. + +**Step 2: the choice.** $P$ is the operator with the smallest $G(P)$ among those that the message +can store and with which the field can be packed and unpacked: + +| Edition | Operators that can be stored | +|---|---| +| GRIB1 | $k/1000$ with $\lvert k \rvert \le 32766$ | +| GRIB2 | $k/10^6$ with $\lvert k \rvert \le 2147483646$ | + +**Step 3: the search.** $\Delta(P)$ is a staircase: it grows with $P$ and is constant between two +jumps of $E$. On one stair the sum falls with $P$, so only the last operator of each stair can be +the minimum. The search starts at the minimum of a smooth version of $G$ (the step replaced by the +range of the scaled coefficients) and visits the stairs on both sides. The smooth version is never +larger than $G$: when it exceeds the best $G$ found, the search stops. + +**Special cases.** $P = 0$ if all packed coefficients are equal (they are then coded exactly), and +if the coefficients are too small for every operator (all codes are zero, as in legacy ecCodes). + +## The difference, with numbers + +The fit chooses $P$ from the shape of the spectrum. The optimal operator chooses it from the error +of the coded field. The fitted $P$ can lie anywhere on a stair of $\Delta(P)$, also just after a +jump, where the step has just doubled. The optimal operator takes the end of the best stair. + +### A small example + +$J = 6$, $J_S = 1$, every coefficient $c_{mn} = \pm (n+1)^{-2}$, 8 bits per value, GRIB1. + +The fit: + +| $n$ | $n(n+1)$ | $x_n$ | $N_n$ | $y_n$ | $w_n$ | +|---:|---:|---:|---:|---:|---:| +| 2 | 6 | 1.7918 | 0.111111 | -2.1972 | 6.0 | +| 3 | 12 | 2.4849 | 0.062500 | -2.7726 | 3.0 | +| 4 | 20 | 2.9957 | 0.040000 | -3.2189 | 2.0 | +| 5 | 30 | 3.4012 | 0.027778 | -3.5835 | 1.5 | +| 6 | 42 | 3.7377 | 0.020408 | -3.8918 | 1.2 | + +$\sum w_n = 13.7$, $\bar x = 2.4660$, $\bar y = -2.7726$, +$\sum w_n (x_n - \bar x)(y_n - \bar y) = -5.6459$, $\sum w_n (x_n - \bar x)^2 = 6.5424$, so +$P = 5.6459 / 6.5424 = 0.863$. + +The error for some operators. $S$ is the sum $\sum (2n+1)(n(n+1))^{-2P}$; the expected RMS error is +$\Delta \sqrt{S / (12 \cdot 45)}$ for the 45 packed values; the measured one is from packing and +unpacking. + +| $P$ | $E$ | Step $\Delta$ | $S$ | Expected RMS | Measured RMS | +|:---|---:|---:|---:|---:|---:| +| 0 | -10 | 0.000977 | 45 | 0.000282 | 0.000258 | +| 0.5 | -8 | 0.00391 | 2.543 | 0.000268 | 0.000274 | +| **0.836** (optimal) | -8 | 0.00391 | 0.4823 | **0.000117** | **0.000123** | +| 0.837 | -7 | 0.00781 | 0.4801 | 0.000233 | 0.000188 | +| **0.863** (fit) | -7 | 0.00781 | 0.4256 | **0.000219** | **0.000220** | +| 1.0 | -7 | 0.00781 | 0.2296 | 0.000161 | 0.000142 | +| 1.5 | -4 | 0.0625 | 0.0289 | 0.000457 | 0.000327 | + +At $P = 0.837$ the range no longer fits 8 bits with $E = -8$, and the step doubles. The fitted +$P = 0.863$ lies on this coarser stair. The optimal $P = 0.836$ is the last operator of the finer +one, and its error is about half as large. + +### Realistic fields + +Sub-truncation 20. RMS is the error of the packed coefficients after packing and unpacking, with the +operators as the message stores them. + +| Field | Coding | Fit $P$ | $E$ | RMS | Optimal $P$ | $E$ | RMS | Fit / optimal | +|:---|:---|---:|---:|---:|---:|---:|---:|---:| +| Power law, T639 | GRIB1, 12 bits | 1.236 | -11 | 2.07e-09 | 1.149 | -12 | 1.86e-09 | 1.11 | +| Power law, T639 | GRIB2, 16 bits | 1.235832 | -15 | 1.29e-10 | 1.149131 | -16 | 1.17e-10 | 1.10 | +| Steep spectrum, T1279 | GRIB1, 16 bits | 12.635 | 74 | 5.97e-15 | 11.936 | 64 | 4.40e-16 | **13.6** | +| Steep spectrum, T1279 | GRIB2, 16 bits | 12.635315 | 74 | 5.65e-15 | 12.274924 | 67 | 4.34e-16 | **13.0** | +| Temperature, T1279 | GRIB1, 12 bits | 0.740 | -2 | 1.86e-05 | 0.751 | -2 | 1.72e-05 | 1.08 | +| Temperature, T1279 | GRIB2, 8 bits | 0.739606 | 2 | 2.98e-04 | 0.751565 | 2 | 2.71e-04 | 1.10 | + +- **Power law:** random coefficients with $|c| \le (n+1)^{-2.5}$. +- **Steep spectrum:** the synthetic field of + [`tests/grib_ecc-2393.cc`](../../../tests/grib_ecc-2393.cc), built from the row norms of the SPP + random patterns in ECC-2393. +- **Temperature:** a real field, decoded from 16 bits and packed again with fewer bits. + +For the ordinary fields the error of the fit is 8 to 15 % larger. For the steep spectrum the fit is +dominated by a few steep rows just above the sub-truncation: its operator is too large, the scaled +coefficients of the high degrees grow too much ($E = 74$ instead of 64 or 67), and its error is 13 +times larger. + +## Cost + +One T1279 field with 16 bits per value (1.6 million values), one thread: + +| Step | Time | +|:---|---:| +| The fit | 0.2 ms | +| The optimal operator, GRIB1 / GRIB2 | 2.2 ms / 3.6 ms | +| Packing with the library | 3.0 ms | +| ecCodes today (legacy code, fit) | 10.1 ms | +| ecCodes with the library and the fit (`ECCODES_USE_SC=1`) | 3.7 ms | +| ecCodes with the library and the optimal operator (`ECCODES_SC_OPERATOR=optimal`) | 6.4 ms | + +The optimal operator costs about as much as packing the field. It comes with the library, whose +packing is faster than the legacy code: in this case encoding with the optimal operator is still +faster than today's default. + +## Limits of the optimal operator + +> [!IMPORTANT] +> **Re-packing decoded values.** Decoded values lie on the grid of their operator. Packed again +> with that operator and the same bits per value, they are reproduced exactly or nearly so. With +> any recomputed operator, fitted or optimal, they get a new rounding error. Keep the operator of +> the message when the values are unchanged (in ecCodes: `computeLaplacianOperator=0` or GRIBEX +> mode). + +- **Expected, not measured.** The operator minimises the expected error. For a field with only a + few packed values the measured error can differ much from it, and a neighbouring operator can be + better. +- **Fields that are not real.** The minimum is guaranteed if the packed coefficients are not all + positive or all negative. Every real field qualifies, because its imaginary parts of $m = 0$ are + zero. Otherwise the result can be coded, but may be only a local minimum. +- **Rounding mode.** The default (to nearest) is required; in another mode the result can differ + by a unit. 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 0000000000..7d97e9ab27 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/detail/Float.h @@ -0,0 +1,107 @@ +// 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 + +namespace sc::detail +{ + +// The bits of x, hidden from the optimiser: Clang recognises an exponent test of the bits as a +// floating-point class test and folds it away under -ffast-math / -ffinite-math-only / -fno-honor-nans. +// An empty asm statement (64-bit targets) or a volatile copy keeps the integer test. +inline uint64_t opaqueBits(double x) +{ + uint64_t bits = 0; + std::memcpy(&bits, &x, sizeof bits); +#if (defined(__GNUC__) || defined(__clang__)) && UINTPTR_MAX == 0xffffffffffffffffULL + __asm__("" : "+r"(bits)); + return bits; +#else + volatile uint64_t copy = bits; + return copy; +#endif +} + +// NaN and infinity from the bit pattern: unlike std::isnan / std::isfinite, these cannot be folded away +// by -ffast-math, -ffinite-math-only or -fno-honor-nans in the code that includes this header +inline bool isFiniteBits(double x) +{ + const uint64_t bits = opaqueBits(x); + return ((bits >> 52) & 0x7ff) != 0x7ff; +} + +inline bool isNanBits(double x) +{ + const uint64_t bits = opaqueBits(x); + return ((bits >> 52) & 0x7ff) == 0x7ff && (bits & 0xfffffffffffffULL) != 0; +} + +// 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 0000000000..ab04d4e527 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/detail/Operator.h @@ -0,0 +1,27 @@ +// 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-2381: 1 if fewer than two rows are above 1e-15 (e.g. a field zero-padded to a higher truncation) +// - 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/detail/OptimalOperator.h b/projects/spectral_complex/include/spectral_complex/detail/OptimalOperator.h new file mode 100644 index 0000000000..91f2147d24 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/detail/OptimalOperator.h @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// The laplacian operator P with the smallest expected packing error (ECC-2393) + +#pragma once + +#include + +namespace sc::detail +{ + +// How the packed coefficients are coded and how the message stores the operator +struct OptimalOperatorRequest +{ + int32_t bitsPerValue = 16; + // true: the decimal and the binary scale factor are optimised (sc::Method::bestPrecision) + bool bestPrecision = false; + // The decimal scale factor D of sc::Method::bits (unused with bestPrecision) + int32_t decimalScaleFactor = 0; + // The reference value is an IBM32 float (GRIB1), else an IEEE32 float (GRIB2) + bool ibmReference = false; + // The message stores the operator as an integer number of units: P = units / unitsPerOne, + // -maxUnits <= units <= maxUnits + int64_t unitsPerOne = 1000000; + int64_t maxUnits = 2147483646; +}; + +// The operator, in units, with the smallest expected squared error of the packed coefficients +// +// (2^E / 10^D)^2 / 12 * sum over the packed degrees n of (2n + 1) * (n(n + 1))^(-2P) +// +// among the operators that the message can store and with which the field can be coded +// (docs/laplacian_operator.md explains the formula and the search). +// - E and D are the scale factors that sc::parameters chooses for P. Degree n has 2n + 1 packed +// values with an error: unpacking sets the imaginary part of m = 0 to zero. +// - An operator can be coded if all factors (n(n + 1))^P and their inverses are normal numbers, +// sc::parameters accepts it without an underflow, and different coefficients keep different +// scaled values. +// - The minimum is found if the packed coefficients are not all positive or all negative (every real +// field: its imaginary parts of m = 0 are zero). Otherwise the result can be coded, but may be only +// a local minimum. +// +// Special cases: +// - No packed coefficients (JS = J): 0. +// - All packed coefficients equal (for example zero) and P = 0 can be coded: 0 (coded exactly). +// - The coefficients are too small for every operator (an underflow with each): 0. sc::parameters +// then codes them all as zero, as legacy ecCodes. +// +// Throws std::range_error if a coefficient is NaN or infinite, or if no operator can be coded and +// the coefficients are not too small. +// The caller (sc::optimalLaplacianOperator) checks the arguments: (J + 1) * (J + 2) values in +// ecCodes order, 0 <= JS <= J, 1 <= bitsPerValue <= 63, a valid decimal scale factor, +// unitsPerOne >= 1, 0 <= maxUnits < 2^52. +int64_t optimalOperatorUnits(const double* values, int32_t truncation, int32_t subTruncation, const OptimalOperatorRequest& request); + +} // namespace sc::detail diff --git a/projects/spectral_complex/include/spectral_complex/optimal_operator.h b/projects/spectral_complex/include/spectral_complex/optimal_operator.h new file mode 100644 index 0000000000..32302438c0 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/optimal_operator.h @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// The new laplacian operator (ECC-2393): the operator with the smallest expected error of the +// packed coefficients. It is separate from the legacy algorithm (spectral_complex.h: the fit of +// legacy ecCodes, sc::laplacianOperator, and the packing), which does not depend on it. + +#pragma once + +#include +#include +#include + +#include "spectral_complex/detail/OptimalOperator.h" +#include "spectral_complex/spectral_complex.h" + +namespace sc +{ + +// How a message stores the laplacian operator: as an integer number of units +enum class OperatorCoding +{ + GRIB1, // thousandths in 16 bits: -32.766 .. 32.766 + GRIB2 // millionths in 32 bits: -2147.483646 .. 2147.483646 +}; + +// A laplacian operator that a message can store +struct CodedOperator +{ + // The integer the message stores (GRIB1: key P, GRIB2: key laplacianScalingFactor) + int64_t units = 0; + // The operator: units / 1000 (GRIB1) or units / 1000000 (GRIB2), as ecCodes reads the key laplacianOperator. + // To store the operator, set the integer key to units: converting value back by truncation, + // (long)(value * 1000), gives units - 1 for about 1% of the operators (rounding is exact). + double value = 0; +}; + +// The laplacian operator with the smallest expected error of the packed coefficients (ECC-2393), +// among the operators that the message can store and with which the field can be packed and +// unpacked. docs/laplacian_operator.md describes the method and its limits. +// - sc::parameters(values, layout, result.value, method, ...) accepts the result, without an +// underflow (zeroCodes). Exception: if the coefficients are too small for every operator, the +// result is 0 and sc::parameters codes them all as zero, as legacy ecCodes. +// - The minimum is guaranteed for a real field (zero imaginary parts of m = 0). If the packed +// coefficients are all positive or all negative, the result may be only a local minimum. +// - To pack decoded values again unchanged, keep the operator of the message instead: any +// recomputed operator adds a new rounding error. +// - Needs the default rounding mode (to nearest). +// Throws std::range_error if a coefficient is NaN or infinite or if no operator can be coded, +// std::invalid_argument for invalid arguments. +inline CodedOperator optimalLaplacianOperator(const double* values, size_t count, const Layout& layout, const Method& method, + OperatorCoding coding = OperatorCoding::GRIB2) +{ + detail::checkCount("optimalLaplacianOperator", count, valueCount(layout)); + sp::detail::checkRange("bits per value", method.bitsPerValue(), 1, sp::detail::maxEncodingBitsPerValue); + detail::checkDecimalScaleFactor(method.decimalScaleFactor()); + if (coding != OperatorCoding::GRIB1 && coding != OperatorCoding::GRIB2) { + detail::invalid("unknown coding of the laplacian operator"); + } + detail::OptimalOperatorRequest request; + request.bitsPerValue = method.bitsPerValue(); + request.bestPrecision = method.isBestPrecision(); + request.decimalScaleFactor = method.decimalScaleFactor(); + request.ibmReference = method.referenceFormat() == ReferenceFormat::IBM32; + request.unitsPerOne = coding == OperatorCoding::GRIB1 ? 1000 : 1000000; + request.maxUnits = coding == OperatorCoding::GRIB1 ? 32766 : 2147483646; + CodedOperator result; + result.units = detail::optimalOperatorUnits(values, layout.truncation, layout.subTruncation, request); + result.value = static_cast(result.units) / static_cast(request.unitsPerOne); + return result; +} + +inline CodedOperator optimalLaplacianOperator(const std::vector& values, const Layout& layout, const Method& method, + OperatorCoding coding = OperatorCoding::GRIB2) +{ + return optimalLaplacianOperator(values.data(), values.size(), layout, method, coding); +} + +} // namespace sc 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 0000000000..bd870523c0 --- /dev/null +++ b/projects/spectral_complex/include/spectral_complex/spectral_complex.h @@ -0,0 +1,654 @@ +// 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 +#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; + } + + int32_t bitsPerValue() const { return bitsPerValue_; } + bool isBestPrecision() const { return bestPrecision_; } + // The decimal scale factor of Method::bits (0 for bestPrecision) + int32_t decimalScaleFactor() const { return decimalScaleFactor_; } + ReferenceFormat referenceFormat() const { return referenceFormat_; } + +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)); + } +} + +// The decimal scale factor D must fit the 16 bits of GRIB and 10^D must be a normal number (not +// zero, subnormal or infinite): throws std::invalid_argument otherwise. Checked before 10^D is +// computed, which takes |D| multiplications. +inline void checkDecimalScaleFactor(int32_t decimalScaleFactor) +{ + sp::detail::checkRange("decimal scale factor", decimalScaleFactor, -sp::detail::maxScaleFactor, sp::detail::maxScaleFactor); + if (decimalScaleFactor < DBL_MIN_10_EXP || decimalScaleFactor > DBL_MAX_10_EXP) { + invalid("the decimal scale factor " + std::to_string(decimalScaleFactor) + " is out of range (10^D must be between 1e" + + std::to_string(DBL_MIN_10_EXP) + " and 1e" + std::to_string(DBL_MAX_10_EXP) + ")"); + } +} + +// The factors (n(n + 1))^P of the packed degrees n > JS and their inverses (unpacking multiplies by +// them) must be normal numbers: throws std::range_error otherwise. An infinite factor times a zero +// coefficient is NaN, and the inverse of a subnormal factor is infinite. +inline void checkFactors(const std::vector& scals, int32_t subTruncation, double laplacianOperator) +{ + for (size_t n = static_cast(subTruncation) + 1; n < scals.size(); n++) { + // NaN (an operator that is NaN) from the bits: not folded away by -ffast-math in consumer code + if (!isFiniteBits(scals[n]) || !(scals[n] >= DBL_MIN && scals[n] <= 1.0 / DBL_MIN)) { + throw std::range_error("Spectral complex packing: the laplacian operator " + std::to_string(laplacianOperator) + + " is out of range (the factor of the degree " + std::to_string(n) + " or its inverse is not a normal number)"); + } + } +} + +// Packing multiplies a coefficient by 10^D before the factor (as legacy ecCodes), and unpacking +// divides (code * 2^E + R) / 10^D by the factor of its degree: both must stay finite and precise, +// also for a degree with a small factor. maxAbs: the largest absolute packed coefficient; maxCoded: +// the largest absolute scaled coefficient times 10^D; minFactor, maxFactor: the smallest and the +// largest factor of the packed degrees; codedError: the largest error of a coded value, +// min(2^E / 2, ymax - R) (a value closer to R than half a step gets the code 0). +inline bool decodable(double maxAbs, double maxCoded, double minFactor, double maxFactor, int32_t binaryScaleFactor, int32_t decimalScaleFactor, + double codedError) +{ + const double ln2 = 0.69314718055994530942, ln10 = 2.30258509299404568402; + const double logLimit = std::log(DBL_MAX / 4); + if (!isFiniteBits(maxAbs * sp::detail::sp_power(decimalScaleFactor, 10))) { + return false; // packing: the coefficient times 10^D + } + // The step 2^E / 10^D in the units of the coefficients + const double logStep = binaryScaleFactor * ln2 - decimalScaleFactor * ln10; + // A subnormal intermediate has an absolute error of up to 2^-1075: v * 10^D (packing, then times + // the factor) and (code * 2^E + R) / 10^D (unpacking, then divided by the factor) must stay + // precise to an eighth of the step + const double logTiny = -1075 * ln2, logEighth = 3 * ln2; + if (decimalScaleFactor != 0 && logTiny + std::log(maxFactor) > binaryScaleFactor * ln2 - logEighth) { + return false; + } + if (logTiny > logStep - logEighth) { + return false; + } + // Unpacking: (code * 2^E + R) / 10^D is at most (maxCoded + 2^E) / 10^D + if (std::max(std::log(maxCoded) - decimalScaleFactor * ln10, logStep) + ln2 > logLimit) { + return false; + } + // Divided by the factor of its degree: the coefficient plus at most the error of the coded value + // divided by the factor. Within the float range if the coefficients are (unpack), with a + // margin for the rounding. + const double limit = maxAbs <= FLT_MAX / 2 ? FLT_MAX / 2 : DBL_MAX / 4; + const double logError = std::log(codedError) - decimalScaleFactor * ln10 - std::log(minFactor); + return logError <= std::log(limit) && maxAbs + std::exp(logError) <= limit; +} + +// The codes of the smallest and the largest coded value y = (v * 10^D) * factor are within 0 and +// 2^bits - 1, computed as sc::pack (simple_packing) computes them +inline bool codesInRange(double ymin, double ymax, double referenceValue, int32_t binaryScaleFactor, int32_t bitsPerValue) +{ + const double divisor = sp::detail::sp_power(-binaryScaleFactor, 2); + const double limit = std::ldexp(1.0, bitsPerValue); + const double lo = (ymin - referenceValue) * divisor + 0.5; + const double hi = (ymax - referenceValue) * divisor + 0.5; + return lo >= 0.0 && hi < limit; // false for NaN +} + +// ECC-2393: throws std::range_error unless the coefficients can be packed and unpacked with the +// scaling: packing and unpacking must stay finite and precise (decodable), and the codes that +// sc::pack computes, (v * 10^D) * factor, must be in range. min and max are the extremes of +// v * factor, from which the scaling was chosen as legacy ecCodes does: 10^D * (v * factor) differs +// from the coded values in the last bits, and when a product is subnormal. +inline void checkPackable(const double* values, int32_t J, int32_t JS, const std::vector& scals, double min, double max, + const sp::Scaling& scaling, double laplacianOperator) +{ + // Calls f(v, factor) for every packed coefficient + const auto forEachPacked = [&](auto f) { + 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++, i += 2) { + f(values[i], scals[n]); + f(values[i + 1], scals[n]); + } + } + }; + + // The factors grow or fall with n + const double factor1 = scals[static_cast(JS) + 1], factor2 = scals[static_cast(J)]; + const double minFactor = std::min(factor1, factor2), maxFactor = std::max(factor1, factor2); + + // The extremes of the coded values, as sc::pack computes them + const double d = sp::detail::sp_power(scaling.decimalScaleFactor, 10); + double ymin = min, ymax = max; + if (scaling.decimalScaleFactor != 0) { + bool first = true; + forEachPacked([&](double v, double factor) { + const double y = (v * d) * factor; + ymin = (first || y < ymin) ? y : ymin; + ymax = (first || y > ymax) ? y : ymax; + first = false; + }); + } + const double maxCoded = std::max(std::fabs(min), std::fabs(max)) * d; + const double codedError = std::min(std::ldexp(0.5, scaling.binaryScaleFactor), std::max(0.0, ymax - scaling.referenceValue)); + + // The largest absolute packed coefficient: an upper bound, |v| <= |v * factor| / minFactor, is + // enough if the check passes with it (the check gets stricter with a larger value). Only + // otherwise the coefficients are scanned. + double maxAbs = std::max(std::fabs(min), std::fabs(max)) / minFactor * (1 + 4 * DBL_EPSILON); + const auto passes = [&] { + return decodable(maxAbs, maxCoded, minFactor, maxFactor, scaling.binaryScaleFactor, scaling.decimalScaleFactor, codedError); + }; + if (!(maxAbs <= FLT_MAX / 2 && passes())) { + maxAbs = 0; + forEachPacked([&](double v, double) { maxAbs = std::max(maxAbs, std::fabs(v)); }); + } + if (!passes() || !codesInRange(ymin, ymax, scaling.referenceValue, scaling.binaryScaleFactor, scaling.bitsPerValue)) { + throw std::range_error("Spectral complex packing: the coefficients cannot be packed and unpacked with the laplacian operator " + + std::to_string(laplacianOperator) + " (an intermediate value or a decoded value overflows or is not precise)"); + } +} + +// (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, a factor (n(n + 1))^P or its inverse is not a normal number, or packing +// or unpacking would overflow, see detail::decodable), +// std::invalid_argument for invalid arguments (also a decimal scale factor D beyond 16 bits or +// with a 10^D that is not a normal number). +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); + detail::checkDecimalScaleFactor(method.bestPrecision_ ? 0 : method.decimalScaleFactor_); + + 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); + detail::checkFactors(scals, JS, laplacianOperator); + double min = 0; + double max = 0; + bool first = true; + bool special = false; // NaN or infinity: 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++) { + // NaN or infinity in the input, from the bits of the value loaded from memory: not folded + // away by -ffast-math (a test of the product could be: the compiler may assume that a + // fast-math multiplication gives no NaN) + const double x = values[i++]; + special |= !detail::isFiniteBits(x); + const double v = x * scals[n]; + 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 (special || !detail::isFiniteBits(min) || !detail::isFiniteBits(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; + detail::checkPackable(values, J, JS, scals, min, max, p.scaling, laplacianOperator); + 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); + detail::checkPackable(values, J, JS, scals, min, max, p.scaling, laplacianOperator); + 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 0000000000..1e4cef0599 --- /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 0000000000..1ed6e4dabd --- /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 (isNanBits(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 (isNanBits(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 0000000000..cecdbdb94e --- /dev/null +++ b/projects/spectral_complex/src/Operator.cc @@ -0,0 +1,149 @@ +// 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, ECC-2381 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])); + } + } + + // ECC-2381: fewer than two rows above zeps, e.g. a field zero-padded to a higher truncation. A + // fit would be driven by the artificial zeps norms of the other rows: 1, as for GRIB-172 + int64_t validNorms = 0; + for (int64_t loop = ismin; loop <= ismax; loop++) { + if (norms[loop] > zeps) + validNorms++; + } + if (validNorms < 2) + return 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/src/OptimalOperator.cc b/projects/spectral_complex/src/OptimalOperator.cc new file mode 100644 index 0000000000..14e908bd07 --- /dev/null +++ b/projects/spectral_complex/src/OptimalOperator.cc @@ -0,0 +1,641 @@ +// SPDX-FileCopyrightText: 2026 European Centre for Medium-Range Weather Forecasts (ECMWF) +// SPDX-License-Identifier: Apache-2.0 + +// The laplacian operator with the smallest expected packing error (ECC-2393). +// +// One pass over the coefficients gives the largest and the smallest packed coefficient of each +// degree n. With them the scaling that sc::parameters chooses for an operator P is computed exactly +// in O(J) (chooseScaling below): the scaled extremes are max(hi(n) s(n)) and min(lo(n) s(n)) with +// the factors s(n) = (n(n + 1))^P, since a multiplication by a positive factor keeps the order. +// docs/laplacian_operator.md describes the method. +// +// The error to minimise is G(P) = log(step(P)) + log(W(P)) / 2 with step = 2^E / 10^D and +// W(P) = sum w(n) (n(n + 1))^(-2P). W falls with P, and the step is constant on intervals of P +// (it grows with P): only the largest operator of each step can be the minimum. The search starts +// at the minimum of F(P) = log(range(P)) + log(W(P)) / 2, the error with a continuous step, and +// visits the steps upwards and downwards. F bounds G from below, which ends the search. +// +// This needs a largest scaled coefficient that grows with P and a smallest one that falls: packed +// coefficients that are not all positive or all negative. Then the range and the step grow with P +// and F is convex. A real field always qualifies: its imaginary parts of m = 0 are zero. For other +// fields the range can have a dip (where the scaled coefficients are nearly equal) and the result +// is an operator that can be coded and is a local minimum, but not necessarily the smallest error. + +#include "spectral_complex/detail/OptimalOperator.h" + +#include +#include +#include +#include +#include +#include + +#include "spectral_complex/detail/Float.h" +#include "simple_packing/simple_packing.h" + +namespace sc::detail +{ +namespace +{ + +// --- What sc::parameters does with an operator (the scaling of legacy ecCodes and the checks of the +// library), computed from the extremes of each degree. The new algorithm keeps its own copy: the +// legacy algorithm (spectral_complex.h) does not depend on it. The tests compare it with +// sc::parameters (brute force over all GRIB1 operators). --- + + +// The packed coefficients v of a field and the factors s = (n(n + 1))^P of their degrees +struct ScaledRange +{ + double min = 0, max = 0; // the extremes of v * s (without 10^D, as legacy ecCodes) + double maxAbs = 0; // the largest |v| + double minFactor = 1, maxFactor = 1; // the smallest and the largest s +}; + +enum class ScalingResult +{ + Ok, + TooLarge, // the reference value or the binary scale factor is out of range + Underflow, // no binary scale factor >= -127: legacy ecCodes codes all coefficients as zero + Undecodable, // packing or unpacking would overflow or lose precision (see decodable) +}; + +// Packing multiplies a coefficient by 10^D before the factor (as legacy ecCodes), and unpacking +// divides (code * 2^E + R) / 10^D by the factor of its degree: both must stay finite and precise, +// also for a degree with a small factor. maxCoded: the largest absolute scaled coefficient times 10^D; +// codedError: the largest error of a coded value, min(2^E / 2, ymax - R) (a value closer to R than +// half a step gets the code 0). +bool decodable(const ScaledRange& r, double maxCoded, int32_t binaryScaleFactor, int32_t decimalScaleFactor, double codedError) +{ + const double ln2 = 0.69314718055994530942, ln10 = 2.30258509299404568402; + const double logLimit = std::log(DBL_MAX / 4); + if (!isFiniteBits(r.maxAbs * sp::detail::sp_power(decimalScaleFactor, 10))) { + return false; // packing: the coefficient times 10^D + } + // The step 2^E / 10^D in the units of the coefficients + const double logStep = binaryScaleFactor * ln2 - decimalScaleFactor * ln10; + // A subnormal intermediate has an absolute error of up to 2^-1075: v * 10^D (packing, then times + // the factor) and (code * 2^E + R) / 10^D (unpacking, then divided by the factor) must stay + // precise to an eighth of the step + const double logTiny = -1075 * ln2, logEighth = 3 * ln2; + if (decimalScaleFactor != 0 && logTiny + std::log(r.maxFactor) > binaryScaleFactor * ln2 - logEighth) { + return false; + } + if (logTiny > logStep - logEighth) { + return false; + } + // Unpacking: (code * 2^E + R) / 10^D is at most (maxCoded + 2^E) / 10^D + if (std::max(std::log(maxCoded) - decimalScaleFactor * ln10, logStep) + ln2 > logLimit) { + return false; + } + // Divided by the factor of its degree: the coefficient plus at most the error of the coded value + // divided by the factor. Within the float range if the coefficients are (unpack), with a + // margin for the rounding. + const double limit = r.maxAbs <= FLT_MAX / 2 ? FLT_MAX / 2 : DBL_MAX / 4; + const double logError = std::log(codedError) - decimalScaleFactor * ln10 - std::log(r.minFactor); + return logError <= std::log(limit) && r.maxAbs + std::exp(logError) <= limit; +} + +// The codes of the smallest and the largest coded value y = (v * 10^D) * factor are within 0 and +// 2^bits - 1, computed as sc::pack (simple_packing) computes them +bool codesInRange(double ymin, double ymax, double referenceValue, int32_t binaryScaleFactor, int32_t bitsPerValue) +{ + const double divisor = sp::detail::sp_power(-binaryScaleFactor, 2); + const double limit = std::ldexp(1.0, bitsPerValue); + const double lo = (ymin - referenceValue) * divisor + 0.5; + const double hi = (ymax - referenceValue) * divisor + 0.5; + return lo >= 0.0 && hi < limit; // false for NaN +} + +// The reference value (half the float range: the nearest smaller float of a negative minimum is +// further from zero) and the range of the scaled coefficients (a binary scale factor <= 127) fit +bool scaledRangeFits(const ScaledRange& r, const OptimalOperatorRequest& q) +{ + const double dd = q.bestPrecision ? 1.0 : sp::detail::sp_power(q.decimalScaleFactor, 10); + const double refLimit = 0.5 * (q.ibmReference ? ibm32Max() : ieee32Max()); + const double rangeLimit = std::ldexp(std::ldexp(1.0, q.bitsPerValue) - 1, 127); + return isFiniteBits(r.min) && isFiniteBits(r.max) && std::fabs(dd * r.min) <= refLimit && std::fabs(dd * r.max) <= refLimit && + dd * (r.max - r.min) <= rangeLimit; +} + +// The scaling of the packed coefficients, as legacy ecCodes chooses it: the reference value R, the +// binary scale factor E and the decimal scale factor D (s.bitsPerValue is not set). Ok only if the +// coefficients can be packed and unpacked with it. codedExtremes(d) returns the extremes +// (min, max) of the coded values (v * d) * factor, computed as sc::pack computes them (they differ +// from d * min and d * max in the last bits, and when a product is subnormal). +template +ScalingResult chooseScaling(const ScaledRange& r, const OptimalOperatorRequest& q, CodedExtremes codedExtremes, sp::Scaling& s) +{ + s.referenceValue = 0; + s.binaryScaleFactor = 0; + s.decimalScaleFactor = q.bestPrecision ? 0 : q.decimalScaleFactor; + + if (!scaledRangeFits(r, q)) { + return ScalingResult::TooLarge; + } + const double dd = q.bestPrecision ? 1.0 : sp::detail::sp_power(q.decimalScaleFactor, 10); + + if (q.bestPrecision) { + try { + const sp::ReferenceFormat format = q.ibmReference ? sp::ReferenceFormat::IBM32 : sp::ReferenceFormat::IEEE32; + const sp::Scaling b = sp::scaling(r.min, r.max, sp::Method::bestPrecision(q.bitsPerValue).referenceFormat(format)); + s.referenceValue = b.referenceValue; + s.binaryScaleFactor = b.binaryScaleFactor; + s.decimalScaleFactor = b.decimalScaleFactor; + } + catch (const std::exception&) { + return ScalingResult::TooLarge; + } + } + else { + const std::optional ref = + sp::detail::nearest_smaller_value(dd * r.min, q.ibmReference ? sp::detail::FloatType::IBM32 : sp::detail::FloatType::IEEE32); + if (!ref) { + return ScalingResult::TooLarge; + } + std::optional e; + try { + e = sp::detail::get_binary_scale_factor(dd * r.max, *ref, q.bitsPerValue); + } + catch (const std::range_error&) { + return ScalingResult::TooLarge; // a binary scale factor above 127 + } + if (!e) { + return ScalingResult::Underflow; // R = 0, E = 0 + } + s.referenceValue = *ref; + s.binaryScaleFactor = static_cast(*e); + } + + // ECC-2393: packing and unpacking must stay finite and precise, and the codes in range + const double d = sp::detail::sp_power(s.decimalScaleFactor, 10); + double ymin = r.min, ymax = r.max; + if (s.decimalScaleFactor != 0) { + codedExtremes(d, ymin, ymax); + } + const double maxCoded = std::max(std::fabs(r.min), std::fabs(r.max)) * d; + const double codedError = std::min(std::ldexp(0.5, s.binaryScaleFactor), std::max(0.0, ymax - s.referenceValue)); + if (!decodable(r, maxCoded, s.binaryScaleFactor, s.decimalScaleFactor, codedError) || + !codesInRange(ymin, ymax, s.referenceValue, s.binaryScaleFactor, q.bitsPerValue)) { + return ScalingResult::Undecodable; + } + return ScalingResult::Ok; +} + +// --- The search --- + + +// The packed degrees n = JS + 1 .. J, arrays indexed by n - JS - 1 +struct Rows +{ + size_t count = 0; + std::vector hi, lo; // the largest and the smallest packed coefficient of the degree + std::vector logHi, logLo; // log of their absolute values (unused for a zero) + std::vector base; // n(n + 1), as sc::parameters computes it + std::vector x; // log(n(n + 1)) + std::vector w; // the number of packed values with an error: 2n + 1 + double maxAbs = 0; // the largest absolute packed coefficient + bool constant = true; // all packed coefficients are equal +}; + +Rows rowsOf(const double* values, int64_t J, int64_t JS) +{ + Rows r; + r.count = static_cast(J - JS); + r.hi.assign(r.count, -HUGE_VAL); + r.lo.assign(r.count, HUGE_VAL); + bool special = false; + size_t i = 0; + for (int64_t m = 0; m <= J; m++) { + int64_t n = m; + if (m <= JS) { + i += 2 * static_cast(JS - m + 1); + n = JS + 1; + } + for (size_t j = static_cast(n - JS - 1); j < r.count; j++, i += 2) { + const double a = values[i], b = values[i + 1]; + special |= !isFiniteBits(a) || !isFiniteBits(b); + r.hi[j] = std::max({ r.hi[j], a, b }); + r.lo[j] = std::min({ r.lo[j], a, b }); + } + } + if (special) { + throw std::range_error("Spectral complex packing: a coefficient is NaN or infinite"); + } + + r.logHi.resize(r.count); + r.logLo.resize(r.count); + r.base.resize(r.count); + r.x.resize(r.count); + r.w.resize(r.count); + for (size_t j = 0; j < r.count; j++) { + const size_t n = static_cast(JS) + 1 + j; + r.base[j] = static_cast(n * (n + 1)); + r.x[j] = std::log(r.base[j]); + // n + 1 complex coefficients (m = 0..n); unpack sets the imaginary part of m = 0 to zero (a real field) + r.w[j] = static_cast(2 * n + 1); + r.logHi[j] = r.hi[j] != 0 ? std::log(std::fabs(r.hi[j])) : 0.0; + r.logLo[j] = r.lo[j] != 0 ? std::log(std::fabs(r.lo[j])) : 0.0; + r.constant = r.constant && r.hi[j] == r.lo[j] && r.hi[j] == r.hi[0]; + r.maxAbs = std::max({ r.maxAbs, std::fabs(r.hi[j]), std::fabs(r.lo[j]) }); + } + return r; +} + +// log(W(P)) = log(sum w(n) (n(n + 1))^(-2P)), and the mean of x = log(n(n + 1)) with these weights +double logW(const Rows& r, double P, double* meanX = nullptr) +{ + // The largest term has the exponent 0 (x grows with n) + const double top = -2 * P * (P >= 0 ? r.x.front() : r.x.back()); + double sum = 0, sumX = 0; + for (size_t j = 0; j < r.count; j++) { + const double e = r.w[j] * std::exp(-2 * P * r.x[j] - top); + sum += e; + sumX += e * r.x[j]; + } + if (meanX) { + *meanX = sumX / sum; + } + return top + std::log(sum); +} + +// The scaled extremes max(hi(n) s(n)) and min(lo(n) s(n)) divided by exp(shift), the largest scaled +// absolute coefficient: no overflow for any P +struct Extremes +{ + double max = 0, min = 0, shift = -HUGE_VAL; + size_t jmax = 0, jmin = 0; +}; + +Extremes extremes(const Rows& r, double P) +{ + Extremes e; + for (size_t j = 0; j < r.count; j++) { + if (r.hi[j] != 0) + e.shift = std::max(e.shift, r.logHi[j] + P * r.x[j]); + if (r.lo[j] != 0) + e.shift = std::max(e.shift, r.logLo[j] + P * r.x[j]); + } + for (size_t j = 0; j < r.count; j++) { + const double a = r.hi[j] != 0 ? std::copysign(std::exp(r.logHi[j] + P * r.x[j] - e.shift), r.hi[j]) : 0.0; + const double b = r.lo[j] != 0 ? std::copysign(std::exp(r.logLo[j] + P * r.x[j] - e.shift), r.lo[j]) : 0.0; + if (j == 0 || a > e.max) { + e.max = a; + e.jmax = j; + } + if (j == 0 || b < e.min) { + e.min = b; + e.jmin = j; + } + } + return e; +} + +// F(P) = log(range(P)) + log(W(P)) / 2: the log of the expected error if the step were continuous, +// up to a constant (-HUGE_VAL for a zero range) +double continuousError(const Rows& r, double P) +{ + const Extremes e = extremes(r, P); + const double range = e.max - e.min; + return range > 0 ? std::log(range) + e.shift + 0.5 * logW(r, P) : -HUGE_VAL; +} + +// The derivative of F: the degree where the range grows minus the weighted mean degree of the error +double continuousSlope(const Rows& r, double P) +{ + const Extremes e = extremes(r, P); + const double range = e.max - e.min; + if (!(range > 0)) { + return 0; + } + double meanX = 0; + logW(r, P, &meanX); + return (e.max * r.x[e.jmax] - e.min * r.x[e.jmin]) / range - meanX; +} + +// What sc::parameters does with an operator +struct Coding +{ + enum class State + { + Ok, + TooLarge, // a smaller operator is needed + TooSmall // a larger operator is needed + }; + State state = State::TooLarge; + // A scaling exists (Ok, or packing and unpacking would overflow or lose precision): logStep is + // log(2^E / 10^D), and the step grows with P + bool hasStep = false; + double logStep = 0; + bool underflow = false; // sc::parameters codes all coefficients as zero + + bool ok() const { return state == State::Ok; } +}; +using State = Coding::State; + +class Search +{ +public: + Search(const Rows& rows, const OptimalOperatorRequest& request) : + r_(rows), q_(request), unitsPerOne_(static_cast(request.unitsPerOne)), + // 2^E / 10^D * (2^bits - 0.5) > range: the bound of the step from below + logCodes_(std::log(std::ldexp(1.0, request.bitsPerValue) - 0.5)), + factors_(rows.count) + { + } + + // The operator of k units, as ecCodes reads it from the message + double operatorOf(int64_t k) const { return static_cast(k) / unitsPerOne_; } + + // What sc::parameters does with the operator of k units + Coding coding(int64_t k) const + { + Coding c; + const double P = operatorOf(k); + ScaledRange range; + for (size_t j = 0; j < r_.count; j++) { + // The factor and its inverse (used by unpack) must be normal numbers + const double s = std::pow(r_.base[j], P); + if (!(s >= DBL_MIN)) { + c.state = State::TooSmall; + return c; + } + if (!(s <= 1.0 / DBL_MIN)) { + return c; + } + factors_[j] = s; + const double a = r_.hi[j] * s, b = r_.lo[j] * s; + range.max = j == 0 ? a : std::max(range.max, a); + range.min = j == 0 ? b : std::min(range.min, b); + } + range.maxAbs = r_.maxAbs; + range.minFactor = std::min(factors_.front(), factors_.back()); // the factors grow or fall with n + range.maxFactor = std::max(factors_.front(), factors_.back()); + + if (!scaledRangeFits(range, q_)) { + return c; + } + // Different coefficients with the same scaled value (the products underflow): not coded + const double dd = q_.bestPrecision ? 1.0 : sp::detail::sp_power(q_.decimalScaleFactor, 10); + if (!r_.constant && !(dd * range.max > dd * range.min)) { + c.state = State::TooSmall; + return c; + } + + // The extremes of each degree give the extremes of the coded values (the products keep the order) + const auto codedExtremes = [&](double d, double& ymin, double& ymax) { + for (size_t j = 0; j < r_.count; j++) { + const double a = (r_.hi[j] * d) * factors_[j], b = (r_.lo[j] * d) * factors_[j]; + ymax = j == 0 ? a : std::max(ymax, a); + ymin = j == 0 ? b : std::min(ymin, b); + } + }; + sp::Scaling s; + const ScalingResult result = chooseScaling(range, q_, codedExtremes, s); + if (result == ScalingResult::TooLarge) { + return c; + } + if (result == ScalingResult::Underflow) { + c.state = State::TooSmall; + c.underflow = true; + return c; + } + c.hasStep = true; + c.logStep = s.binaryScaleFactor * std::log(2.0) - s.decimalScaleFactor * std::log(10.0); + if (result == ScalingResult::Ok) { + c.state = State::Ok; + } + else { + // Undecodable: the factor of a degree is too small compared with the step + c.state = P < 0 ? State::TooSmall : State::TooLarge; + } + return c; + } + + int64_t run() const + { + const int64_t k0 = start(); + int64_t best = k0; + double bestError = error(k0, coding(k0)); + walkUp(k0, best, bestError); + walkDown(k0, best, bestError); + return best; + } + +private: + // G: the log of the expected error (up to a constant) with the step of the coding c + double error(int64_t k, const Coding& c) const { return c.logStep + 0.5 * logW(r_, operatorOf(k)); } + + // A lower bound of G for the operator of k units + double errorBound(int64_t k) const { return continuousError(r_, operatorOf(k)) - logCodes_; } + + // The operator, in units, where the convex function F has its minimum + int64_t continuousOptimum() const + { + if (r_.count == 1) { + return 0; // F is constant + } + const auto slope = [&](int64_t k) { return continuousSlope(r_, operatorOf(k)); }; + int64_t a = -q_.maxUnits, b = q_.maxUnits; + if (a == b || !(slope(a) < 0)) { + return a; + } + if (slope(b) < 0) { + return b; + } + while (b - a > 1) { + const int64_t mid = a + (b - a) / 2; + (slope(mid) < 0 ? a : b) = mid; + } + return continuousError(r_, operatorOf(a)) <= continuousError(r_, operatorOf(b)) ? a : b; + } + + // An operator that can be coded, near the minimum of the continuous error. Throws if there is + // none; 0 if the coefficients are too small for every operator. + int64_t start() const + { + int64_t k = continuousOptimum(); + Coding c = coding(k); + if (!c.ok()) { + // The nearest operator that is not too large (or not too small) + const bool tooLarge = c.state == State::TooLarge; + const auto pred = [&](int64_t kk) { return coding(kk).state != c.state; }; + const std::optional f = seek(k, tooLarge ? -q_.maxUnits : q_.maxUnits, pred); + if (f) { + k = boundary(f->at, f->before, pred); + c = coding(k); + } + } + if (!c.ok()) { + // Near the limits of the doubles and floats the operators that can be coded need not be + // next to the minimum of the continuous error + const std::optional scanned = scanForCodable(k); + if (scanned) { + return *scanned; + } + if (coding(0).underflow) { + return 0; // too small for every operator: sc::parameters codes them all as zero + } + throw std::range_error("Spectral complex packing: the coefficients cannot be coded with any laplacian operator"); + } + return k; + } + + // The operators of a step: Ok (or, with undecodable, any with a scaling) and the step at most logStep + auto withStep(double logStep, bool undecodable) const + { + return [this, logStep, undecodable](int64_t k) { + const Coding c = coding(k); + return (c.ok() || (undecodable && c.hasStep)) && c.logStep <= logStep; + }; + } + + // Keeps k if its error is smaller than the best one + void consider(int64_t k, const Coding& c, int64_t& best, double& bestError) const + { + if (c.ok()) { + const double e = error(k, c); + if (e < bestError) { + bestError = e; + best = k; + } + } + } + + // The steps above k0: the largest operator of each, until the lower bound of the error exceeds + // the best one. A step whose largest operator cannot be packed and unpacked (an overflow or a + // loss of precision near the limits of the doubles and floats) is skipped, not the end. + void walkUp(int64_t k0, int64_t& best, double& bestError) const + { + int64_t last = extend(k0, withStep(coding(k0).logStep, false)); + consider(last, coding(last), best, bestError); + while (last < q_.maxUnits) { + const int64_t first = last + 1; + const Coding c = coding(first); + if (!c.hasStep || !(errorBound(first) < bestError)) { + break; + } + last = extend(first, withStep(c.logStep, !c.ok())); + consider(last, coding(last), best, bestError); + } + } + + // The steps below k0: the largest operator of each smaller step, until the lower bound of the + // error exceeds the best one or no smaller step can be coded + void walkDown(int64_t k0, int64_t& best, double& bestError) const + { + double logStep = coding(k0).logStep; + for (int64_t first = k0; first > -q_.maxUnits;) { + const auto below = [&](int64_t k) { + const Coding c = coding(k); + return (c.state == State::TooSmall && !c.hasStep) || (c.hasStep && c.logStep < logStep); + }; + const std::optional f = seek(first, -q_.maxUnits, below); + if (!f) { + break; + } + const int64_t k = boundary(f->at, f->before, below); + const Coding c = coding(k); + if (!c.hasStep || !(errorBound(k) < bestError)) { + break; + } + consider(k, c, best, bestError); + logStep = c.logStep; + first = k; + } + } + + // The operator with the smallest error among about 4200 operators that can be coded: evenly + // spaced over all operators, and spaced by powers of two from both ends and from k0 + std::optional scanForCodable(int64_t k0) const + { + std::vector candidates; + const int64_t n = 4096; + for (int64_t i = 0; i <= n; i++) { + candidates.push_back(-q_.maxUnits + static_cast(static_cast(2 * q_.maxUnits) * static_cast(i) / static_cast(n))); + } + for (int64_t d = 1; d <= q_.maxUnits; d *= 2) { + candidates.push_back(q_.maxUnits - d); + candidates.push_back(-q_.maxUnits + d); + if (k0 + d <= q_.maxUnits) + candidates.push_back(k0 + d); + if (k0 - d >= -q_.maxUnits) + candidates.push_back(k0 - d); + } + std::optional best; + double bestError = HUGE_VAL; + for (int64_t k : candidates) { + const Coding c = coding(k); + if (c.ok() && (!best || error(k, c) < bestError)) { + best = k; + bestError = error(k, c); + } + } + return best; + } + + struct Found + { + int64_t at = 0; // pred holds here + int64_t before = 0; // the last operator tried before, where it does not hold + }; + + // The first operator on the way from a (where pred does not hold) to limit, in growing steps, + // for which pred holds + template + static std::optional seek(int64_t a, int64_t limit, Pred pred) + { + const int64_t direction = limit >= a ? 1 : -1; + for (int64_t step = 1; a != limit; step *= 2) { + const int64_t b = (direction * (limit - a) <= step) ? limit : a + direction * step; + if (pred(b)) { + return Found{ b, a }; + } + a = b; + } + return std::nullopt; + } + + // pred holds at a and not at b: the last operator on the way from a to b for which it holds + // (pred is expected to change once) + template + static int64_t boundary(int64_t a, int64_t b, Pred pred) + { + while (b - a > 1 || a - b > 1) { + const int64_t mid = a + (b - a) / 2; + (pred(mid) ? a : b) = mid; + } + return a; + } + + // pred holds at a: the last operator above a for which it still holds + template + int64_t extend(int64_t a, Pred pred) const + { + const std::optional f = seek(a, q_.maxUnits, [&](int64_t k) { return !pred(k); }); + return f ? boundary(f->before, f->at, pred) : q_.maxUnits; + } + + const Rows& r_; + const OptimalOperatorRequest& q_; + double unitsPerOne_; + double logCodes_; + mutable std::vector factors_; // the factors of the degrees, of the last coding() +}; + +} // namespace + +int64_t optimalOperatorUnits(const double* values, int32_t truncation, int32_t subTruncation, const OptimalOperatorRequest& request) +{ + if (subTruncation >= truncation) { + return 0; // no packed coefficients + } + const Rows rows = rowsOf(values, truncation, subTruncation); + const Search search(rows, request); + if (rows.constant && search.coding(0).ok()) { + return 0; // a zero range: coded exactly + } + return search.run(); +} + +} // namespace sc::detail diff --git a/projects/spectral_complex/tests/CMakeLists.txt b/projects/spectral_complex/tests/CMakeLists.txt new file mode 100644 index 0000000000..66d09e26ae --- /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 spectral_complex_legacy_reference) + 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(