
#include <limits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/time.h>
#include <random>
#include <iomanip>

#include <Kokkos_Core.hpp>

#include <Kokkos_Random.hpp>
#include <Kokkos_DualView.hpp>
#include <impl/Kokkos_Timer.hpp>


#define PI 3.14159265358979323846
#define RANDOM_BLOCK_SIZE (1024*1024)
#define RANDOM_BLOCK_NUM 512
#define MAX_RANDOM_LENGTH (RANDOM_BLOCK_NUM*RANDOM_BLOCK_SIZE)


// A Functor for generating uint64_t random numbers templated on the
// GeneratorPool type
template <class GeneratorPool>
struct generate_random {
    // Output View for the random numbers
    Kokkos::View<uint64_t*> vals;

    // The GeneratorPool
    GeneratorPool rand_pool;

    int samples;

    // Initialize all members
    generate_random(Kokkos::View<uint64_t*> vals_, GeneratorPool rand_pool_, int samples_)
      : vals(vals_)
      , rand_pool(rand_pool_)
      , samples(samples_)
    {
    }
    KOKKOS_INLINE_FUNCTION
    void operator()(int i) const
    {
        // Get a random number state from the pool for the active thread
        typename GeneratorPool::generator_type rand_gen = rand_pool.get_state();

        // Draw samples numbers from the pool as urand64 between 0 and
        // rand_pool.MAX_URAND64 Note there are function calls to get other type of
        // scalars, and also to specify Ranges or get a normal distributed float.
        for (int k = 0; k < samples; k++) vals(i * samples + k) = rand_gen.urand64();

        // Give the state back, which will allow another thread to acquire it
        rand_pool.free_state(rand_gen);
    }
};





// 
// Box-Muller transform (https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform)
// The transform converts from the uniform distribution to N(0,1).
//
template <class GeneratorPool>
struct generate_normal_dist {
    Kokkos::View<double*> normals; // Normal distribution N(0,1)
    GeneratorPool rand_pool1;
    GeneratorPool rand_pool2;
    int samples;
    uint64_t range_min;
    uint64_t range_max1 = 0;
    uint64_t range_max2 = 0;


    generate_normal_dist(Kokkos::View<double*> normals_, GeneratorPool rand_pool1_, GeneratorPool rand_pool2_, int samples_)
        : normals(normals_), rand_pool1(rand_pool1_), rand_pool2(rand_pool2_), samples(samples_), range_min(1) {
        range_max1 = 0xffffffffffffffffULL-1;
        range_max2 = range_max1;
    }

    KOKKOS_INLINE_FUNCTION
    void operator()(int i) const {
        typename GeneratorPool::generator_type rand_gen1 = rand_pool1.get_state();
        typename GeneratorPool::generator_type rand_gen2 = rand_pool2.get_state();

        for (int k = 0; k < samples/2; k++) {
            double u1 = (double) rand_gen1.urand64(range_min, range_max1) / range_max1;
            double u2 = (double) rand_gen2.urand64(range_min, range_max2) / range_max2;
            normals(i * samples + 2*k)     = sqrt(-2*log(u1)) * cos(2*PI*u2);
            normals(i * samples + 2*k + 1) = sqrt(-2*log(u1)) * sin(2*PI*u2);
        }

        rand_pool1.free_state(rand_gen1);
        rand_pool2.free_state(rand_gen2);
    }

};














// void checkSizes( int &N, int &M, int &S, int &nrepeat );
void randomNumberTest();
void normalRandomTest();

void stlTest(const size_t N = 10000) {

    std::random_device rd{};

    // std::mt19937 gen_twister{rd()};
    std::default_random_engine gen(rd());

    std::normal_distribution<> dist{5,2};
 
    Kokkos::Timer timer;
    double* a = (double*) malloc(N * sizeof(double));
    double* b = (double*) malloc(N * sizeof(double));
    for(size_t n=0; n<N; ++n) {
        a[n] = dist(gen);
    }
    std::cout << "OD: " << timer.seconds() << std::endl;

    timer.reset();
    for(size_t n=0; n<N; ++n) {
        b[n] = a[n];
    }
    std::cout << "Pool: " << timer.seconds() << std::endl;

    free(a);
    free(b);
}

int main(int argc, char* argv[])
{
    size_t N = 10000;
    if (argc > 1) N = atoi(argv[1]);

    Kokkos::initialize(argc, argv);
    {
        // randomNumberTest();
        // normalRandomTest();
        stlTest(N);
    }
    Kokkos::finalize();

    return 0;
}

void randomNumberTest()
{
    int size = 1024;
    int samples = 1024;
    int seed = 5374857;

    // Create two random number generator pools one for 64bit states and one for 1024 bit states Both take an 64 bit
    // unsigned integer seed to initialize a Random_XorShift64 generator which is used to fill the generators of the
    // pool.
    Kokkos::Random_XorShift64_Pool<> rand_pool64(seed);
    Kokkos::Random_XorShift1024_Pool<> rand_pool1024(seed);
    Kokkos::DualView<uint64_t*> vals("Vals", size * samples);

    // Run some performance comparisons
    Kokkos::Timer timer;
    Kokkos::parallel_for(size, generate_random<Kokkos::Random_XorShift64_Pool<> >(vals.d_view, rand_pool64, samples));
    Kokkos::fence();

    timer.reset();
    Kokkos::parallel_for(size, generate_random<Kokkos::Random_XorShift64_Pool<> >(vals.d_view, rand_pool64, samples));
    Kokkos::fence();
    double time_64 = timer.seconds();

    Kokkos::parallel_for(size,
                         generate_random<Kokkos::Random_XorShift1024_Pool<> >(vals.d_view, rand_pool1024, samples));
    Kokkos::fence();

    timer.reset();
    Kokkos::parallel_for(size,
                         generate_random<Kokkos::Random_XorShift1024_Pool<> >(vals.d_view, rand_pool1024, samples));
    Kokkos::fence();
    double time_1024 = timer.seconds();

    printf("\n\n#Time XorShift64*:   %e %e\n", time_64, 1.0e-9 * samples * size / time_64);
    printf("#Time XorShift1024*: %e %e\n", time_1024, 1.0e-9 * samples * size / time_1024);

    Kokkos::deep_copy(vals.h_view, vals.d_view);
    std::cout << vals.h_view(0) << std::endl;
}




void normalRandomTest() {


    size_t size = RANDOM_BLOCK_NUM/2;
    size_t samples = RANDOM_BLOCK_SIZE;
    int seed = 2020;

    Kokkos::Random_XorShift64_Pool<> rand_pool1(seed);
    Kokkos::Random_XorShift64_Pool<> rand_pool2(seed+1);
    Kokkos::DualView<double*> normals("Normals", size * samples);

    Kokkos::parallel_for(size, generate_normal_dist<Kokkos::Random_XorShift64_Pool<> >(normals.d_view, rand_pool1, rand_pool2, samples));

    Kokkos::deep_copy(normals.h_view, normals.d_view);
    std::cout << normals.h_view(0) << std::endl;

}



