NEP 4.3.0
NetCDF Expansion Pack
Loading...
Searching...
No Matches
nxcdf_convert.c File Reference

Internal numeric conversion and quantization for nxCDF. More...

#include "nxcdf/nxcdf.h"
#include "config.h"
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "nxcdf_internal.h"

Macros

#define CONVERT_SOURCE(T, REAL)
 Macro: expand a loop converting one source C type to every standard destination type.
#define DEST_INT(ID, D, LOW, HIGH, FILL)
 Macro: one case of CONVERT_SOURCE writing an integer destination with guarded conversion.

Functions

static int numeric (nc_type t)
 Test whether a type is a standard numeric atomic type.
static uint16_t encode_bfloat (float f, int *range)
 Encode a float as bfloat16 with round-to-nearest-even.
static uint16_t encode_bfloat_double (double d, int *range)
 Encode a double as bfloat16 with a single final rounding.
static float decode_half (uint16_t h)
 Decode an IEEE 754 binary16 bit pattern as float.
static uint16_t encode_half (float f, int *range)
 Encode a float as IEEE 754 binary16 with round-to-nearest-even.
static uint16_t encode_half_double (double d, int *range)
 Encode a double as IEEE 754 binary16 with a single final rounding.
static void quantize (void *data, nc_type t, size_t n, const void *fill, int mode, int nsd)
 Apply netCDF quantization in place after conversion.
static int integer_range (nc_type source, nc_type target, unsigned long long u, long long s)
 Check integer range without passing 64-bit boundaries through floating point.
int nxcdf_convert_type (const void *src, void *dest, nc_type src_type, nc_type dest_type, size_t len, int *range_error, const void *fill_value, int strict_nc3, int quantize_mode, int nsd, int fill_on_overflow)
 NEP's internal numeric conversion engine for nxCDF.

Detailed Description

Internal numeric conversion and quantization for nxCDF.

Author
Edward Hartnett, Intelligent Data Design, Inc.

Macro Definition Documentation

◆ CONVERT_SOURCE

#define CONVERT_SOURCE ( T,
REAL )
Value:
do { \
const T *input = src; \
const int real_source = REAL; \
size_t j; \
switch (dest_type) { \
DEST_INT(NC_BYTE, signed char, -0x1p7L, 0x1p7L, NC_FILL_BYTE) \
DEST_INT(NC_UBYTE, unsigned char, 0, 0x1p8L, NC_FILL_UBYTE) \
DEST_INT(NC_SHORT, short, -0x1p15L, 0x1p15L, NC_FILL_SHORT) \
DEST_INT(NC_USHORT, unsigned short, 0, 0x1p16L, NC_FILL_USHORT) \
DEST_INT(NC_INT, int, -0x1p31L, 0x1p31L, NC_FILL_INT) \
DEST_INT(NC_UINT, unsigned int, 0, 0x1p32L, NC_FILL_UINT) \
DEST_INT(NC_INT64, long long, -0x1p63L, 0x1p63L, NC_FILL_INT64) \
DEST_INT(NC_UINT64, unsigned long long, 0, 0x1p64L, NC_FILL_UINT64) \
case NC_FLOAT: \
for (j = 0; j < len; j++) { \
long double v = (long double)input[j]; \
if (isfinite(v) && fabsl(v) > FLT_MAX) { \
*range_error = 1; \
((float *)dest)[j] = signbit(v) ? -INFINITY : INFINITY; \
} else ((float *)dest)[j] = (float)input[j]; \
} \
break; \
case NC_DOUBLE: \
for (j = 0; j < len; j++) ((double *)dest)[j] = (double)input[j]; \
break; \
} \
} while (0)

Macro: expand a loop converting one source C type to every standard destination type.

Used inside nxcdf_convert_type()'s switch (src_type); generates the per-destination loops, including DEST_INT cases with range checking and NC_FLOAT/NC_DOUBLE cases with overflow detection.

Parameters
TSource C type.
REALWhether the source is floating point.

◆ DEST_INT

