random number generator in boost.python - random

How can I use the same random number generator in my "Python with numpy" code as my C++0x code?
I am currently using
std::ranlux64_base_01
in C++ and
numpy.random.RandomState(10)
in Python.
I exposed C++'s random number generator:
typedef std::ranlux64_base_01 RNG;
RNG g_rng;
...
class_<RNG>("RNG");
scope().attr("g_rng") = g_rng;
How do I use it with Python's methods that take a numpy.random?

There are 2 ways:
the first is to use pythons random number generator from c++. It will probably look something like this:
boost::python::object randmod = boost::python::import("numpy.random")
boost::python::object randfunc = randmod.attr("RandomState")
randfunc(10)
The second is to wrap and expose the c++ function so that it can be used from python. The code for this is left an an exercise for the student.
Edit:
Once you have exported the c++ function you would have to make a python object that mimics the interface of numpy.random.RandomState using the c++ function for it's random bits. This is probably more work then you want to do. I have not used numpy, but from the docs it looks like the RandomState object is not-trivial.

Related

How do I use the rand crate without the standard library?

I'm doing embedded game development for the Sega Megadrive with Rust and would like a random number generator to increase replayability. It can be pseudo-random: there's no security stuff required.
I've been looking at the rand crate which falls in the "No standard library" department, but I'm not sure on how to use it with this in my Crate.toml:
[dependencies]
rand = {version = "0.8.3", default-features = false}
When I disable default-features, there's no random function in the prelude anymore. There is the Rng trait but I'm too inexperienced to figure out how to use it.
To use the rand crate without std you need to manually use one of the generators that work without it. Those generators are the OsRng and the SmallRng structs. As the name suggests the first one uses the operating system's generator, which requires the getrandom crate, which probably isn't supported on SEGA Megadrive.
SmallRng should work without problems though. We cannot use the random() function, we need to manually create the generator and then call its methods.
To do this we first have to create a generator, like this:
let mut small_rng = SmallRng::seed_from_u64([insert your seed here]);
You can also use the seed_from_u32, whose documentation you can find here.
Then we can use it as such:
let rand_num = small_rng.next_u64();
Importantly, we have to import the RngCore trait to use these functions, this way:
use rand::{Rng, SeedableRng};
use rand::rngs::SmallRng;
use rand::RngCore;
SmallRng relies on the small_rng crate feature, so you should import it this way (in the Cargo.toml file):
rand = { version = "0.8.3", features = ["small_rng"], default-features = false }
I should also leave a disclaimer: SmallRng's generator isn't cryptographically secure.

How is emdeding of cython syntax inside python syntax implemented?

Looking on simple example of cython code I wonder if CPython interpreter needed some hard-coded hacks to understand cython syntax (e.g. cdef int N) or if it is implemented using some concepts of standard python syntax (e.g. functions, classes, operators etc.)
I mean, I can roughly imagine how the cython backend can be implemented (c-code generation, compilation etc.), but I don't understand how the frontend syntax can be integrated within standard python interpreter without touching the python interpteter itself (i.e. without extending python language beyond standard).
What is cdef ?
In other words, what cdef actually is? Is it a function, operator, or some new keyword? I would understand N = cedef(int) - that would create instance of some class derived from int. But written like that, I don't see how these 3 tokens even interact (1 cdef, 2 int, 3 N) ?
Does the for-loop actually iterate?
if you write code like this:
cdef int i,N = 1000000
cdef double f = 0
for i in xrange(N):
f += (i*i)
print f
The loop for i in xrange(N): is normal python loop. What prevents python interpreter to uselessly iterate 1000000 iterations before cython compile it into to C-code?
Does it work something like this:
N is an instance of some class cdef. xrange call N.__int__() which returns 1, passing the loop only once. The expression f += (i*i) contains only cdef objects, so cython can redefine __add_(), __set__(), __get__() functions in a way that generate C-code for f+=(i*i)
But then I still don't see how the construct for i in xrange() is send to cython, to generate C code from it.
Anyway, it seems quite complicated and fragiel, so perhaps it must be otherwise

Return Ruby's Fiddle::Pointer from C function

