Basically I have a ufunc that requires some randomness. In order to keep the ufuncs as reproducible as possible I would like to use numpy's random number generator for that; basically because setting the seed will be more intuitive this way.
However I cannot find the documentation of the numpy.random C-API (does it have one?).
My current approach looks like that:
#include <numpy/random.h> // does not exist
...
static void
ufunc_M( char ** args
, npy_intp * dimensions
, npy_intp * steps
, void * data)
{
basic_gate_argument_t argument = *((basic_gate_argument_t *) data);
PYQCS_GATE_GENERIC_SETUP;
npy_intp i;
npy_double amplitude_1 = 0;
for(i = 0; i < ndim; i++)
{
if(i & (1 << argument.act))
{
amplitude_1 += qm_in[i].real * qm_in[i].real;
amplitude_1 += qm_in[i].imag * qm_in[i].imag;
}
}
npy_double rand = random_uniform(0, 1); // does not exist
...
*measured_out = 1 << argument.act;
}
...
As it turns out: one cannot do it using the numpy.random
library directly. I found out about that after searching the numpy headers for a while. The random library is just not exported.
My workaround is passing a python callable to the ufunc:
static void
ufunc_M( char ** args
, npy_intp * dimensions
, npy_intp * steps
, void * data)
{
basic_gate_argument_t argument = *((basic_gate_argument_t *) data);
PYQCS_GATE_GENERIC_SETUP;
npy_intp i;
...
npy_double randr;
//==================================================//
// Get some random value. I do not like the way this
// is done but it seems like there is no better way.
PyObject * random_result = PyObject_CallFunctionObjArgs(argument.rng, NULL);
if(!PyFloat_Check(random_result))
{
randr = 0;
}
else
{
randr = PyFloat_AsDouble(random_result);
}
Py_DECREF(random_result);
//==================================================//
...
}
One must check wheter the passed object is a callable when constructing the ufunc:
static int
BasicGate_init
( BasicGate * self
, PyObject * args)
{
char type;
if(!PyArg_ParseTuple(args, "ClldO"
, &type
, &(self->argument.act)
, &(self->argument.control)
, &(self->argument.r)
, &(self->argument.rng))
)
{
return -1;
}
if(!PyCallable_Check(self->argument.rng))
{
PyErr_SetString(PyExc_TypeError, "random (5th argument) must be a callable (returning float)");
return -1;
}
...
case 'M':
{
self->ufunc = PyUFunc_FromFuncAndDataAndSignature(
ufunc_M_funcs // func
, self->data // data
, ufunc_types //types
, 1 // ntypes
, 2 // nin
, 3 // nout
, PyUFunc_None // identity
, "M_function" // name
, "Computes the M (Measurement) gate on a state." // doc
, 0 // unused
, "(n),(m)->(n),(m),()");
...
}
Ufuncs however cannot fail, so when the passed function does not return PyFloat
s the ufunc will produce nonsense.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.