#define DEST_INT ( ID,
D,
LOW,
HIGH,
FILL )
Value:
case ID: \
for (j = 0; j < len; j++) { \
long double v = (long double)input[j]; \
int outside; \
if (real_source && fill_on_overflow) v = truncl(v); \
outside = real_source \
? (!isfinite(v) || v < (LOW) || v >= (HIGH)) \
: integer_range(src_type, ID, (unsigned long long)input[j], (long long)input[j]); \
if (outside && !(strict_nc3 && src_type == NC_UBYTE && ID == NC_BYTE)) \
*range_error = 1; \
((D *)dest)[j] = outside && real_source && fill_on_overflow \
? (fill_value ? *(const D *)fill_value : (D)(FILL)) : (D)input[j]; \
} \
break;
static int integer_range(nc_type source, nc_type target, unsigned long long u, long long s)
Check integer range without passing 64-bit boundaries through floating point.
Definition nxcdf_convert.c:308

Macro: one case of CONVERT_SOURCE writing an integer destination with guarded conversion.

Integer sources are checked by integer_range(). Real sources get one of two checks, keyed on fill_on_overflow: the netcdf-c attribute semantics check the raw input before truncation (a float like -0.5 still overflows an unsigned destination), while the NEP variable semantics check the truncated value, so fractions near a bound simply truncate. Out-of-range values set *range_error; the store is the fill value when fill_on_overflow is set (NEP write semantics) or the raw cast otherwise (netcdf-c attribute-read semantics). The classic NC_UBYTE→NC_BYTE overflow is tolerated under _NCProperties strict-nc3 semantics.

Parameters
IDNetCDF destination type.
DDestination C type.
LOWInclusive lower bound.
HIGHExclusive upper bound.
FILLDefault fill value.

Function Documentation

◆ decode_half()

float decode_half ( uint16_t h)
static

Decode an IEEE 754 binary16 bit pattern as float.

The conversion is exact: subnormals are normalized, infinities and NaN payloads are preserved into the float NaN.

Parameters
hEncoded bits.
Returns
Decoded value.

◆ encode_bfloat()

uint16_t encode_bfloat ( float f,
int * range )
static

Encode a float as bfloat16 with round-to-nearest-even.

bfloat16 is the top 16 bits of an IEEE-754 float, so encoding is a right shift — but the dropped bits must round correctly. Adding 0x7fff + lsb before shifting implements ties-to-even. NaN inputs are preserved as NaN; finite values that overflow to the bfloat16 infinity exponent raise range.

Parameters
fSource value.
rangeReceives a range flag on finite overflow.
Returns
Encoded bits.

◆ encode_bfloat_double()

uint16_t encode_bfloat_double ( double d,
int * range )
static

Encode a double as bfloat16 with a single final rounding.

A naive double→float→bfloat16 sequence rounds twice and can land on the wrong representable value (double rounding). To avoid it, when the float result is inexact the neighboring float on the correct side of d is chosen before the final bfloat16 rounding — so only one rounding decides the outcome. Values beyond FLT_MAX become bfloat16 infinities with range set.

Parameters
dSource value.
rangeReceives a range flag on finite overflow.
Returns
Encoded bits.

◆ encode_half()

uint16_t encode_half ( float f,
int * range )
static

Encode a float as IEEE 754 binary16 with round-to-nearest-even.

binary16 keeps the sign, rebases the exponent by -112 and rounds the significand to 10 bits. Finite magnitudes of 65520 or more overflow to infinity with range set (the tie at 65520 rounds to even, which is infinity); magnitudes in (65504, 65520) round to the largest finite 0x7bff. Results below 2^-14 become subnormals or signed zero; that underflow is not a range error. NaN stays a quiet NaN. Mirrors f32_to_f16() in src/nep_float16.c, which is the reference implementation.

Parameters
fSource value.
rangeReceives a range flag on finite overflow.
Returns
Encoded bits.

◆ encode_half_double()

uint16_t encode_half_double ( double d,
int * range )
static

Encode a double as IEEE 754 binary16 with a single final rounding.

Same round-to-odd technique as encode_bfloat_double(): when the float result is inexact the neighboring float on the correct side of d is chosen before the final binary16 rounding. float's 24-bit significand has 13 spare bits over binary16's 11, so this equals rounding the double directly. Values beyond FLT_MAX become binary16 infinities with range set.

