OPALX (Object Oriented Parallel Accelerator Library for Exascal) master (dc2a29eed580)
OPALX
Loading...
Searching...
No Matches
QuasiRandom.h
Go to the documentation of this file.
1//
2// Quasi-random number generator to replace GSL QRNG
3//
4// Copyright (c) 2023, Paul Scherrer Institute, Villigen PSI, Switzerland
5// All rights reserved
6//
7// This file is part of OPAL.
8//
9// OPAL is free software: you can redistribute it and/or modify
10// it under the terms of the GNU General Public License as published by
11// the Free Software Foundation, either version 3 of the License, or
12// (at your option) any later version.
13//
14// You should have received a copy of the GNU General License
15// along with OPAL. If not, see <https://www.gnu.org/licenses/>.
16//
17
18#ifndef OPAL_QUASIRANDOM_HH
19#define OPAL_QUASIRANDOM_HH
20
21#include <cmath>
22#include <string>
23#include <vector>
24
25// Simple Sobol sequence generator (quasi-random)
26class gsl_qrng {
27public:
29
30 void init(size_t dimension) {
31 dimension_ = dimension;
32 count_ = 0;
33 // Initialize direction numbers for Sobol sequence
34 init_sobol();
35 }
36
37 void get(double* x) {
38 for (size_t i = 0; i < dimension_; ++i) {
39 x[i] = sobol_sample(i);
40 }
41 count_++;
42 }
43
44private:
45 void init_sobol() {
46 // Simplified Sobol initialization
47 // In practice, you'd want proper direction numbers
49 for (size_t i = 0; i < dimension_; ++i) {
50 direction_numbers_[i] = (1u << (31 - i)) | 1u;
51 }
52 }
53
54 double sobol_sample(size_t dim) {
55 if (dim >= dimension_) return 0.0;
56
57 unsigned int x = count_;
58 double result = 0.0;
59 double factor = 0.5;
60
61 for (int i = 0; i < 32; ++i) {
62 if (x & 1) {
63 result += factor;
64 }
65 x >>= 1;
66 factor *= 0.5;
67 }
68
69 return result;
70 }
71
72 size_t dimension_;
73 size_t count_;
74 std::vector<unsigned int> direction_numbers_;
75};
76
77// GSL-compatible functions
78inline gsl_qrng* gsl_qrng_alloc(const char* /* type */, unsigned int dimension) {
79 gsl_qrng* q = new gsl_qrng();
80 q->init(dimension);
81 return q;
82}
83
84inline void gsl_qrng_get(const gsl_qrng* q, double* x) { const_cast<gsl_qrng*>(q)->get(x); }
85
86inline void gsl_qrng_free(gsl_qrng* q) { delete q; }
87
88#endif // OPAL_QUASIRANDOM_HH
void gsl_qrng_free(gsl_qrng *q)
Definition QuasiRandom.h:86
gsl_qrng * gsl_qrng_alloc(const char *, unsigned int dimension)
Definition QuasiRandom.h:78
void gsl_qrng_get(const gsl_qrng *q, double *x)
Definition QuasiRandom.h:84
size_t count_
Definition QuasiRandom.h:73
double sobol_sample(size_t dim)
Definition QuasiRandom.h:54
void get(double *x)
Definition QuasiRandom.h:37
void init_sobol()
Definition QuasiRandom.h:45
std::vector< unsigned int > direction_numbers_
Definition QuasiRandom.h:74
size_t dimension_
Definition QuasiRandom.h:72
void init(size_t dimension)
Definition QuasiRandom.h:30