| 1 |
""" |
| 2 |
Implementation of `BinomialFunction` |
| 3 |
""" |
| 4 |
|
| 5 |
import numpy as np |
| 6 |
|
| 7 |
from brian2.core.base import Nameable |
| 8 |
from brian2.core.functions import DEFAULT_FUNCTIONS, Function |
| 9 |
from brian2.units.fundamentalunits import check_units |
| 10 |
from brian2.utils.stringtools import replace |
| 11 |
|
| 12 |
__all__ = ["BinomialFunction"] |
| 13 |
|
| 14 |
|
| 15 |
def _pre_calc_constants_approximated(n, p): |
| 16 |
loc = n * p |
| 17 |
scale = np.sqrt(n * p * (1 - p)) |
| 18 |
return loc, scale |
| 19 |
|
| 20 |
|
| 21 |
def _pre_calc_constants(n, p): |
| 22 |
reverse = p > 0.5 |
| 23 |
if reverse: |
| 24 |
P = 1.0 - p |
| 25 |
else: |
| 26 |
P = p |
| 27 |
q = 1.0 - P |
| 28 |
qn = np.exp(n * np.log(q)) |
| 29 |
bound = min(n, n * P + 10.0 * np.sqrt(n * P * q + 1)) |
| 30 |
return reverse, q, P, qn, bound |
| 31 |
|
| 32 |
|
| 33 |
def _generate_cython_code(n, p, use_normal, name): |
| 34 |
# Cython implementation |
| 35 |
# Inversion transform sampling |
| 36 |
if use_normal: |
| 37 |
loc, scale = _pre_calc_constants_approximated(n, p) |
| 38 |
cython_code = """ |
| 39 |
cdef float %NAME%(const int vectorisation_idx): |
| 40 |
return _randn(vectorisation_idx) * %SCALE% + %LOC% |
| 41 |
""" |
| 42 |
cython_code = replace( |
| 43 |
cython_code, |
| 44 |
{"%SCALE%": f"{scale:.15f}", "%LOC%": f"{loc:.15f}", "%NAME%": name}, |
| 45 |
) |
| 46 |
dependencies = {"_randn": DEFAULT_FUNCTIONS["randn"]} |
| 47 |
else: |
| 48 |
reverse, q, P, qn, bound = _pre_calc_constants(n, p) |
| 49 |
# The following code is an almost exact copy of numpy's |
| 50 |
# rk_binomial_inversion function |
| 51 |
# (numpy/random/mtrand/distributions.c) |
| 52 |
cython_code = """ |
| 53 |
cdef long %NAME%(const int vectorisation_idx): |
| 54 |
cdef long X = 0 |
| 55 |
cdef double px = %QN% |
| 56 |
cdef double U = _rand(vectorisation_idx) |
| 57 |
while U > px: |
| 58 |
X += 1 |
| 59 |
if X > %BOUND%: |
| 60 |
X = 0 |
| 61 |
px = %QN% |
| 62 |
U = _rand(vectorisation_idx) |
| 63 |
else: |
| 64 |
U -= px |
| 65 |
px = ((%N%-X+1) * %P% * px)/(X*%Q%) |
| 66 |
return %RETURN_VALUE% |
| 67 |
""" |
| 68 |
cython_code = replace( |
| 69 |
cython_code, |
| 70 |
{ |
| 71 |
"%N%": f"{int(n)}", |
| 72 |
"%P%": f"{p:.15f}", |
| 73 |
"%Q%": f"{q:.15f}", |
| 74 |
"%QN%": f"{qn:.15f}", |
| 75 |
"%BOUND%": f"{bound:.15f}", |
| 76 |
"%RETURN_VALUE%": f"{int(n)}-X" if reverse else "X", |
| 77 |
"%NAME%": name, |
| 78 |
}, |
| 79 |
) |
| 80 |
dependencies = {"_rand": DEFAULT_FUNCTIONS["rand"]} |
| 81 |
|
| 82 |
return cython_code, dependencies |
| 83 |
|
| 84 |
|
| 85 |
def _generate_cpp_code(n, p, use_normal, name): |
| 86 |
# C++ implementation |
| 87 |
# Inversion transform sampling |
| 88 |
if use_normal: |
| 89 |
loc, scale = _pre_calc_constants_approximated(n, p) |
| 90 |
cpp_code = """ |
| 91 |
float %NAME%(const int vectorisation_idx) |
| 92 |
{ |
| 93 |
return _randn(vectorisation_idx) * %SCALE% + %LOC%; |
| 94 |
} |
| 95 |
""" |
| 96 |
cpp_code = replace( |
| 97 |
cpp_code, |
| 98 |
{"%SCALE%": f"{scale:.15f}", "%LOC%": f"{loc:.15f}", "%NAME%": name}, |
| 99 |
) |
| 100 |
dependencies = {"_randn": DEFAULT_FUNCTIONS["randn"]} |
| 101 |
else: |
| 102 |
reverse, q, P, qn, bound = _pre_calc_constants(n, p) |
| 103 |
# The following code is an almost exact copy of numpy's |
| 104 |
# rk_binomial_inversion function |
| 105 |
# (numpy/random/mtrand/distributions.c) |
| 106 |
cpp_code = """ |
| 107 |
long %NAME%(const int vectorisation_idx) |
| 108 |
{ |
| 109 |
long X = 0; |
| 110 |
double px = %QN%; |
| 111 |
double U = _rand(vectorisation_idx); |
| 112 |
while (U > px) |
| 113 |
{ |
| 114 |
X++; |
| 115 |
if (X > %BOUND%) |
| 116 |
{ |
| 117 |
X = 0; |
| 118 |
px = %QN%; |
| 119 |
U = _rand(vectorisation_idx); |
| 120 |
} else |
| 121 |
{ |
| 122 |
U -= px; |
| 123 |
px = ((%N%-X+1) * %P% * px)/(X*%Q%); |
| 124 |
} |
| 125 |
} |
| 126 |
return %RETURN_VALUE%; |
| 127 |
} |
| 128 |
""" |
| 129 |
cpp_code = replace( |
| 130 |
cpp_code, |
| 131 |
{ |
| 132 |
"%N%": f"{int(n)}", |
| 133 |
"%P%": f"{P:.15f}", |
| 134 |
"%Q%": f"{q:.15f}", |
| 135 |
"%QN%": f"{qn:.15f}", |
| 136 |
"%BOUND%": f"{bound:.15f}", |
| 137 |
"%RETURN_VALUE%": f"{int(n)}-X" if reverse else "X", |
| 138 |
"%NAME%": name, |
| 139 |
}, |
| 140 |
) |
| 141 |
dependencies = {"_rand": DEFAULT_FUNCTIONS["rand"]} |
| 142 |
|
| 143 |
return {"support_code": cpp_code}, dependencies |
| 144 |
|
| 145 |
|
| 146 |
class BinomialFunction(Function, Nameable): |
| 147 |
r""" |
| 148 |
BinomialFunction(n, p, approximate=True, name='_binomial*') |
| 149 |
|
| 150 |
A function that generates samples from a binomial distribution. |
| 151 |
|
| 152 |
Parameters |
| 153 |
---------- |
| 154 |
n : int |
| 155 |
Number of samples |
| 156 |
p : float |
| 157 |
Probablility |
| 158 |
approximate : bool, optional |
| 159 |
Whether to approximate the binomial with a normal distribution if |
| 160 |
:math:`n p > 5 \wedge n (1 - p) > 5`. Defaults to ``True``. |
| 161 |
""" |
| 162 |
|
| 163 |
#: Container for implementing functions for different targets |
| 164 |
#: This container can be extended by other codegeneration targets/devices |
| 165 |
#: The key has to be the name of the target, the value a function |
| 166 |
#: that takes three parameters (n, p, use_normal) and returns a tuple of |
| 167 |
#: (code, dependencies) |
| 168 |
implementations = {"cpp": _generate_cpp_code, "cython": _generate_cython_code} |
| 169 |
|
| 170 |
@check_units(n=1, p=1) |
| 171 |
def __init__(self, n, p, approximate=True, name="_binomial*"): |
| 172 |
Nameable.__init__(self, name) |
| 173 |
|
| 174 |
# Python implementation |
| 175 |
use_normal = approximate and (n * p > 5) and n * (1 - p) > 5 |
| 176 |
if use_normal: |
| 177 |
loc = n * p |
| 178 |
scale = np.sqrt(n * p * (1 - p)) |
| 179 |
|
| 180 |
def sample_function(vectorisation_idx): |
| 181 |
try: |
| 182 |
N = len(vectorisation_idx) |
| 183 |
except TypeError: |
| 184 |
N = int(vectorisation_idx) |
| 185 |
return np.random.normal(loc, scale, size=N) |
| 186 |
|
| 187 |
else: |
| 188 |
|
| 189 |
def sample_function(vectorisation_idx): |
| 190 |
try: |
| 191 |
N = len(vectorisation_idx) |
| 192 |
except TypeError: |
| 193 |
N = int(vectorisation_idx) |
| 194 |
return np.random.binomial(n, p, size=N) |
| 195 |
|
| 196 |
Function.__init__( |
| 197 |
self, |
| 198 |
pyfunc=lambda: sample_function(1), |
| 199 |
arg_units=[], |
| 200 |
return_unit=1, |
| 201 |
stateless=False, |
| 202 |
auto_vectorise=True, |
| 203 |
) |
| 204 |
|
| 205 |
self.implementations.add_implementation("numpy", sample_function) |
| 206 |
|
| 207 |
for target, func in BinomialFunction.implementations.items(): |
| 208 |
code, dependencies = func(n=n, p=p, use_normal=use_normal, name=self.name) |
| 209 |
self.implementations.add_implementation( |
| 210 |
target, code, dependencies=dependencies, name=self.name |
| 211 |
) |