c++vexcl

VexCL: Index of maximum value in a vexcl vector


How can I find the index of the maximum value in a VexCL vector? I can find the maximum value:

int h[] = {3, 2, 1, 5, 4};
vex::vector<int> d(ctx, 5);
vex::copy(h, d);

vex::Reductor<int, vex::MAX> max(ctx.queue());
int m = max(d);

Which gives m = 5 but is there a way to find the index of the maximum value, ind = 3?


Solution

  • You will need to

    1. encode both vector value and vector position in a vexcl expression, and
    2. create custom functor for vex::Reductor that would reduce the above expression based on its first component.

    Here is the working code:

    #include <iostream>
    #include <vector>
    #include <vexcl/vexcl.hpp>
    
    // This function converts two integers to cl_int2
    VEX_FUNCTION(cl_int2, make_int2, (int, x)(int, y),
            int2 v = {x, y};
            return v;
            );
    
    // This struct compares OpenCL vector types by the first component.
    struct MAX0 {
        template <class Tn>
        struct impl {
            typedef typename vex::cl_scalar_of<Tn>::type T;
    
            // Initial value.
            static Tn initial() {
                Tn v;
    
                if (std::is_unsigned<T>::value)
                    v.s[0] = static_cast<T>(0);
                else
                    v.s[0] = -std::numeric_limits<T>::max();
    
                return v;
            }
    
            // Device-side function call operator
            struct device : vex::UserFunction<device, Tn(Tn, Tn)> {
                static std::string name() { return "MAX_" + vex::type_name<Tn>(); }
                static std::string body() { return "return prm1.x > prm2.x ? prm1 : prm2;"; }
            };
    
            // Host-side function call operator
            Tn operator()(Tn a, Tn b) const {
                return a.s[0] > b.s[0] ? a : b;
            }
        };
    };
    
    int main(int argc, char *argv[]) {
        vex::Context ctx( vex::Filter::Env );
    
        std::vector<int> h = {3, 2, 1, 5, 4};
        vex::vector<int> d(ctx, h);
    
        // Create reductor based on MAX0 operation,
        // then reduce an expression that encodes both value and position of a
        // vector element:
        vex::Reductor<cl_int2, MAX0> max(ctx);
    
        cl_int2 m = max(make_int2(d, vex::element_index()));
    
        std::cout << "max value of " << m.s[0] << " at position " << m.s[1] << std::endl;
    }
    

    This outputs

    max value of 5 at position 3