ModelicaRandom.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /* ModelicaRandom.c - External functions for Modelica.Math.Random library
  2. Copyright (C) 2015-2016, Modelica Association and DLR
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  12. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  13. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  14. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  15. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  16. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  17. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  18. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  19. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  20. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21. */
  22. /* The functions in this file are non-portable. The following #define's are used
  23. to define the system calls of the operating system
  24. _MSC_VER : Microsoft Visual C++
  25. MODELICA_EXPORT: Prefix used for function calls. If not defined, blank is used
  26. Useful definitions:
  27. - "static" that is all functions become static
  28. (useful if file is included with other C-sources for an
  29. embedded system)
  30. - "__declspec(dllexport)" if included in a DLL and the
  31. functions shall be visible outside of the DLL
  32. Release Notes:
  33. Oct. 27, 2015: by Thomas Beutlich, ITI GmbH
  34. Added nonnull attribute/annotations (ticket #1436)
  35. Feb. 17, 2015: by Andreas Kloeckner and Martin Otter, DLR-SR
  36. Implemented a first version
  37. */
  38. #if !defined(MODELICA_EXPORT)
  39. # define MODELICA_EXPORT DYMOLA_STATIC
  40. #endif
  41. /* Have RANDOM int64 / uint64 */
  42. #if defined (_WIN32)
  43. #if defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__)
  44. #define HAVE_RANDOM_INT64_T 1
  45. #define HAVE_RANDOM_UINT64_T 1
  46. #else
  47. #undef HAVE_RANDOM_INT64_T
  48. #undef HAVE_RANDOM_UINT64_T
  49. #endif
  50. #else
  51. #define HAVE_RANDOM_INT64_T 1
  52. #define HAVE_RANDOM_UINT64_T 1
  53. #endif
  54. /* Define to 1 if you have the <stdint.h> header file. */
  55. #if defined(_WIN32)
  56. #if defined(_MSC_VER) && _MSC_VER >= 1600
  57. #define HAVE_RANDOM_STDINT_H 1
  58. #elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__)
  59. #define HAVE_RANDOM_STDINT_H 1
  60. #else
  61. #undef HAVE_RANDOM_STDINT_H
  62. #endif
  63. #elif defined(__GNUC__) && !defined(__VXWORKS__)
  64. #define HAVE_RANDOM_STDINT_H 1
  65. #else
  66. #undef HAVE_RANDOM_STDINT_H
  67. #endif
  68. /* Include integer type header */
  69. #if defined(HAVE_RANDOM_STDINT_H)
  70. #include <stdint.h>
  71. #else
  72. #define int32_t int
  73. #define uint32_t unsigned int
  74. #if defined(HAVE_RANDOM_INT64_T)
  75. #if defined(_MSC_VER) && _MSC_VER < 1300
  76. #define int64_t __int64
  77. #else
  78. #define int64_t long long
  79. #endif
  80. #endif
  81. #if defined(HAVE_RANDOM_UINT64_T)
  82. #if defined(_MSC_VER) && _MSC_VER < 1300
  83. #define uint64_t unsigned __int64
  84. #else
  85. #define uint64_t unsigned long long
  86. #endif
  87. #endif
  88. #endif
  89. #include <stdlib.h>
  90. #include <limits.h>
  91. #include <math.h>
  92. #include <string.h>
  93. #include "ModelicaUtilities.h"
  94. #include "gconstructor.h"
  95. /* The standard way to detect posix is to check _POSIX_VERSION,
  96. * which is defined in <unistd.h>
  97. */
  98. #if defined(__unix__) || defined(__linux__) || defined(__APPLE_CC__)
  99. #if !defined(NO_FILE_SYSTEM) && !defined(LABCAR)
  100. #include <unistd.h>
  101. #endif
  102. #endif
  103. #if !defined(_POSIX_) && defined(_POSIX_VERSION)
  104. #define _POSIX_ 1
  105. #endif
  106. /* On Posix systems define a mutex using the single static variable "m" */
  107. #if defined(_POSIX_) && !defined(NO_FILE_SYSTEM) && !defined(LABCAR)
  108. #include <pthread.h>
  109. static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
  110. #define MUTEX_LOCK() pthread_mutex_lock(&m)
  111. #define MUTEX_UNLOCK() pthread_mutex_unlock(&m)
  112. /* On Windows systems define a critical section using the single static variable "cs" */
  113. #elif defined(_WIN32) && defined(G_HAS_CONSTRUCTORS)
  114. #if !defined(WIN32_LEAN_AND_MEAN)
  115. #define WIN32_LEAN_AND_MEAN
  116. #endif
  117. #include <Windows.h>
  118. static CRITICAL_SECTION cs;
  119. #ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA
  120. #pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(ModelicaRandom_initializeCS)
  121. #endif
  122. G_DEFINE_CONSTRUCTOR(ModelicaRandom_initializeCS)
  123. static void ModelicaRandom_initializeCS(void) {
  124. InitializeCriticalSection(&cs);
  125. }
  126. #ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA
  127. #pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(ModelicaRandom_deleteCS)
  128. #endif
  129. G_DEFINE_DESTRUCTOR(ModelicaRandom_deleteCS)
  130. static void ModelicaRandom_deleteCS(void) {
  131. DeleteCriticalSection(&cs);
  132. }
  133. #define MUTEX_LOCK() EnterCriticalSection(&cs)
  134. #define MUTEX_UNLOCK() LeaveCriticalSection(&cs)
  135. /* On other systems do not use a mutex at all */
  136. #else
  137. #define MUTEX_LOCK()
  138. #define MUTEX_UNLOCK()
  139. #endif
  140. /*
  141. * Non-null pointers need to be passed to external functions.
  142. *
  143. * The following macros handle nonnull attributes for GNU C and Microsoft SAL.
  144. */
  145. #if defined(__GNUC__)
  146. #define MODELICA_NONNULLATTR __attribute__((nonnull))
  147. #else
  148. #define MODELICA_NONNULLATTR
  149. #endif
  150. #if !defined(__ATTR_SAL)
  151. #define _In_
  152. #define _Out_
  153. #endif
  154. MODELICA_EXPORT void ModelicaRandom_xorshift64star(_In_ int state_in[],
  155. _Out_ int state_out[], _Out_ double* y) MODELICA_NONNULLATTR;
  156. MODELICA_EXPORT void ModelicaRandom_xorshift128plus(_In_ int state_in[],
  157. _Out_ int state_out[], _Out_ double* y) MODELICA_NONNULLATTR;
  158. MODELICA_EXPORT void ModelicaRandom_xorshift1024star(_In_ int state_in[],
  159. _Out_ int state_out[], _Out_ double* y) MODELICA_NONNULLATTR;
  160. MODELICA_EXPORT void ModelicaRandom_setInternalState_xorshift1024star(
  161. _In_ int* state, size_t nState, int id) MODELICA_NONNULLATTR;
  162. MODELICA_EXPORT void ModelicaRandom_convertRealToIntegers(double d,
  163. _Out_ int i[]) MODELICA_NONNULLATTR;
  164. MODELICA_EXPORT void ModelicaInternal_getTime(_Out_ int* ms, _Out_ int* sec,
  165. _Out_ int* min, _Out_ int* hour, _Out_ int* mday, _Out_ int* mon,
  166. _Out_ int* year) MODELICA_NONNULLATTR;
  167. MODELICA_EXPORT int ModelicaInternal_getpid(void);
  168. /* XORSHIFT ALGORITHMS */
  169. /* For details see http://xorshift.di.unimi.it/
  170. Written in 2014 by Sebastiano Vigna (vigna@acm.org)
  171. To the extent possible under law, the author has dedicated all copyright
  172. and related and neighboring rights to this software to the public domain
  173. worldwide. This software is distributed without any warranty.
  174. See <http://creativecommons.org/publicdomain/zero/1.0/>.
  175. Adapted by Martin Otter and Andreas Kloeckner for use with Modelica:
  176. - Inputs and outputs must be int's, that is int32_t.
  177. - Inputs are casted accordingly.
  178. - Outputs are casted accordingly.
  179. - The additional double between 0 and 1 is output.
  180. */
  181. /* transform 64-bit unsigned integer to double such that zero cannot appear, by
  182. first transforming to a 64-bit signed integer, then to a double in the range 0 .. 1.
  183. (using the algorithm given here: http://www.doornik.com/research/randomdouble.pdf) */
  184. #define ModelicaRandom_INVM64 5.42101086242752217004e-20 /* = 2^(-64) */
  185. #define ModelicaRandom_RAND(INT64) ( (int64_t)(INT64) * ModelicaRandom_INVM64 + 0.5 )
  186. MODELICA_EXPORT void ModelicaRandom_xorshift64star(int state_in[], int state_out[], double* y) {
  187. /* xorshift64* random number generator.
  188. For details see http://xorshift.di.unimi.it/
  189. Written in 2014 by Sebastiano Vigna (vigna@acm.org)
  190. To the extent possible under law, the author has dedicated all copyright
  191. and related and neighboring rights to this software to the public domain
  192. worldwide. This software is distributed without any warranty.
  193. See <http://creativecommons.org/publicdomain/zero/1.0/>.
  194. Adapted by Martin Otter and Andreas Kloeckner (DLR)
  195. for the Modelica external function interface.
  196. */
  197. /* This is a good generator if you're short on memory, but otherwise we
  198. rather suggest to use a xorshift128+ (for maximum speed) or
  199. xorshift1024* (for speed and very long period) generator. */
  200. /* Convert inputs */
  201. union s_tag {
  202. int32_t s32[2];
  203. uint64_t s64;
  204. } s;
  205. size_t i;
  206. uint64_t x;
  207. for (i=0; i<sizeof(s)/sizeof(uint32_t); i++) {
  208. s.s32[i] = state_in[i];
  209. }
  210. x = s.s64;
  211. /* The actual algorithm */
  212. x ^= x >> 12; /* a */
  213. x ^= x << 25; /* b */
  214. x ^= x >> 27; /* c */
  215. #if defined(_MSC_VER)
  216. x = x * 2685821657736338717i64;
  217. #else
  218. x = x * 2685821657736338717LL;
  219. #endif
  220. /* Convert outputs */
  221. s.s64 = x;
  222. for (i=0; i<sizeof(s)/sizeof(uint32_t); i++) {
  223. state_out[i] = s.s32[i];
  224. }
  225. *y = ModelicaRandom_RAND(x);
  226. }
  227. MODELICA_EXPORT void ModelicaRandom_xorshift128plus(int state_in[], int state_out[], double* y) {
  228. /* xorshift128+ random number generator.
  229. For details see http://xorshift.di.unimi.it
  230. Arguments seed and newSeed must be int32_t vectors with at least 4 elements each.
  231. Written in 2014 by Sebastiano Vigna (vigna@acm.org)
  232. To the extent possible under law, the author has dedicated all copyright
  233. and related and neighboring rights to this software to the public domain
  234. worldwide. This software is distributed without any warranty.
  235. See <http://creativecommons.org/publicdomain/zero/1.0/>.
  236. Adapted by Martin Otter and Andreas Kloeckner (DLR)
  237. for the Modelica external function interface.
  238. */
  239. /* This is the fastest generator passing BigCrush without systematic
  240. errors, but due to the relatively short period it is acceptable only
  241. for applications with a very mild amount of parallelism; otherwise, use
  242. a xorshift1024* generator. */
  243. /* The state must be seeded so that it is not everywhere zero. If you have
  244. a 64-bit seed, we suggest to pass it twice through MurmurHash3's
  245. avalanching function. */
  246. /* Convert inputs */
  247. union s_tag {
  248. int32_t s32[4];
  249. uint64_t s64[2];
  250. } s;
  251. size_t i;
  252. uint64_t s1;
  253. uint64_t s0;
  254. for (i=0; i<sizeof(s)/sizeof(uint32_t); i++) {
  255. s.s32[i] = state_in[i];
  256. }
  257. /* The actual algorithm */
  258. s1 = s.s64[0];
  259. s0 = s.s64[1];
  260. s.s64[0] = s.s64[1];
  261. s1 ^= s1 << 23; /* a */
  262. s.s64[1] = ( s1 ^ s0 ^ ( s1 >> 17 ) ^ ( s0 >> 26 ) ) + s0; /* b, c */
  263. /* Convert outputs */
  264. for (i=0; i<sizeof(s)/sizeof(uint32_t); i++) {
  265. state_out[i] = s.s32[i];
  266. }
  267. *y = ModelicaRandom_RAND(s.s64[1]);
  268. }
  269. static void ModelicaRandom_xorshift1024star_internal(uint64_t s[], int* p, double* y) {
  270. /* xorshift1024* random number generator.
  271. For details see http://xorshift.di.unimi.it
  272. This internal function directly operates on a pointer to the state array, such that
  273. no copying of states is needed.
  274. Written in 2014 by Sebastiano Vigna (vigna@acm.org)
  275. To the extent possible under law, the author has dedicated all copyright
  276. and related and neighboring rights to this software to the public domain
  277. worldwide. This software is distributed without any warranty.
  278. See <http://creativecommons.org/publicdomain/zero/1.0/>.
  279. Adapted by Martin Otter and Andreas Kloeckner (DLR)
  280. for the Modelica external function interface.
  281. */
  282. /* This is a fast, top-quality generator. If 1024 bits of state are too
  283. much, try a xorshift128+ or a xorshift64* generator. */
  284. /* The state must be seeded so that it is not everywhere zero. If you have
  285. a 64-bit seed, we suggest to seed a xorshift64* generator and use its
  286. output to fill s. */
  287. /* Convert inputs */
  288. uint64_t s0;
  289. uint64_t s1;
  290. *p = *p & 15;
  291. /* The actual algorithm */
  292. s0 = s[*p];
  293. s1 = s[*p = (*p + 1) & 15];
  294. s1 ^= s1 << 31; /* a */
  295. s1 ^= s1 >> 11; /* b */
  296. s0 ^= s0 >> 30; /* c */
  297. s[*p] = s0 ^ s1;
  298. /* Convert outputs */
  299. #if defined(_MSC_VER)
  300. *y = ModelicaRandom_RAND(s[*p]*1181783497276652981i64);
  301. #else
  302. *y = ModelicaRandom_RAND(s[*p]*1181783497276652981LL);
  303. #endif
  304. }
  305. MODELICA_EXPORT void ModelicaRandom_xorshift1024star(int state_in[], int state_out[], double* y) {
  306. /* xorshift1024* random number generator.
  307. For details see http://xorshift.di.unimi.it
  308. This function uses ModelicaRandom_xorshift1024star_internal as generator and adapts inputs and outputs.
  309. Adapted by Martin Otter and Andreas Kloeckner (DLR)
  310. for the Modelica external function interface.
  311. */
  312. /* This is a fast, top-quality generator. If 1024 bits of state are too
  313. much, try a xorshift128+ or a xorshift64* generator. */
  314. /* The state must be seeded so that it is not everywhere zero. If you have
  315. a 64-bit seed, we suggest to seed a xorshift64* generator and use its
  316. output to fill s. */
  317. /* Convert inputs */
  318. union s_tag {
  319. int32_t s32[32];
  320. uint64_t s64[16];
  321. } s;
  322. size_t i;
  323. int p;
  324. for (i=0; i<sizeof(s)/sizeof(uint32_t); i++) {
  325. s.s32[i] = state_in[i];
  326. }
  327. p = state_in[32];
  328. /* The actual algorithm */
  329. ModelicaRandom_xorshift1024star_internal(s.s64, &p, y);
  330. /* Convert outputs */
  331. for (i=0; i<sizeof(s)/sizeof(uint32_t); i++) {
  332. state_out[i] = s.s32[i];
  333. }
  334. state_out[32] = p;
  335. }
  336. /* EXTERNAL SEED ALGORITHMS */
  337. /* these functions give access to an external random number state
  338. you should be very careful about using them...
  339. The external variables are
  340. - ModelicaRandom_s: The first part of the internal state of xorshift1024*
  341. - ModelicaRandom_p: The second part of the internal state of xorshift1024*
  342. - ModelicaRandom_id: The check variable used for initializing the state
  343. We use MUTEX_LOCK() and MUTEX_UNLOCK() as defined above for
  344. thread-safe access to these variables.
  345. */
  346. /* Internal state of impure random number generator */
  347. static const size_t ModelicaRandom_size = 33;
  348. static uint64_t ModelicaRandom_s[ 16 ];
  349. static int ModelicaRandom_p;
  350. static int ModelicaRandom_id = 0;
  351. MODELICA_EXPORT void ModelicaRandom_setInternalState_xorshift1024star(int* state, size_t nState, int id) {
  352. /* Receive the external states from Modelica */
  353. union s_tag {
  354. int32_t s32[2];
  355. uint64_t s64;
  356. } s;
  357. int i;
  358. if ( nState > ModelicaRandom_size ) {
  359. ModelicaFormatError("External state vector is too large. Should be %lu.\n", (unsigned long)ModelicaRandom_size);
  360. }
  361. MUTEX_LOCK();
  362. for (i=0; i<16; i++) {
  363. s.s32[0] = state[2*i];
  364. s.s32[1] = state[2*i+1];
  365. ModelicaRandom_s[i] = s.s64;
  366. }
  367. ModelicaRandom_p = state[32];
  368. ModelicaRandom_id = id;
  369. MUTEX_UNLOCK();
  370. }
  371. MODELICA_EXPORT double ModelicaRandom_impureRandom_xorshift1024star(int id) {
  372. /* xorshift1024* random number generator (same as above, but with internal state, instead of external one).
  373. For details see http://xorshift.di.unimi.it
  374. Argument "id" is provided to guarantee the right calling sequence
  375. of the function in a Modelica environment (first calling function
  376. ModelicaRandom_initialize_xorshift1024star that must return "dummy" which is passed
  377. as input argument to ModelicaRandom_xorshift1024star. As a result, the ordering
  378. of the function is correct.
  379. This function uses ModelicaRandom_xorshift1024star_internal as generator and adapts inputs and outputs.
  380. Adapted by Martin Otter (DLR) to initialize the seed with ModelicaRandom_initializeRandom
  381. and to return a double in range 0 < randomNumber < 1.0
  382. */
  383. /* This is a fast, top-quality generator. If 1024 bits of state are too
  384. much, try a xorshift128+ or a xorshift64* generator. */
  385. /* The state must be seeded so that it is not everywhere zero. If you have
  386. a 64-bit seed, we suggest to seed a xorshift64* generator and use its
  387. output to fill s. */
  388. double y;
  389. MUTEX_LOCK();
  390. /* Check that ModelicaRandom_initializeImpureRandome_xorshift1024star was called before */
  391. if ( id != ModelicaRandom_id ) {
  392. ModelicaError("Function impureRandom not initialized with function initializeImpureRandom\n");
  393. }
  394. /* Compute random number */
  395. ModelicaRandom_xorshift1024star_internal(ModelicaRandom_s, &ModelicaRandom_p, &y);
  396. MUTEX_UNLOCK();
  397. return y;
  398. }
  399. MODELICA_EXPORT int ModelicaRandom_automaticGlobalSeed(double dummy) {
  400. /* Creates an automatic integer seed (typically from the current time and process id) */
  401. int ms, sec, min, hour, mday, mon, year;
  402. int pid;
  403. int seed;
  404. ModelicaInternal_getTime(&ms, &sec, &min, &hour, &mday, &mon, &year);
  405. pid = ModelicaInternal_getpid();
  406. /* Check that worst case combination can be included in an Integer:
  407. 1000*60*60 = 3.6e6 < 2^31 = 2147483648 (2.1e9)
  408. Everything is added to 1, in order to guard against the very unlikely case that the sum is zero.
  409. */
  410. seed = 1 + ms + 1000*sec + 1000*60*min + 1000*60*60*hour + 6007*pid;
  411. return seed;
  412. }
  413. MODELICA_EXPORT void ModelicaRandom_convertRealToIntegers(double d, int i[]) {
  414. /* Cast a double to two integers */
  415. union d2i {
  416. double d;
  417. int i[2];
  418. } u;
  419. u.d = d;
  420. i[0] = u.i[0];
  421. i[1] = u.i[1];
  422. }