Parameters
dSource value.
rangeReceives a range flag on finite overflow.
Returns
Encoded bits.

◆ integer_range()

int integer_range ( nc_type source,
nc_type target,
unsigned long long u,
long long s )
static

Check integer range without passing 64-bit boundaries through floating point.

Comparing a long long to 2^63 via floating point is imprecise near the boundary (exactly the values that matter for NC_UINT64 and NC_INT64), so integer-to-integer conversions are range-checked entirely in integer arithmetic: unsigned sources go through u, signed through s.

Parameters
sourceSource type.
targetInteger destination type.
uSource converted to unsigned long long, used for unsigned sources.
sSource converted to long long, used for signed sources.
Returns
Nonzero when outside the destination range.

◆ numeric()

int numeric ( nc_type t)
static

Test whether a type is a standard numeric atomic type.

"Standard numeric" means the classic netCDF numeric types (NC_BYTE through NC_DOUBLE, including the unsigned set) — the ones nxcdf_convert_type() handles itself. NC_CHAR, NC_STRING, small floats, bitfields, references and user-defined types are excluded.

Parameters
tNetCDF type.
Returns
Nonzero for a standard numeric type.

◆ nxcdf_convert_type()

int nxcdf_convert_type ( const void * src,
void * dest,
nc_type src_type,
nc_type dest_type,
size_t len,
int * range_error,
const void * fill_value,
int strict_nc3,
int quantize_mode,
int nsd,
int fill_on_overflow )

NEP's internal numeric conversion engine for nxCDF.

Converts between standard numeric atomic types, and between NC_BFLOAT16/NC_FLOAT16 storage and NC_FLOAT/NC_DOUBLE buffers. Modeled on netcdf-c's libsrc4/nc4var.c conversion but owned by NEP so behavior (in particular NC_ERANGE reporting, issue #381) is consistent across all I/O paths: variable I/O, attributes and quantized writes.

Three strategies: standard numerics convert elementwise in C with exact range checks; NC_FLOAT16 pairs use decode_half() and encode_half()/encode_half_double(); NC_BFLOAT16 pairs use encode_bfloat() with round-to-nearest-even. Both 16-bit types decode exactly and narrow with round-to-nearest-even, single rounding from double — HDF5 performs no application numeric conversion. Quantization is applied to the converted output last. Callers may probe with NULL buffers to validate a conversion before allocating.

Parameters
srcSource buffer (may be NULL for a validation-only probe).
destDestination buffer (may be NULL for a probe).
src_typeResolved source type.
dest_typeResolved destination type.
lenElement count.
range_errorRequired output range flag.
fill_valueOptional destination fill.
strict_nc3Classic byte-range convention.
quantize_modeQuantization mode.
nsdQuantization precision.
fill_on_overflowNonzero to store the fill value on real-to-integer overflow (NEP variable semantics); zero stores the raw truncated cast like netcdf-c (attribute read semantics).
Returns
NC_NOERR or a type, argument, allocation or HDF5 error; overflow is reported via range_error, not the return value.
Author
Edward Hartnett, Intelligent Data Design, Inc.

◆ quantize()

void quantize ( void * data,
nc_type t,
size_t n,
const void * fill,
int mode,
int nsd )
static

Apply netCDF quantization in place after conversion.

Quantization throws away low-order mantissa bits of float/double data to make compression more effective. The three modes: NC_QUANTIZE_BITGROOM alternately sets/zeros the tail bits, NC_QUANTIZE_GRANULARBR keeps a per-value decimal precision, and NC_QUANTIZE_BITROUND keeps a fixed bit count and rounds. Fill values, zeros and non-finite values are left untouched.

All bit manipulation goes through memcpy to stay legal under strict aliasing — the buffer was written as a real float/double, and reading it as an integer through a cast would be undefined.

Parameters
dataNumeric destination buffer.
tDestination type (NC_FLOAT or NC_DOUBLE).
nElement count.
fillOptional fill value.
modeValidated quantization mode.
nsdValidated precision.