I am currently working on a high-performance Vector/Matrix Ruby gem C extension, as I find the built-in implementation cumbersome and not ideal for most cases that I have personally encountered, as well as lacking in other areas.
My first approach was implementing in Ruby as a subclass of Fiddle::CStructEntity, as a goal is to make them optimized for interop without need for conversion (such as passing to native OpenGL functions). Implementing in C offers a great benefit for the math, but I ran into a roadblock when trying to implement a minor function.
I wished to have a method return a Fiddle::Pointer to the struct (basically a pointer to Rdata->data. I wished to return an actual Fiddle::Pointer object. Returning an integer address, packed string, etc. is trivial, and using that could easily be extended in a Ruby method to convert to a Fiddle::Pointer like this:
def ptr
# Assume address is an integer address returned from C
Fiddle::Pointer.new(self.address, self.size)
end
This kind of opened up a question to me, and that is it possible to to even do such from C? Fiddle is not part of the core, library, it is part of the standard lib, and as such, is really just an extension itself.
The problem is trivial, and can be easily overcome with a couple lines of Ruby code as demonstrated above, but was more curious if returning a Fiddle object was even possible from a C extension without hacks? I was unable to find any examples of this being done, and as always when it comes to the documentation involving Fiddle, it is quite basic and does not explain much.
The solution for this is actually rather simple, though admittedly not as elegant or clean of a solution I was hoping to discover.
There are possibly more elaborate ways to go about this by including the headers for Fiddle, and building against it, but this was not really a viable solution, as I didn't want to restrict my C extension to only work with Ruby 2.0+, and would be perfectly acceptable to simply omit the method in the event Ruby version was less than 2.0.
First I include version.h, which gives access defines the macro RUBY_API_VERSION_MAJOR, which is all I really need to know in regards to whether or not Fiddle will be present or not.
This will be an abbreviated version to simply show how to get the Fiddle::Pointer class as a VALUE, and to create an instance.
#if RUBY_API_VERSION_MAJOR >= 2
rb_require("fiddle");
VALUE fiddle = rb_const_get(rb_cObject, rb_intern("Fiddle"));
rb_cFiddlePointer = rb_const_get(fiddle, rb_intern("Pointer"));
#endif
In this example, the class is stored in rb_cFiddlePointer, which can then be used to create and return a Fiddle::Pointer object from C.
// Get basic data about the struct
struct RData *rdata = RDATA(self);
VALUE *args = xmalloc(sizeof(VALUE) * 2);
// Set the platform pointer-size address (could just use size_t here...)
#if SIZEOF_INTPTR_T == 4
args[0] = LONG2NUM((long) rdata->data);
#elif SIZEOF_INTPTR_T == 8
args[0] = LL2NUM((long long) rdata->data);
#else
args[0] = INT2NUM(0);
#endif
// Get size of structure
args[1] = INT2NUM(SIZE_OF_YOUR_STRUCTURE);
VALUE ptr = rb_class_new_instance(2, args, rb_cFiddlePointer);
xfree(args);
return ptr;
After linking the function to an actual Ruby method, you can then call it to get a sized pointer to the internal structure in memory.

No member named dim in Halide::GeneratorInput<Halide::Func>

I'm trying to translate the resize app from the halide repository from the inline declarations to a generator. Everything seems to work fine, except for this:
Func clamped = BoundaryConditions::repeat_edge(input);`
In the original code, input is declared like so ImageParam input(Float(32), 3). In my generator, I've translated this to: Input<Func> input { "input", Float(32), 3 }. I'm then declaring the clamped in the exact same way as the original code. When compiling, I'm getting this error:
Halide.h:15202:50: error: no member named 'dim' in 'Halide::GeneratorInput<Halide::Func>'
object_bounds.push_back({ Expr(func_like.dim(i).min()), Expr(func_like.dim(i).extent()) });
~~~~~~~~~ ^
Is there a way to create a BoundaryConditions::repeat_edge on an Input<Func>?
There is, associate a Buffer<> with it. (Maybe a Buffer in your case, try it out).
struct MyGen : Generator<MyGen> {
Input<Buffer<>> dim_only_input_buffer{ "dim_only_input_buffer", 3 };
...
};
I ran into something similar, you can see more about this in this github issue
The idea of Input<Func> is that it may be instantiated with another Func when composing generators together. (E.g. the output of one generator may be the input to another and the graph of all connected generators is compiled as a single Halide program.) The problem is Funcs do not have fixed bounds like Buffers do. Hence one cannot ask for (e.g.) the width of a Func.
For a generator which is designed to always be used with concrete memory, one can use Input. To impose a boundary condition on an Input, the bounds need to be passed as explicit parameters to the generator. E.g. as other Inputs.

Random function in Modelica

Hello,I need a function as random in C language. Maybe you will say that i can call C function, but the effect is not the same in visual c++ tool. So, I need your help.
thanks.
See the Noise library:
https://github.com/DLR-SR/Noise
It has some models and functions to generate random numbers.
If you are using Dymola, you can use the function rand():
model rand_model
Real a(start=rand());
Real b(start=rand());
equation
when (sample(1,1)) then
a = rand();
b = rand();
end when;
end rand_model;
The function is not documented in the Dymola user manual and it is no part of the modelica standard. The output seems to be an integer between 0 and 32767, seed seems to be constant.
Perhaps the implementation is given in the moutil.c file which is shipped with Dymola. But i'm not sure.

Resources