argminmax

    Portable SIMD extrema indices, NaN policies, and validity bitmaps ported from argminmax

    argminmax
    argmin
    argmax
    simd
    numeric
    Download zip
    Author
    Version
    0.1.0
    License
    MIT
    Last updated
    49 minutes ago
    Downloads
    1

    No dependencies

    #ArgMinMax checked examples

    The indices are relative to the view, with first-index ties.

    ///|
    test "extrema indices and partial views" {
    let values = [3, -2, 9, -2]
    assert_eq(@argminmax.argminmax(values), Some((1, 2)))
    assert_eq(@argminmax.argminmax(values[2:]), Some((1, 0)))
    assert_eq(@argminmax.argmin(([] : Array[Int32])), None)
    }

    NaN propagation and Arrow validity bitmaps retain original indices.

    ///|
    test "NaN policies and valid elements" {
    let values = [1.0, @double.not_a_number, -3.0]
    assert_eq(@argminmax.argminmax(values), Some((2, 0)))
    assert_eq(@argminmax.nanargminmax(values), Some((1, 1)))
    assert_eq(@argminmax.argminmax_masked([-5, 3, 9, 4], b"\x06"), Some((1, 2)))
    }

    Element

    pub(open) trait Element : Compare {
    fn is_nan(Self) -> Bool = _
    fn find_extrema(ArrayView[Self], minimum~ : Bool, maximum~ : Bool, propagate_nan~ : Bool, simd~ : Bool?) -> (Int, Int)? = _
    }

    A numeric element supported by the extrema searches.

    Built-in implementations cover Byte, Int16, UInt16, Int, UInt, Int64, UInt64, Float, and Double. This package also provides Int8, Int128, UInt128, Float16, and BFloat16. Custom implementations can use the default scalar search by implementing this trait and Compare. Numeric comparisons must be consistent for non-NaN values.
    impl Element for Byte
    impl Element for Int
    impl Element for Int16
    impl Element for Int64
    impl Element for UInt
    impl Element for UInt16
    impl Element for UInt64
    impl Element for Float
    impl Element for Double

    BitmapError

    pub(all) suberror BitmapError {
    InvalidOffset(Int)
    InsufficientBits(required~ : Int64, available~ : Int64)
    } derive(Eq,
    Debug
    )

    A validity bitmap does not describe the requested input range. Masked searches raise this before reading values or bitmap bits. offset counts bits relative to the supplied bitmap view, whose bits are numbered least-significant first. Length calculations use Int64 to avoid overflow.

    BFloat16

    pub struct BFloat16 {
    // private fields
    } derive(
    Debug
    )

    An immutable bfloat16 value preserving its sign, exponent, and NaN payload. This uses eight exponent and seven fraction bits. Construct from raw bits; searches implement the same NaN and signed-zero semantics as Float16. Shared assignments are safe because there is no mutable state.
    impl Element for BFloat16
    impl Compare for BFloat16
    impl Eq for BFloat16

    BFloat16::from_bits

    fn BFloat16::from_bits(bits : UInt16) -> BFloat16

    Constructs bfloat16 from exact bits, accepting all finite and NaN patterns. The result is immutable and construction works on all backends.

    BFloat16::is_nan

    fn BFloat16::is_nan(self : BFloat16) -> Bool

    Detects bfloat16 NaNs of either sign, including signaling encodings.

    BFloat16::to_bits

    fn BFloat16::to_bits(self : BFloat16) -> UInt16

    Returns the original bfloat16 bits without normalization or mutation.

    BFloat16::to_double

    fn BFloat16::to_double(self : BFloat16) -> Double

    Widens bfloat16 exactly through its binary32 bit representation. Finite values, signed zeroes, and infinities are exact. Floating-point operations may canonicalize NaN payloads; the stored bits remain unchanged.

    Float16

    pub struct Float16 {
    // private fields
    } derive(
    Debug
    )

    An immutable IEEE 754 binary16 value preserving all original bits. Construct from a raw UInt16; no rounding or implicit conversion occurs. Searches ignore or propagate NaNs as requested and treat signed zeroes as equal. Assignment aliases are safe because this value has no mutable state.
    impl Element for Float16
    impl Compare for Float16
    impl Eq for Float16

    Float16::from_bits

    fn Float16::from_bits(bits : UInt16) -> Float16

    Constructs a binary16 value from its exact bits, including all NaN payloads. Every bit pattern is accepted on all backends; the result is immutable.

    Float16::is_nan

    fn Float16::is_nan(self : Float16) -> Bool

    Detects binary16 NaNs, including signaling NaNs and either sign.

    Float16::to_bits

    fn Float16::to_bits(self : Float16) -> UInt16

    Returns the original binary16 bits without normalization or mutation.

    Float16::to_double

    fn Float16::to_double(self : Float16) -> Double

    Widens binary16 to Double exactly for finite values and signed zero. Infinities retain their sign. NaN payload bits are shifted to the binary64 fraction; backend floating-point operations may subsequently canonicalize them. The stored bits are never changed and no rounding is required.

    Int128

    pub struct Int128 {
    // private fields
    } derive(Eq,
    Debug
    )

    An immutable signed 128-bit two's-complement integer with exact 64-bit words. The high word is signed and the low word is unsigned. Shared assignments are safe. Searches use scalar comparisons on every backend and preserve all 128 bits, including in JavaScript; no floating-point conversion is used.
    impl Element for Int128
    impl Compare for Int128

    Int128::from_int64

    fn Int128::from_int64(value : Int64) -> Int128

    Sign-extends value exactly to an immutable 128-bit integer.

    Int128::from_words

    fn Int128::from_words(high~ : Int64, low~ : UInt64) -> Int128

    Constructs the signed value high * 2^64 + low exactly on every backend. Every word pair is valid and the result is immutable; the high word carries the sign. This representation includes -2^127 and 2^127 - 1.

    Int128::high

    fn Int128::high(self : Int128) -> Int64

    Returns the signed most significant word without changing this value.

    Int128::low

    fn Int128::low(self : Int128) -> UInt64

    Returns the unsigned least significant word without changing this value.

    Int8

    pub struct Int8 {
    // private fields
    } derive(Eq,
    Debug
    )

    An immutable signed eight-bit value stored in two's-complement form. MoonBit has no built-in Int8; construction checks -128 through 127. Shared assignments are safe and searches never mutate this value.
    impl Element for Int8
    impl Compare for Int8

    Int8::from_bits

    fn Int8::from_bits(bits : Byte) -> Int8

    Interprets all eight bits of bits as a signed two's-complement integer. Every input is valid; the result is immutable and backend-independent.

    Int8::from_int

    fn Int8::from_int(value : Int) -> Int8?

    Constructs an Int8 from value, returning None outside -128 through 127. No truncation, wrapping, or mutation occurs; this works on all backends.

    Int8::to_bits

    fn Int8::to_bits(self : Int8) -> Byte

    Returns the original two's-complement bits without conversion or mutation.

    Int8::to_int

    fn Int8::to_int(self : Int8) -> Int

    Returns this value as an exact signed Int in -128 through 127.

    UInt128

    pub struct UInt128 {
    // private fields
    } derive(Eq,
    Debug
    )

    An immutable unsigned 128-bit integer represented by two exact 64-bit words. high is the most significant word; no machine endianness is assumed. Shared assignments are safe. Searches use exact scalar comparisons on every backend, including JavaScript, and never convert these values to Double.
    impl Element for UInt128
    impl Compare for UInt128

    UInt128::from_uint64

    fn UInt128::from_uint64(value : UInt64) -> UInt128

    Widens value exactly to 128 bits with a zero high word.

    UInt128::from_words

    fn UInt128::from_words(high~ : UInt64, low~ : UInt64) -> UInt128

    Constructs an exact unsigned value high * 2^64 + low on all backends. Every word pair is valid; the returned value is immutable.

    UInt128::high

    fn UInt128::high(self : UInt128) -> UInt64

    Returns the most significant 64 bits without changing this value.

    UInt128::low

    fn UInt128::low(self : UInt128) -> UInt64

    Returns the least significant 64 bits without changing this value.

    argmax

    fn[T : Element + Compare + Eq] argmax(data : ArrayView[T], simd? : Bool) -> Int?

    Returns the first maximum index relative to data, ignoring NaNs. Empty input returns None; nonempty all-NaN input returns Some(0). Equal values, including signed zero, retain the first index. Ownership, mutation, vector requests, and backend fallbacks are the same as argminmax. Only the maximum is tracked during the search. Automatic searches are scalar; explicit requests follow argminmax.

    argmax_masked

    fn[T : Element + Compare + Eq] argmax_masked(data : ArrayView[T], validity : BytesView, offset? : Int, simd? : Bool) -> Int? raise BitmapError

    Returns the first valid maximum index, ignoring NaNs and preserving view indices. Bitmap bits, first ties, all-null/NaN behavior, read-only ownership, SIMD requests, and BitmapError validation match argminmax_masked. Tracks only the maximum within each valid run. Automatic single-extremum searches are scalar.

    argmin

    fn[T : Element + Compare + Eq] argmin(data : ArrayView[T], simd? : Bool) -> Int?

    Returns the first minimum index relative to data, ignoring NaNs. Empty input returns None; nonempty all-NaN input returns Some(0). Equal values, including signed zero, retain the first index. Ownership, mutation, vector requests, and backend fallbacks are the same as argminmax. Only the minimum is tracked during the search. Automatic searches are scalar; explicit requests follow argminmax.

    argmin_masked

    fn[T : Element + Compare + Eq] argmin_masked(data : ArrayView[T], validity : BytesView, offset? : Int, simd? : Bool) -> Int? raise BitmapError

    Returns the first valid minimum index, ignoring NaNs and preserving view indices. Bitmap bits, first ties, all-null/NaN behavior, read-only ownership, SIMD requests, and BitmapError validation match argminmax_masked. Tracks only the minimum within each valid run. Automatic single-extremum searches are scalar.

    argminmax

    fn[T : Element + Compare + Eq] argminmax(data : ArrayView[T], simd? : Bool) -> (Int, Int)?

    Returns the first indices of the minimum and maximum elements in data.

    Indices are relative to this view, including when it starts inside an array. Equal values retain their first index; positive and negative zero are equal. NaNs are ignored. A nonempty all-NaN view returns Some((0, 0)); an empty view returns None. Input and element state are never changed or copied. Omitting simd selects vectors on linear-memory Wasm for Float and Double views of at least 4096 elements, following local measurements. Other automatic searches are scalar. simd=true explicitly requests portable vectors on native and Wasm for 8–64-bit elements. Short inputs, 128-bit elements, Wasm GC, and JavaScript use scalar processing. Leading NaNs are skipped scalarly; no CPU-specific instruction set is requested.

    test {
    assert_eq(@argminmax.argminmax([3, -2, 9, -2]), Some((1, 2)))
    }

    argminmax_masked

    fn[T : Element + Compare + Eq] argminmax_masked(data : ArrayView[T], validity : BytesView, offset? : Int, simd? : Bool) -> (Int, Int)? raise BitmapError

    Returns extrema indices while skipping nulls marked by an Arrow bitmap. Element i is valid iff bit offset + i of validity is set; the least significant bit comes first. offset is relative to the bitmap view and independent of the data view's start. Results retain original data-view indices; first ties and NaN ignoring match argminmax. No valid elements returns None; all valid elements NaN returns their first valid index twice. Negative offsets or insufficient bitmap bits raise BitmapError, including for empty input, before reads. Neither input is mutated or copied. simd requests the ordinary element kernel within contiguous valid runs; sparse masks use short scalar runs. Omission and simd=false use a direct scalar scan without per-run views or results. Scalar-only backends use that same direct scan even for simd=true. Bitmap positioning uses overflow-safe byte/bit arithmetic after wide validation; bitmap scanning is scalar.

    test {
    assert_eq(@argminmax.argminmax_masked([-5, 3, 9, 4], b"\x06"), Some((1, 2)))
    }

    nanargmax

    fn[T : Element + Compare + Eq] nanargmax(data : ArrayView[T], simd? : Bool) -> Int?

    Returns the first NaN index if present, otherwise the first maximum index. Empty input returns None. NaN payload guarantees, read-only ownership, view-relative indices, first ties, and backend fallbacks match nanargminmax. Only the maximum is tracked when no NaN is encountered. Automatic searches are scalar; explicit requests follow nanargminmax.

    nanargmax_masked

    fn[T : Element + Compare + Eq] nanargmax_masked(data : ArrayView[T], validity : BytesView, offset? : Int, simd? : Bool) -> Int? raise BitmapError

    Returns the first valid NaN index, otherwise the first valid maximum index. Nulls, bitmap offsets, errors, immutable inputs, first ties, view-relative indices, and SIMD/fallback behavior match nanargminmax_masked. Automatic single-extremum searches are scalar.

    nanargmin

    fn[T : Element + Compare + Eq] nanargmin(data : ArrayView[T], simd? : Bool) -> Int?

    Returns the first NaN index if present, otherwise the first minimum index. Empty input returns None. NaN payload guarantees, read-only ownership, view-relative indices, first ties, and backend fallbacks match nanargminmax. Only the minimum is tracked when no NaN is encountered. Automatic searches are scalar; explicit requests follow nanargminmax.

    nanargmin_masked

    fn[T : Element + Compare + Eq] nanargmin_masked(data : ArrayView[T], validity : BytesView, offset? : Int, simd? : Bool) -> Int? raise BitmapError

    Returns the first valid NaN index, otherwise the first valid minimum index. Nulls, bitmap offsets, errors, immutable inputs, first ties, view-relative indices, and SIMD/fallback behavior match nanargminmax_masked. Automatic single-extremum searches are scalar.

    nanargminmax

    fn[T : Element + Compare + Eq] nanargminmax(data : ArrayView[T], simd? : Bool) -> (Int, Int)?

    Returns both extrema indices, or the first NaN index in both components. Unlike NumPy's nanargmin, the upstream nan prefix means propagate NaNs. The first NaN is guaranteed even for differing payloads, signs, or signaling NaNs. Without NaNs, results match argminmax; integers also behave that way. Empty input returns None. The input is never mutated or copied. View indices, first ties, SIMD requests, and fallbacks match argminmax. Automatic NaN-propagating searches are scalar on every backend.

    test {
    let values : Array[Double] = [1.0, @double.not_a_number, -3.0]
    assert_eq(@argminmax.nanargminmax(values), Some((1, 1)))
    }

    nanargminmax_masked

    fn[T : Element + Compare + Eq] nanargminmax_masked(data : ArrayView[T], validity : BytesView, offset? : Int, simd? : Bool) -> (Int, Int)? raise BitmapError

    Returns valid extrema, or the first valid NaN index in both components. Null NaNs are skipped. Every NaN payload/sign follows the first-index rule. Bitmap semantics, empty/all-null behavior, validation errors, ownership, view-relative indices, and backend fallbacks match argminmax_masked.