1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
|
.. _random:
Pseudo-Random Number Generation
-------------------------------
Pseudo-random numbers from a variety of distributions may be generated with the :class:`Random` class. Multiple random number generators are provided; low level access to the mcell_ran4 generator is described in:
.. toctree:: :maxdepth: 1
mcran4.rst
Random Class
============
.. class:: Random
Syntax:
``h.Random()``
``h.Random(seed)``
``h.Random(seed, size)``
Description:
The Random class provides commonly used random distributions which are
useful for stochastic
simulations. The default distribution is normal with mean = 0 and standard
deviation = 1.
This class is an interface to the RNG class
from the gnu c++ class library. As of version 5.2, a cryptographic quality
RNG class wrapper for :func:`mcell_ran4` was added and is available
with the :meth:`Random.MCellRan4` method. The current default random generator
is :meth:`Random.ACG`.
As of version 7.3, a more versatile cryptographic quality generator,
Random123, is available with the :meth:`Random.Random123` method. This generator
uses a 34bit counter, up to 3 32 bit identifiers, and a 32 bit global index and
is most suitable for managing separate independent, reproducible, restartable
streams that are unique to individual cell and synapses in large parallel
network models.
See: http://www.thesalmons.org/john/random123/papers/random123sc11.pdf
Note that multiple instances of the Random class will produce different
streams of random numbers only if their seeds are different.
One can switch distributions at any time but if the distribution is
stationary then it is more efficient to use :meth:`Random.repick` to avoid
constructor/destructor overhead.
Example:
.. code-block::
python
from neuron import h
r = h.Random()
for i in range(10):
print(r.uniform(30, 50)) # not as efficient as
for i in range(10):
print(r.repick()) # this
prints 20 random numbers ranging in value between 30 and 50.
----
.. method:: Random.ACG
Syntax:
``r.ACG()``
``r.ACG(seed)``
``r.ACG(seed, size)``
Description:
Use a variant of the Linear Congruential Generator (algorithm M)
described in Knuth, Art of Computer Programming, Vol. III in
combination with a Fibonacci Additive Congruential Generator. This is
a "very high quality" random number generator, Default size is 55,
giving a size of 1244 bytes to the structure. Minimum size is 7 (total
100 bytes), maximum size is 98 (total 2440 bytes).
----
.. method:: Random.MLCG
Syntax:
``r.MLCG()``
``r.MLCG(seed1)``
``r.MLCG(seed1, seed2)``
Description:
Use a Multiplicative Linear Congruential Generator. Not as high
quality as the ACG. It uses only 8 bytes.
----
.. method:: Random.MCellRan4
Syntax:
``highindex = r.MCellRan4()``
``highindex = r.MCellRan4(highindex)``
``highindex = r.MCellRan4(highindex, lowindex)``
Description:
Use the MCell variant of the Ran4 generator. See :func:`mcell_ran4`.
In the no argument case or if the highindex is 0, then the system selects
an index which is the random 32 bit integer resulting from
an mcell_ran4 call with an index equal to the
the number of instances of the Random generator that had been created.
Thus, each stream should be statistically independent as long as the
highindex values differ by more than the eventual length of the stream.
In any case, the
initial highindex is returned and can be used to restart an instance
of the generator. Use :func:`mcell_ran4_init` to set the (global)
low 32 bit index of the generator. The :meth:`Random.seq` method is useful
for getting the current sequence number and restarting at that sequence
number (highindex).
If the lowindex arg is present and nonzero, then that lowindex is used
instead of the global one specified by :func:`mcell_ran4_init`.
This allows 2^32-1 independent streams that do not overlap.
Note that for reproducibility,
the distribution should be defined AFTER setting the seed since some
distributions, such as :meth:`Random.normal`, hold state information from
a previous pick from the uniform distribution.
.. seealso::
:meth:`Random.Random123`
Example:
.. code-block::
python
from neuron import h, gui
r = h.Random()
index = h.ref(r.MCellRan4())
r.uniform(0, 2)
vec = h.Vector(1000)
g1 = h.Graph()
g2 = h.Graph()
g1.size(0, 1000, 0, 2)
g2.size(0, 2, 0, 150)
def doit():
g1.erase()
g2.erase()
vec.setrand(r)
hist = vec.histogram(0, 2, 0.2)
vec.line(g1)
hist.line(g2, .2)
g1.flush()
g2.flush()
def set_index_then_doit():
r.MCellRan4(index[0])
doit()
doit()
h.xpanel("MCellRan4 test")
h.xbutton("Sample", doit)
h.xvalue("Original index", index, 1, set_index_then_doit)
h.xpanel()
.. image:: ../../images/random-mcellran4.png
:align: center
----
.. method:: Random.Random123
Syntax:
``0 = r.Random123(id1, id2, id3)``
Description:
Use the Random123 generator (currently philox4x32 is the crypotgraphic hash
used) with the stream identified by the identifiers 0 <= id1,2,3 < 2^32
and the global index (see :meth:`Random.Random123_globalindex`). The counter,
which increments from 0 to 2^34-1, is initialized to 0 (see :meth:`Random.seq`).
If any of the up to 3 arguments are missing, it is assumed 0.
The generators should be usable in the context of threads as long as
no instance is used in more than one thread.
This generator
uses a 34bit counter, 3 32 bit identifiers, and a 32 bit global index and
is most suitable for managing separate independent, reproducible, restartable
streams that are unique to individual cell and synapses in large parallel
network models.
See: http://www.thesalmons.org/john/random123/papers/random123sc11.pdf
----
.. method:: Random.Random123_globalindex
Syntax:
``uint32 = r.Random123_globalindex([uint32])``
Description:
Gets and sets the global index used by all instances of the Random123
instances of Random.
----
.. method:: Random.seq
Syntax:
``currenthighindex = r.seq()``
``r.seq(sethighindex)``
Description:
For MCellRan4,
Gets and sets the current highindex value when the :meth:`Random.MCellRan4` is
in use. This allows restarting the generator at any specified point.
Note that the currenthighindex value is incremented every :meth:`Random.repick`.
Usually the increment is 1 but some distributions, e.g. :meth:`Random.poisson`
can increment by more. Also, some distributions, e.g. :meth:`Random.normal`,
pick twice on the first repick but once thereafter.
For Random123,
Gets and sets the counter value which ranges from 0 to 2^34-1.
The reason the the greater range is that the internal Random123 generators
return 4 uint32 values on each call. So that is done only every 4 picks from
the generator.
Example:
.. code-block::
python
from neuron import h
r = h.Random()
r.negexp(1)
h.mcell_ran4_init(1)
r.MCellRan4(1)
for i in range(11):
print('{} {}'.format(i, r.repick()))
r.MCellRan4(1)
for i in range(6):
print('%d %g' % (i, r.repick()))
idum = r.seq()
print("idum = {}".format(idum ))
for i in range(6, 11):
print('{} {}'.format(i, r.repick()))
print("restarting")
r.seq(idum)
for i in range(6, 11):
print('{} {}'.format(i, r.repick()))
print("restarting")
r.seq(idum)
for i in range(6, 11):
print('{} {}'.format(i, r.repick()))
Output:
.. code-block::
None
0 1.51709661466
1 0.485175784418
2 0.212032709823
3 0.503178330905
4 0.114339664628
5 1.28075206782
6 0.0578608361212
7 0.26376087479
8 0.291156947261
9 3.21937205675
10 0.409557452659
0 1.51709661466
1 0.485175784418
2 0.212032709823
3 0.503178330905
4 0.114339664628
5 1.28075206782
idum = 7.0
6 0.0578608361212
7 0.26376087479
8 0.291156947261
9 3.21937205675
10 0.409557452659
restarting
6 0.0578608361212
7 0.26376087479
8 0.291156947261
9 3.21937205675
10 0.409557452659
restarting
6 0.0578608361212
7 0.26376087479
8 0.291156947261
9 3.21937205675
10 0.409557452659
----
.. method:: Random.repick
Syntax:
``r.repick()``
Description:
Pick again from the distribution last used.
----
.. method:: Random.play
Syntax:
``r.play(_ref_var)``
Description:
At the beginning of every call to :func:`fadvance` and :func:`finitialize` var is set
to a new value equivalent to
.. code-block::
none
var = r.repick()
(but with no interpreter overhead). This is similar in concept to :meth:`Vector.play`.
Play may be called several times for different variables and each variable
will get an independent random value but with the same distribution.
To disconnect the Random object from its list of variables, either the variables
or the Random object must be destroyed.
Example:
.. code-block::
python
from neuron import h
r = h.Random()
# set the distribution
r.uniform(0, 1)
# create a reference, and have the uniform random variable update it at each time step
rv = h.ref(0)
r.play(rv)
# print some random numbers
for i in range(5):
h.fadvance()
print(rv[0])
More practically, this might be used with a fixed time step to set, say, ``h.IClamp[0]._ref_amp`` for a random current injection.
----
.. method:: Random.uniform
Syntax:
``r.uniform(low, high)``
Description:
Create a uniform random variable over the open interval (*low*...\ *high*).
See examples of this in :meth:`Random.MCellRan4` and :meth:`Random.play`.
----
.. method:: Random.discunif
Syntax:
``r.discunif(low, high)``
Description:
Create a uniform random variable over the discrete integers from
low to high.
----
.. method:: Random.normal
Syntax:
``r.normal(mean, variance)``
Description:
Gaussian distribution.
Example:
.. code-block::
python
from neuron import h, gui
r = h.Random()
r.normal(-1, .5)
vec = h.Vector()
vec.indgen(-3, 2, .1) # x-axis for plot
hist = h.Vector(vec.size())
g = h.Graph()
g.size(-3, 2, 0, 50)
hist.plot(g, vec)
for i in range(500):
x = r.repick()
print('%d %g' % (i, x))
j = int((x+3)*10) # -3 to 2 -> 0 to 50
if j >= 0:
hist[j] += 1
g.flush()
h.doNotify()
.. image:: ../../images/random-normal.png
:align: center
----
.. method:: Random.lognormal
Syntax:
``r.lognormal(mean, variance)``
Description:
Create a logarithmic normal distribution.
Example:
.. code-block::
python
from neuron import h, gui
r = h.Random()
r.lognormal(5,2)
n=20
xvec = h.Vector(n*3) # bins look like discrete spikes
for i in range(n):
xvec[3*i] = i - 0.1
xvec[3*i+1] = i
xvec[3*i+2] = i + .1
hist = h.Vector(xvec.size())
g = h.Graph()
g.size(0, 15, 0, 120)
hist.plot(g, xvec)
for i in range(500):
x = r.repick()
print('%d %g' % (i, x))
j = 3 * int(x) + 1
if j >= hist.size(): # don't let any off the edge
j = hist.size() - 1
hist[j] = hist[j]+1
g.flush()
h.doNotify()
.. image:: ../../images/random-lognormal.png
:align: center
----
.. method:: Random.poisson
Syntax:
``r.poisson(mean)``
Description:
Create a poisson distribution.
Example:
.. code-block::
python
from neuron import h, gui
r = h.Random()
r.poisson(3)
n=20
xvec = h.Vector(n*3)
for i in range(n):
xvec[3*i] = i-.1
xvec[3*i+1] = i
xvec[3*i+2] = i+.1
hist = h.Vector(xvec.size())
g = h.Graph()
g.size(0, 15, 0, 120)
hist.plot(g, xvec)
for i in range(500):
x = r.repick()
print('%d %g' % (i, x))
j = int(x)
j = 3*j+1
if j >= hist.size():
j = hist.size() -1
hist[j] = hist[j]+1
g.flush()
h.doNotify()
.. image:: ../../images/random-poisson.png
:align: center
----
.. method:: Random.binomial
Syntax:
``r.binomial(N,p)``
Description:
Create a binomial distribution. Returns the number of "successes" after
*N* trials when the probability of a success after one trial is *p*.
(n>0, 0<=p<=1).
``P(n, N, p) = p * P(n-1, N-1, p) + (1 - p) * P(n, N-1, p)``
Example:
.. code-block::
python
from neuron import h, gui
r = h.Random()
r.binomial(20, .5)
g = h.Graph()
g.size(0, 20, 0, 100)
hist = h.Vector(20)
hist.plot(g)
for i in range(500):
j = int(r.repick()) # r.repick() always returns a float even though the binomial always is an integer
hist[j] += 1
g.flush()
h.doNotify()
.. image:: ../../images/random-binomial.png
:align: center
----
.. method:: Random.geometric
Syntax:
``r.geometric(mean)``
Description:
Create a discrete geometric distribution.
Given 0<=*mean*<=1, return the number of uniform random samples
that were drawn before the sample was larger than the *mean* (always
greater than 0).
Example:
.. code-block::
python
from neuron import h, gui
r = h.Random()
r.geometric(.8)
hist = new Vector(1000)
def sample():
hist = h.Vector(1000)
hist.setrand(r)
hist = hist.histogram(0,100,1)
hist.plot(g)
g = h.Graph()
g.size(0,40,0,200)
sample()
h.xpanel("Resample")
h.xbutton("Resample", sample)
h.xpanel()
.. image:: ../../images/random-geometric.png
:align: center
----
.. method:: Random.hypergeo
Syntax:
``r.hypergeo(mean,variance)``
Description:
Create a hypergeometric distribution.
----
.. method:: Random.negexp
Syntax:
``r.negexp(mean)``
Description:
Create a negative exponential distribution. Distributed as the intervals
between events in a poisson distribution.
Example:
.. code-block::
python
from neuron import h, gui
r = h.Random()
r.negexp(2.5)
hist = h.Vector(1000)
def sample():
hist = h.Vector(1000)
hist.setrand(r)
hist = hist.histogram(0,20,.1)
hist.plot(g, .1)
g = h.Graph()
g.size(0,20,0,50)
sample()
h.xpanel("Resample")
h.xbutton("Resample", sample)
h.xpanel()
.. image:: ../../images/random-negexp.png
:align: center
----
.. method:: Random.erlang
Syntax:
``r.erlang(mean,variance)``
Description:
Create an Erlang distribution.
----
.. method:: Random.weibull
Syntax:
``r.weibull(alpha,beta)``
Description:
Create a Weibull distribution.
|