Contents

BNNSArithmeticUnary

A structure that contains the input and output of an arithmetic operation with a single input.

Declaration

struct BNNSArithmeticUnary

Overview

Use a BNNSArithmeticUnary structure to pass the descriptions and types of the input and output of a unary arithmetic operation to BNNSLayerParametersArithmetic.

The following code shows how to calculate the element-wise square roots of a vector:

let input: [Float] = [4, 16, 9, 25, 100]
let count = input.count
var output = [Float](repeating: .nan,
                     count: count)

let descriptor = BNNSNDArrayDescriptor(flags: BNNSNDArrayFlags(0),
                                       layout: BNNSDataLayoutVector,
                                       size: (count, 0, 0, 0, 0, 0, 0, 0),
                                       stride: (0, 0, 0, 0, 0, 0, 0, 0),
                                       data: nil,
                                       data_type: .float,
                                       table_data: nil,
                                       table_data_type: .float,
                                       data_scale: 1,
                                       data_bias: 0)

var fields = BNNSArithmeticUnary(in: descriptor,
                                 in_type: BNNSSample,
                                 out: descriptor,
                                 out_type: BNNSSample)

withUnsafeMutablePointer(to: &fields) { fieldsPtr in
    
    var layerParameters = BNNSLayerParametersArithmetic(arithmetic_function: BNNSArithmeticSquareRoot,
                                                        arithmetic_function_fields: fieldsPtr,
                                                        activation: .identity)
    
    guard let arithmeticLayer = BNNSFilterCreateLayerArithmetic(&layerParameters, nil) else {
        print("Unary BNNSFilterCreateLayerArithmetic returns nil")
        return
    }
    defer {
        BNNSFilterDestroy(arithmeticLayer)
    }
    
    input.withUnsafeBytes { inPtr in
        var rawPtr = inPtr.baseAddress!
        
        BNNSArithmeticFilterApplyBatch(arithmeticLayer, 1, 1,
                                       &rawPtr,
                                       [count],
                                       &output,
                                       count)
    }
}

// Prints "[2.0, 4.0, 3.0, 5.0, 10.0]"
print("Unary Arithmetic: outputs", output)

Topics

Creating an Arithmetic Structure

Inspecting the Properties of an Arithmetic Structure

See Also

Arithmetic layers